xref: /btstack/src/hci.c (revision d58dd308876be384a30977c319debf9ba30c8d81)
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 
48aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
498f2a52f4SMatthias Ringwald #include "btstack_run_loop_embedded.h"
50a484130cSMatthias Ringwald #endif
51a484130cSMatthias Ringwald 
524a3574a1SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
53d0b87befSMatthias Ringwald #include "../port/ios/src/btstack_control_iphone.h"
544a3574a1SMatthias Ringwald #endif
554a3574a1SMatthias Ringwald 
56a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
57472a5742SMatthias Ringwald #include "gap.h"
5845c102fdSMatthias Ringwald #endif
5945c102fdSMatthias Ringwald 
6093b8dc03Smatthias.ringwald #include <stdarg.h>
6193b8dc03Smatthias.ringwald #include <string.h>
6256fe0872Smatthias.ringwald #include <stdio.h>
635838a2edSMatthias Ringwald #include <inttypes.h>
647f2435e6Smatthias.ringwald 
6516ece135SMatthias Ringwald #include "btstack_debug.h"
660e2df43fSMatthias Ringwald #include "btstack_event.h"
674a3574a1SMatthias Ringwald #include "btstack_linked_list.h"
684a3574a1SMatthias Ringwald #include "btstack_memory.h"
694a3574a1SMatthias Ringwald #include "gap.h"
704a3574a1SMatthias Ringwald #include "hci.h"
714a3574a1SMatthias Ringwald #include "hci_cmd.h"
72d8905019Smatthias.ringwald #include "hci_dump.h"
7393b8dc03Smatthias.ringwald 
741b0e3922Smatthias.ringwald 
75169f8b28Smatthias.ringwald #define HCI_CONNECTION_TIMEOUT_MS 10000
76ee091cf1Smatthias.ringwald 
77b83d5eabSMatthias Ringwald // prototypes
78758b46ceSmatthias.ringwald static void hci_update_scan_enable(void);
79a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
80ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
8196a45072S[email protected] static void hci_connection_timestamp(hci_connection_t *connection);
827586ee35S[email protected] static int  hci_power_control_on(void);
837586ee35S[email protected] static void hci_power_control_off(void);
846da48142SSean Wilson static void hci_state_reset(void);
85b83d5eabSMatthias Ringwald static void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status);
86b83d5eabSMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
87fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
88b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void);
89b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void);
90b83d5eabSMatthias Ringwald static void hci_emit_discoverable_enabled(uint8_t enabled);
91b83d5eabSMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
92b83d5eabSMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
93b83d5eabSMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
94b83d5eabSMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
95b83d5eabSMatthias Ringwald static void hci_notify_if_sco_can_send_now(void);
9695d71764SMatthias Ringwald static void hci_run(void);
9795d71764SMatthias Ringwald static int  hci_is_le_connection(hci_connection_t * connection);
9895d71764SMatthias Ringwald static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
9995d71764SMatthias Ringwald static int  hci_local_ssp_activated(void);
10095d71764SMatthias Ringwald static int  hci_remote_ssp_supported(hci_con_handle_t con_handle);
1015d509858SMatthias Ringwald 
102a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
10339677e66SMatthias Ringwald // called from test/ble_client/advertising_data_parser.c
10439677e66SMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, int size);
10542ff5ba1SMatthias Ringwald static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address);
1065d509858SMatthias Ringwald #endif
107758b46ceSmatthias.ringwald 
10806b35ec0Smatthias.ringwald // the STACK is here
1093a9fb326S[email protected] #ifndef HAVE_MALLOC
1103a9fb326S[email protected] static hci_stack_t   hci_stack_static;
1113a9fb326S[email protected] #endif
1123a9fb326S[email protected] static hci_stack_t * hci_stack = NULL;
11316833f0aSmatthias.ringwald 
11466fb9560S[email protected] // test helper
11566fb9560S[email protected] static uint8_t disable_l2cap_timeouts = 0;
11666fb9560S[email protected] 
11796a45072S[email protected] /**
11896a45072S[email protected]  * create connection for given address
11996a45072S[email protected]  *
12096a45072S[email protected]  * @return connection OR NULL, if no memory left
12196a45072S[email protected]  */
12296a45072S[email protected] static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
1231a06f663S[email protected]     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
124bb69aaaeS[email protected]     hci_connection_t * conn = btstack_memory_hci_connection_get();
12596a45072S[email protected]     if (!conn) return NULL;
126c91d150bS[email protected]     memset(conn, 0, sizeof(hci_connection_t));
127058e3d6bSMatthias Ringwald     bd_addr_copy(conn->address, addr);
12896a45072S[email protected]     conn->address_type = addr_type;
12996a45072S[email protected]     conn->con_handle = 0xffff;
13096a45072S[email protected]     conn->authentication_flags = AUTH_FLAGS_NONE;
13196a45072S[email protected]     conn->bonding_flags = 0;
13296a45072S[email protected]     conn->requested_security_level = LEVEL_0;
13391a977e8SMatthias Ringwald     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
13491a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&conn->timeout, conn);
13596a45072S[email protected]     hci_connection_timestamp(conn);
13696a45072S[email protected]     conn->acl_recombination_length = 0;
13796a45072S[email protected]     conn->acl_recombination_pos = 0;
13896a45072S[email protected]     conn->num_acl_packets_sent = 0;
1391a06f663S[email protected]     conn->num_sco_packets_sent = 0;
140da886c03S[email protected]     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
141665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
14296a45072S[email protected]     return conn;
14396a45072S[email protected] }
14466fb9560S[email protected] 
145da886c03S[email protected] 
146da886c03S[email protected] /**
147da886c03S[email protected]  * get le connection parameter range
148da886c03S[email protected] *
149da886c03S[email protected]  * @return le connection parameter range struct
150da886c03S[email protected]  */
1514ced4e8cSMatthias Ringwald void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
1524ced4e8cSMatthias Ringwald     *range = hci_stack->le_connection_parameter_range;
153da886c03S[email protected] }
154da886c03S[email protected] 
155da886c03S[email protected] /**
156da886c03S[email protected]  * set le connection parameter range
157da886c03S[email protected]  *
158da886c03S[email protected]  */
159da886c03S[email protected] 
1604ced4e8cSMatthias Ringwald void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
1614ced4e8cSMatthias Ringwald     hci_stack->le_connection_parameter_range = *range;
162da886c03S[email protected] }
163da886c03S[email protected] 
164da886c03S[email protected] /**
165da886c03S[email protected]  * get hci connections iterator
166da886c03S[email protected]  *
167da886c03S[email protected]  * @return hci connections iterator
168da886c03S[email protected]  */
169da886c03S[email protected] 
170665d90f2SMatthias Ringwald void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
171665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(it, &hci_stack->connections);
172da886c03S[email protected] }
173da886c03S[email protected] 
17497addcc5Smatthias.ringwald /**
175ee091cf1Smatthias.ringwald  * get connection for a given handle
176ee091cf1Smatthias.ringwald  *
177ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
178ee091cf1Smatthias.ringwald  */
1795061f3afS[email protected] hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
180665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
181665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
182665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
183665d90f2SMatthias Ringwald         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1843ac2fe56S[email protected]         if ( item->con_handle == con_handle ) {
185da886c03S[email protected]             return item;
186ee091cf1Smatthias.ringwald         }
187ee091cf1Smatthias.ringwald     }
188ee091cf1Smatthias.ringwald     return NULL;
189ee091cf1Smatthias.ringwald }
190ee091cf1Smatthias.ringwald 
19196a45072S[email protected] /**
19296a45072S[email protected]  * get connection for given address
19396a45072S[email protected]  *
19496a45072S[email protected]  * @return connection OR NULL, if not found
19596a45072S[email protected]  */
1962e77e513S[email protected] hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t  addr, bd_addr_type_t addr_type){
197665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
198665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
199665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
200665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
20196a45072S[email protected]         if (connection->address_type != addr_type)  continue;
20296a45072S[email protected]         if (memcmp(addr, connection->address, 6) != 0) continue;
20362bda3fbS[email protected]         return connection;
20462bda3fbS[email protected]     }
20562bda3fbS[email protected]     return NULL;
20662bda3fbS[email protected] }
20762bda3fbS[email protected] 
208ec820d77SMatthias Ringwald static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
20991a977e8SMatthias Ringwald     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
210aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
211528a4a3bSMatthias Ringwald     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
212c785ef68Smatthias.ringwald         // connections might be timed out
213c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
214c785ef68Smatthias.ringwald     }
215f316a845SMatthias Ringwald #else
216528a4a3bSMatthias Ringwald     if (btstack_run_loop_get_time_ms() > connection->timestamp + HCI_CONNECTION_TIMEOUT_MS){
2175f26aadcSMatthias Ringwald         // connections might be timed out
2185f26aadcSMatthias Ringwald         hci_emit_l2cap_check_timeout(connection);
2195f26aadcSMatthias Ringwald     }
2205f26aadcSMatthias Ringwald #endif
221c785ef68Smatthias.ringwald }
222ee091cf1Smatthias.ringwald 
223ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
224aec7654dSMatthias Ringwald #ifdef HAVE_EMBEDDED_TICK
225528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_embedded_get_ticks();
226f316a845SMatthias Ringwald #else
227528a4a3bSMatthias Ringwald     connection->timestamp = btstack_run_loop_get_time_ms();
2285f26aadcSMatthias Ringwald #endif
229ee091cf1Smatthias.ringwald }
230ee091cf1Smatthias.ringwald 
23106b35ec0Smatthias.ringwald 
23228ca2b46S[email protected] inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
23328ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
23428ca2b46S[email protected] }
23528ca2b46S[email protected] 
23628ca2b46S[email protected] inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
23728ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
23828ca2b46S[email protected] }
23928ca2b46S[email protected] 
24028ca2b46S[email protected] 
24143bfb1bdSmatthias.ringwald /**
24280ca58a0Smatthias.ringwald  * add authentication flags and reset timer
24396a45072S[email protected]  * @note: assumes classic connection
2442e77e513S[email protected]  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
2457fde4af9Smatthias.ringwald  */
2467fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
2477fde4af9Smatthias.ringwald     bd_addr_t addr;
248724d70a2SMatthias Ringwald     reverse_bd_addr(bd_addr, addr);
2492e77e513S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2507fde4af9Smatthias.ringwald     if (conn) {
25128ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
25280ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
2537fde4af9Smatthias.ringwald     }
2547fde4af9Smatthias.ringwald }
2557fde4af9Smatthias.ringwald 
25680ca58a0Smatthias.ringwald int  hci_authentication_active_for_handle(hci_con_handle_t handle){
2575061f3afS[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
25880ca58a0Smatthias.ringwald     if (!conn) return 0;
2596724cd9eS[email protected]     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
2606724cd9eS[email protected]     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
2616724cd9eS[email protected]     return 0;
26280ca58a0Smatthias.ringwald }
26380ca58a0Smatthias.ringwald 
26415a95bd5SMatthias Ringwald void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
265a98592bcSMatthias Ringwald     if (hci_stack->link_key_db) {
266a98592bcSMatthias Ringwald         hci_stack->link_key_db->delete_link_key(addr);
267c12e46e7Smatthias.ringwald     }
268c12e46e7Smatthias.ringwald }
269c12e46e7Smatthias.ringwald 
27095d71764SMatthias Ringwald static int hci_is_le_connection(hci_connection_t * connection){
2710bf6344aS[email protected]     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
2720bf6344aS[email protected]     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
2730bf6344aS[email protected] }
2740bf6344aS[email protected] 
2757fde4af9Smatthias.ringwald 
2767fde4af9Smatthias.ringwald /**
27743bfb1bdSmatthias.ringwald  * count connections
27843bfb1bdSmatthias.ringwald  */
27940d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
28056c253c9Smatthias.ringwald     int count = 0;
281665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
282665d90f2SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
28343bfb1bdSmatthias.ringwald     return count;
28443bfb1bdSmatthias.ringwald }
285c8e4258aSmatthias.ringwald 
28695d71764SMatthias Ringwald static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
287ee303eddS[email protected] 
288ee303eddS[email protected]     int num_packets_sent_classic = 0;
289ee303eddS[email protected]     int num_packets_sent_le = 0;
290ee303eddS[email protected] 
291665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
292665d90f2SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
293998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
294ee303eddS[email protected]         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
295ee303eddS[email protected]             num_packets_sent_classic += connection->num_acl_packets_sent;
296ee303eddS[email protected]         } else {
297ee303eddS[email protected]             num_packets_sent_le += connection->num_acl_packets_sent;
298ee303eddS[email protected]         }
299ee303eddS[email protected]     }
300d999b54eSMatthias Ringwald     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
301ee303eddS[email protected]     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
302ee303eddS[email protected]     int free_slots_le = 0;
303ee303eddS[email protected] 
304ee303eddS[email protected]     if (free_slots_classic < 0){
3059da54300S[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);
306998906cdSmatthias.ringwald         return 0;
307998906cdSmatthias.ringwald     }
308ee303eddS[email protected] 
309ee303eddS[email protected]     if (hci_stack->le_acl_packets_total_num){
310ee303eddS[email protected]         // if we have LE slots, they are used
311ee303eddS[email protected]         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
312ee303eddS[email protected]         if (free_slots_le < 0){
3139da54300S[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);
314ee303eddS[email protected]             return 0;
315998906cdSmatthias.ringwald         }
316ee303eddS[email protected]     } else {
317ee303eddS[email protected]         // otherwise, classic slots are used for LE, too
318ee303eddS[email protected]         free_slots_classic -= num_packets_sent_le;
319ee303eddS[email protected]         if (free_slots_classic < 0){
3209da54300S[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);
321ee303eddS[email protected]             return 0;
322ee303eddS[email protected]         }
323ee303eddS[email protected]     }
324ee303eddS[email protected] 
325ee303eddS[email protected]     switch (address_type){
326ee303eddS[email protected]         case BD_ADDR_TYPE_UNKNOWN:
3272125de09SMatthias Ringwald             log_error("hci_number_free_acl_slots: unknown address type");
328ee303eddS[email protected]             return 0;
329ee303eddS[email protected] 
330ee303eddS[email protected]         case BD_ADDR_TYPE_CLASSIC:
331ee303eddS[email protected]             return free_slots_classic;
332ee303eddS[email protected] 
333ee303eddS[email protected]         default:
334cb00d3aaS[email protected]            if (hci_stack->le_acl_packets_total_num){
335ee303eddS[email protected]                return free_slots_le;
336ee303eddS[email protected]            }
337cb00d3aaS[email protected]            return free_slots_classic;
338cb00d3aaS[email protected]     }
339998906cdSmatthias.ringwald }
340998906cdSmatthias.ringwald 
3412125de09SMatthias Ringwald int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
3422125de09SMatthias Ringwald     // get connection type
3432125de09SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3442125de09SMatthias Ringwald     if (!connection){
3452125de09SMatthias Ringwald         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
3462125de09SMatthias Ringwald         return 0;
3472125de09SMatthias Ringwald     }
3482125de09SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
3492125de09SMatthias Ringwald }
3502125de09SMatthias Ringwald 
351701e3307SMatthias Ringwald static int hci_number_free_sco_slots(void){
352e35edcc1S[email protected]     int num_sco_packets_sent = 0;
353665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
354665d90f2SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
355e35edcc1S[email protected]         hci_connection_t * connection = (hci_connection_t *) it;
356e35edcc1S[email protected]         num_sco_packets_sent += connection->num_sco_packets_sent;
357e35edcc1S[email protected]     }
358e35edcc1S[email protected]     if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
359701e3307SMatthias Ringwald         log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
36044d0e3d5S[email protected]         return 0;
36144d0e3d5S[email protected]     }
362701e3307SMatthias Ringwald     // log_info("hci_number_free_sco_slots u", handle, num_sco_packets_sent);
363e35edcc1S[email protected]     return hci_stack->sco_packets_total_num - num_sco_packets_sent;
364e35edcc1S[email protected] }
36544d0e3d5S[email protected] 
366ac928cc2S[email protected] // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
367ac928cc2S[email protected] int hci_can_send_command_packet_now(void){
368ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
369ac928cc2S[email protected] 
370ac928cc2S[email protected]     // check for async hci transport implementations
371ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
372ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
373ac928cc2S[email protected]             return 0;
374ac928cc2S[email protected]         }
375ac928cc2S[email protected]     }
376ac928cc2S[email protected] 
377ac928cc2S[email protected]     return hci_stack->num_cmd_packets > 0;
378ac928cc2S[email protected] }
379ac928cc2S[email protected] 
3809d04d3a7SMatthias Ringwald static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
381ac928cc2S[email protected]     // check for async hci transport implementations
3829d04d3a7SMatthias Ringwald     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
3839d04d3a7SMatthias Ringwald     return hci_stack->hci_transport->can_send_packet_now(packet_type);
384ac928cc2S[email protected] }
3859d04d3a7SMatthias Ringwald 
3869d04d3a7SMatthias Ringwald static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
3879d04d3a7SMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
3889d04d3a7SMatthias Ringwald     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
389ac928cc2S[email protected] }
3909d04d3a7SMatthias Ringwald 
3919d04d3a7SMatthias Ringwald int hci_can_send_acl_classic_packet_now(void){
3929d04d3a7SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
3939d04d3a7SMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_CLASSIC);
3949d04d3a7SMatthias Ringwald }
3959d04d3a7SMatthias Ringwald 
3969d04d3a7SMatthias Ringwald int hci_can_send_acl_le_packet_now(void){
3979d04d3a7SMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
3989d04d3a7SMatthias Ringwald     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
3999d04d3a7SMatthias Ringwald }
4009d04d3a7SMatthias Ringwald 
4019d04d3a7SMatthias Ringwald int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
4029d04d3a7SMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
403e79abdd6S[email protected]     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
404ac928cc2S[email protected] }
405ac928cc2S[email protected] 
406ac928cc2S[email protected] int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
407ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
408ac928cc2S[email protected]     return hci_can_send_prepared_acl_packet_now(con_handle);
4096b4af23dS[email protected] }
4106b4af23dS[email protected] 
411701e3307SMatthias Ringwald int hci_can_send_prepared_sco_packet_now(void){
412d057580eSMatthias Ringwald     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
413ed361f5fSMatthias Ringwald     if (!hci_stack->synchronous_flow_control_enabled) return 1;
414701e3307SMatthias Ringwald     return hci_number_free_sco_slots() > 0;
41544d0e3d5S[email protected] }
41644d0e3d5S[email protected] 
417701e3307SMatthias Ringwald int hci_can_send_sco_packet_now(void){
418d057580eSMatthias Ringwald     if (hci_stack->hci_packet_buffer_reserved) return 0;
419701e3307SMatthias Ringwald     return hci_can_send_prepared_sco_packet_now();
42044d0e3d5S[email protected] }
42144d0e3d5S[email protected] 
422d057580eSMatthias Ringwald void hci_request_sco_can_send_now_event(void){
423d057580eSMatthias Ringwald     hci_stack->sco_waiting_for_can_send_now = 1;
424d057580eSMatthias Ringwald     hci_notify_if_sco_can_send_now();
425d057580eSMatthias Ringwald }
426d057580eSMatthias Ringwald 
42795d71764SMatthias Ringwald // used for internal checks in l2cap.c
428c8b9416aS[email protected] int hci_is_packet_buffer_reserved(void){
429c8b9416aS[email protected]     return hci_stack->hci_packet_buffer_reserved;
430c8b9416aS[email protected] }
431c8b9416aS[email protected] 
4326b4af23dS[email protected] // reserves outgoing packet buffer. @returns 1 if successful
4336b4af23dS[email protected] int hci_reserve_packet_buffer(void){
4349d14b626S[email protected]     if (hci_stack->hci_packet_buffer_reserved) {
4359d14b626S[email protected]         log_error("hci_reserve_packet_buffer called but buffer already reserved");
4369d14b626S[email protected]         return 0;
4379d14b626S[email protected]     }
4386b4af23dS[email protected]     hci_stack->hci_packet_buffer_reserved = 1;
4396b4af23dS[email protected]     return 1;
4406b4af23dS[email protected] }
4416b4af23dS[email protected] 
44268a0fcf7S[email protected] void hci_release_packet_buffer(void){
44368a0fcf7S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
44468a0fcf7S[email protected] }
44568a0fcf7S[email protected] 
4466b4af23dS[email protected] // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
4477f02f414SMatthias Ringwald static int hci_transport_synchronous(void){
4486b4af23dS[email protected]     return hci_stack->hci_transport->can_send_packet_now == NULL;
4496b4af23dS[email protected] }
4506b4af23dS[email protected] 
451452cf3bbS[email protected] static int hci_send_acl_packet_fragments(hci_connection_t *connection){
452452cf3bbS[email protected] 
453452cf3bbS[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);
454452cf3bbS[email protected] 
455452cf3bbS[email protected]     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
456452cf3bbS[email protected]     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
457452cf3bbS[email protected]     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
458452cf3bbS[email protected]         max_acl_data_packet_length = hci_stack->le_data_packets_length;
459452cf3bbS[email protected]     }
460452cf3bbS[email protected] 
461452cf3bbS[email protected]     // testing: reduce buffer to minimum
462452cf3bbS[email protected]     // max_acl_data_packet_length = 52;
463452cf3bbS[email protected] 
464d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments entered");
465d999b54eSMatthias Ringwald 
466452cf3bbS[email protected]     int err;
467452cf3bbS[email protected]     // multiple packets could be send on a synchronous HCI transport
468452cf3bbS[email protected]     while (1){
469452cf3bbS[email protected] 
470d999b54eSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop entered");
471d999b54eSMatthias Ringwald 
472452cf3bbS[email protected]         // get current data
473452cf3bbS[email protected]         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
474452cf3bbS[email protected]         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
475452cf3bbS[email protected]         int more_fragments = 0;
476452cf3bbS[email protected] 
477452cf3bbS[email protected]         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
478452cf3bbS[email protected]         if (current_acl_data_packet_length > max_acl_data_packet_length){
479452cf3bbS[email protected]             more_fragments = 1;
480452cf3bbS[email protected]             current_acl_data_packet_length = max_acl_data_packet_length;
481452cf3bbS[email protected]         }
482452cf3bbS[email protected] 
483452cf3bbS[email protected]         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
484452cf3bbS[email protected]         if (acl_header_pos > 0){
485f8fbdce0SMatthias Ringwald             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
486452cf3bbS[email protected]             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
487f8fbdce0SMatthias Ringwald             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
488452cf3bbS[email protected]         }
489452cf3bbS[email protected] 
490452cf3bbS[email protected]         // update header len
491f8fbdce0SMatthias Ringwald         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
492452cf3bbS[email protected] 
493452cf3bbS[email protected]         // count packet
494452cf3bbS[email protected]         connection->num_acl_packets_sent++;
495d999b54eSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %u)", more_fragments);
496d999b54eSMatthias Ringwald 
497d999b54eSMatthias Ringwald         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
498d999b54eSMatthias Ringwald         if (more_fragments){
499d999b54eSMatthias Ringwald             // update start of next fragment to send
500d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
501d999b54eSMatthias Ringwald         } else {
502d999b54eSMatthias Ringwald             // done
503d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_pos = 0;
504d999b54eSMatthias Ringwald             hci_stack->acl_fragmentation_total_size = 0;
505d999b54eSMatthias Ringwald         }
506452cf3bbS[email protected] 
507452cf3bbS[email protected]         // send packet
508452cf3bbS[email protected]         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
509452cf3bbS[email protected]         const int size = current_acl_data_packet_length + 4;
5105bb5bc3eS[email protected]         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
511452cf3bbS[email protected]         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
512452cf3bbS[email protected] 
513d999b54eSMatthias Ringwald         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %u)", more_fragments);
514d999b54eSMatthias Ringwald 
515452cf3bbS[email protected]         // done yet?
516452cf3bbS[email protected]         if (!more_fragments) break;
517452cf3bbS[email protected] 
518452cf3bbS[email protected]         // can send more?
519452cf3bbS[email protected]         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
520452cf3bbS[email protected]     }
521452cf3bbS[email protected] 
522d999b54eSMatthias Ringwald     log_debug("hci_send_acl_packet_fragments loop over");
523452cf3bbS[email protected] 
524d051460cS[email protected]     // release buffer now for synchronous transport
525203bace6S[email protected]     if (hci_transport_synchronous()){
526452cf3bbS[email protected]         hci_release_packet_buffer();
52763fa3374SMatthias Ringwald         // notify upper stack that it might be possible to send again
52863fa3374SMatthias Ringwald         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
529d6b06661SMatthias Ringwald         hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
530452cf3bbS[email protected]     }
531452cf3bbS[email protected] 
532452cf3bbS[email protected]     return err;
533452cf3bbS[email protected] }
534452cf3bbS[email protected] 
535826f7347S[email protected] // pre: caller has reserved the packet buffer
536826f7347S[email protected] int hci_send_acl_packet_buffer(int size){
5377856c818Smatthias.ringwald 
538452cf3bbS[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
539452cf3bbS[email protected] 
540826f7347S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
541826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
542826f7347S[email protected]         return 0;
543826f7347S[email protected]     }
544826f7347S[email protected] 
545d713a683S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
546d713a683S[email protected]     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
547d713a683S[email protected] 
548826f7347S[email protected]     // check for free places on Bluetooth module
549d713a683S[email protected]     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
550826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
55197b61c7bS[email protected]         hci_release_packet_buffer();
55297b61c7bS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
55397b61c7bS[email protected]     }
5546218e6f1Smatthias.ringwald 
5555061f3afS[email protected]     hci_connection_t *connection = hci_connection_for_handle( con_handle);
55697b61c7bS[email protected]     if (!connection) {
5575fa0b7cfS[email protected]         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
55897b61c7bS[email protected]         hci_release_packet_buffer();
55997b61c7bS[email protected]         return 0;
56097b61c7bS[email protected]     }
56156cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
56256cf178bSmatthias.ringwald 
563452cf3bbS[email protected]     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
5647856c818Smatthias.ringwald 
565452cf3bbS[email protected]     // setup data
566452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = size;
567452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
5686218e6f1Smatthias.ringwald 
569452cf3bbS[email protected]     return hci_send_acl_packet_fragments(connection);
570ee091cf1Smatthias.ringwald }
571ee091cf1Smatthias.ringwald 
57244d0e3d5S[email protected] // pre: caller has reserved the packet buffer
57344d0e3d5S[email protected] int hci_send_sco_packet_buffer(int size){
57444d0e3d5S[email protected] 
57544d0e3d5S[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
57644d0e3d5S[email protected] 
57744d0e3d5S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
57844d0e3d5S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
57944d0e3d5S[email protected]         return 0;
58044d0e3d5S[email protected]     }
58144d0e3d5S[email protected] 
58244d0e3d5S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
5834b3e1e19SMatthias Ringwald 
5844b3e1e19SMatthias Ringwald     // skip checks in loopback mode
5854b3e1e19SMatthias Ringwald     if (!hci_stack->loopback_mode){
58644d0e3d5S[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
58744d0e3d5S[email protected] 
58844d0e3d5S[email protected]         // check for free places on Bluetooth module
589701e3307SMatthias Ringwald         if (!hci_can_send_prepared_sco_packet_now()) {
59044d0e3d5S[email protected]             log_error("hci_send_sco_packet_buffer called but no free ACL buffers on controller");
59144d0e3d5S[email protected]             hci_release_packet_buffer();
59244d0e3d5S[email protected]             return BTSTACK_ACL_BUFFERS_FULL;
59344d0e3d5S[email protected]         }
59444d0e3d5S[email protected] 
595e35edcc1S[email protected]         // track send packet in connection struct
596e35edcc1S[email protected]         hci_connection_t *connection = hci_connection_for_handle( con_handle);
597e35edcc1S[email protected]         if (!connection) {
598e35edcc1S[email protected]             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
599e35edcc1S[email protected]             hci_release_packet_buffer();
600e35edcc1S[email protected]             return 0;
601e35edcc1S[email protected]         }
602e35edcc1S[email protected]         connection->num_sco_packets_sent++;
6034b3e1e19SMatthias Ringwald     }
60444d0e3d5S[email protected] 
60544d0e3d5S[email protected]     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
606543e835cSMatthias Ringwald     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
607543e835cSMatthias Ringwald 
608543e835cSMatthias Ringwald     if (hci_transport_synchronous()){
609543e835cSMatthias Ringwald         hci_release_packet_buffer();
61063fa3374SMatthias Ringwald         // notify upper stack that it might be possible to send again
61163fa3374SMatthias Ringwald         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
612d6b06661SMatthias Ringwald         hci_emit_event(&event[0], sizeof(event), 0);    // don't dump
613543e835cSMatthias Ringwald     }
614543e835cSMatthias Ringwald 
615543e835cSMatthias Ringwald     return err;
61644d0e3d5S[email protected] }
61744d0e3d5S[email protected] 
61816833f0aSmatthias.ringwald static void acl_handler(uint8_t *packet, int size){
6197856c818Smatthias.ringwald 
620e76a89eeS[email protected]     // log_info("acl_handler: size %u", size);
621e76a89eeS[email protected] 
6227856c818Smatthias.ringwald     // get info
6237856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
6245061f3afS[email protected]     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
6257856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
6267856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
6277856c818Smatthias.ringwald 
6287856c818Smatthias.ringwald     // ignore non-registered handle
6297856c818Smatthias.ringwald     if (!conn){
6309da54300S[email protected]         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
6317856c818Smatthias.ringwald         return;
6327856c818Smatthias.ringwald     }
6337856c818Smatthias.ringwald 
634e76a89eeS[email protected]     // assert packet is complete
6359ecc3e17S[email protected]     if (acl_length + 4 != size){
636e76a89eeS[email protected]         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
637e76a89eeS[email protected]         return;
638e76a89eeS[email protected]     }
639e76a89eeS[email protected] 
6407856c818Smatthias.ringwald     // update idle timestamp
6417856c818Smatthias.ringwald     hci_connection_timestamp(conn);
6427856c818Smatthias.ringwald 
6437856c818Smatthias.ringwald     // handle different packet types
6447856c818Smatthias.ringwald     switch (acl_flags & 0x03) {
6457856c818Smatthias.ringwald 
6467856c818Smatthias.ringwald         case 0x01: // continuation fragment
6477856c818Smatthias.ringwald 
6480ca847afS[email protected]             // sanity checks
6497856c818Smatthias.ringwald             if (conn->acl_recombination_pos == 0) {
6509da54300S[email protected]                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
6517856c818Smatthias.ringwald                 return;
6527856c818Smatthias.ringwald             }
6530ca847afS[email protected]             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
6540ca847afS[email protected]                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
6550ca847afS[email protected]                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
6560ca847afS[email protected]                 conn->acl_recombination_pos = 0;
6570ca847afS[email protected]                 return;
6580ca847afS[email protected]             }
6597856c818Smatthias.ringwald 
6607856c818Smatthias.ringwald             // append fragment payload (header already stored)
661ec6321eeS[email protected]             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
6627856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
6637856c818Smatthias.ringwald 
6649da54300S[email protected]             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
665decc01a8Smatthias.ringwald             //        conn->acl_recombination_pos, conn->acl_recombination_length);
6667856c818Smatthias.ringwald 
6677856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
6687856c818Smatthias.ringwald             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
669d6b06661SMatthias Ringwald                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
6707856c818Smatthias.ringwald                 // reset recombination buffer
6717856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
6727856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
6737856c818Smatthias.ringwald             }
6747856c818Smatthias.ringwald             break;
6757856c818Smatthias.ringwald 
6767856c818Smatthias.ringwald         case 0x02: { // first fragment
6777856c818Smatthias.ringwald 
67823a77e1aS[email protected]             // sanity check
67923a77e1aS[email protected]             if (conn->acl_recombination_pos) {
68023a77e1aS[email protected]                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
68123a77e1aS[email protected]                 conn->acl_recombination_pos = 0;
68223a77e1aS[email protected]             }
68323a77e1aS[email protected] 
6847856c818Smatthias.ringwald             // peek into L2CAP packet!
6857856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
6867856c818Smatthias.ringwald 
6879da54300S[email protected]             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
688decc01a8Smatthias.ringwald 
6897856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
6907856c818Smatthias.ringwald             if (acl_length >= l2cap_length + 4){
6917856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
692d6b06661SMatthias Ringwald                 hci_emit_acl_packet(packet, acl_length + 4);
6937856c818Smatthias.ringwald             } else {
6940ca847afS[email protected] 
6950ca847afS[email protected]                 if (acl_length > HCI_ACL_BUFFER_SIZE){
6960ca847afS[email protected]                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
6970ca847afS[email protected]                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
6980ca847afS[email protected]                     return;
6990ca847afS[email protected]                 }
7000ca847afS[email protected] 
7017856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
702ec6321eeS[email protected]                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
7037856c818Smatthias.ringwald                 conn->acl_recombination_pos    = acl_length + 4;
7047856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
705f8fbdce0SMatthias Ringwald                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
7067856c818Smatthias.ringwald             }
7077856c818Smatthias.ringwald             break;
7087856c818Smatthias.ringwald 
7097856c818Smatthias.ringwald         }
7107856c818Smatthias.ringwald         default:
7119da54300S[email protected]             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
7127856c818Smatthias.ringwald             return;
7137856c818Smatthias.ringwald     }
71494ab26f8Smatthias.ringwald 
71594ab26f8Smatthias.ringwald     // execute main loop
71694ab26f8Smatthias.ringwald     hci_run();
71716833f0aSmatthias.ringwald }
71822909952Smatthias.ringwald 
71967a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
7209da54300S[email protected]     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
7213c4d4b90Smatthias.ringwald 
722528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&conn->timeout);
723c785ef68Smatthias.ringwald 
724665d90f2SMatthias Ringwald     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
725a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
7263c4d4b90Smatthias.ringwald 
7273c4d4b90Smatthias.ringwald     // now it's gone
728c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
729c7e0c5f6Smatthias.ringwald }
730c7e0c5f6Smatthias.ringwald 
7310c042179S[email protected] static const uint16_t packet_type_sizes[] = {
7328f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
7338f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
7348f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
7358f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
7368f8108aaSmatthias.ringwald };
73765389bfcS[email protected] static const uint8_t  packet_type_feature_requirement_bit[] = {
73865389bfcS[email protected]      0, // 3 slot packets
73965389bfcS[email protected]      1, // 5 slot packets
74065389bfcS[email protected]     25, // EDR 2 mpbs
74165389bfcS[email protected]     26, // EDR 3 mbps
74265389bfcS[email protected]     39, // 3 slot EDR packts
74365389bfcS[email protected]     40, // 5 slot EDR packet
74465389bfcS[email protected] };
74565389bfcS[email protected] static const uint16_t packet_type_feature_packet_mask[] = {
74665389bfcS[email protected]     0x0f00, // 3 slot packets
74765389bfcS[email protected]     0xf000, // 5 slot packets
74865389bfcS[email protected]     0x1102, // EDR 2 mpbs
74965389bfcS[email protected]     0x2204, // EDR 3 mbps
75065389bfcS[email protected]     0x0300, // 3 slot EDR packts
75165389bfcS[email protected]     0x3000, // 5 slot EDR packet
75265389bfcS[email protected] };
7538f8108aaSmatthias.ringwald 
75465389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
75565389bfcS[email protected]     // enable packet types based on size
7568f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
757f16a69bbS[email protected]     unsigned int i;
7588f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
7598f8108aaSmatthias.ringwald         if (packet_type_sizes[i] == 0) continue;
7608f8108aaSmatthias.ringwald         if (packet_type_sizes[i] <= buffer_size){
7618f8108aaSmatthias.ringwald             packet_types |= 1 << i;
7628f8108aaSmatthias.ringwald         }
7638f8108aaSmatthias.ringwald     }
76465389bfcS[email protected]     // disable packet types due to missing local supported features
76565389bfcS[email protected]     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
76665389bfcS[email protected]         int bit_idx = packet_type_feature_requirement_bit[i];
76765389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
76865389bfcS[email protected]         if (feature_set) continue;
76965389bfcS[email protected]         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
77065389bfcS[email protected]         packet_types &= ~packet_type_feature_packet_mask[i];
77165389bfcS[email protected]     }
7728f8108aaSmatthias.ringwald     // flip bits for "may not be used"
7738f8108aaSmatthias.ringwald     packet_types ^= 0x3306;
7748f8108aaSmatthias.ringwald     return packet_types;
7758f8108aaSmatthias.ringwald }
7768f8108aaSmatthias.ringwald 
7778f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
7783a9fb326S[email protected]     return hci_stack->packet_types;
7798f8108aaSmatthias.ringwald }
7808f8108aaSmatthias.ringwald 
781facf93fdS[email protected] uint8_t* hci_get_outgoing_packet_buffer(void){
7827dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
7833a9fb326S[email protected]     return hci_stack->hci_packet_buffer;
7847dc17943Smatthias.ringwald }
7857dc17943Smatthias.ringwald 
786f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
7873a9fb326S[email protected]     return hci_stack->acl_data_packet_length;
7887dc17943Smatthias.ringwald }
7897dc17943Smatthias.ringwald 
7906ac9a97eS[email protected] int hci_non_flushable_packet_boundary_flag_supported(void){
7916ac9a97eS[email protected]     // No. 54, byte 6, bit 6
7926ac9a97eS[email protected]     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
7936ac9a97eS[email protected] }
7946ac9a97eS[email protected] 
79515a95bd5SMatthias Ringwald static int gap_ssp_supported(void){
7966ac9a97eS[email protected]     // No. 51, byte 6, bit 3
7973a9fb326S[email protected]     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
798f5d8d141S[email protected] }
799f5d8d141S[email protected] 
8007f02f414SMatthias Ringwald static int hci_classic_supported(void){
8016ac9a97eS[email protected]     // No. 37, byte 4, bit 5, = No BR/EDR Support
8023a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
803f5d8d141S[email protected] }
804f5d8d141S[email protected] 
8057f02f414SMatthias Ringwald static int hci_le_supported(void){
806a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
8076ac9a97eS[email protected]     // No. 37, byte 4, bit 6 = LE Supported (Controller)
8083a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
809f5d8d141S[email protected] #else
810f5d8d141S[email protected]     return 0;
811f5d8d141S[email protected] #endif
812f5d8d141S[email protected] }
813f5d8d141S[email protected] 
81469a97523S[email protected] // get addr type and address used in advertisement packets
81515a95bd5SMatthias Ringwald void gap_advertisements_get_address(uint8_t * addr_type, bd_addr_t  addr){
8163a9fb326S[email protected]     *addr_type = hci_stack->adv_addr_type;
8173a9fb326S[email protected]     if (hci_stack->adv_addr_type){
8183a9fb326S[email protected]         memcpy(addr, hci_stack->adv_address, 6);
81969a97523S[email protected]     } else {
8203a9fb326S[email protected]         memcpy(addr, hci_stack->local_bd_addr, 6);
82169a97523S[email protected]     }
82269a97523S[email protected] }
82369a97523S[email protected] 
824a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
82539677e66SMatthias Ringwald void le_handle_advertisement_report(uint8_t *packet, int size){
826d1dc057bS[email protected]     int offset = 3;
827d1dc057bS[email protected]     int num_reports = packet[offset];
828d1dc057bS[email protected]     offset += 1;
829d1dc057bS[email protected] 
83057c9da5bS[email protected]     int i;
8314f4e0224SMatthias Ringwald     // log_info("HCI: handle adv report with num reports: %d", num_reports);
83203fbe9c6S[email protected]     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
83357c9da5bS[email protected]     for (i=0; i<num_reports;i++){
834210c6774S[email protected]         uint8_t data_length = packet[offset + 8];
835a0aac9c4S[email protected]         uint8_t event_size = 10 + data_length;
836d1dc057bS[email protected]         int pos = 0;
837045013feSMatthias Ringwald         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
83857c9da5bS[email protected]         event[pos++] = event_size;
839210c6774S[email protected]         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
840d1dc057bS[email protected]         offset += 8;
841d1dc057bS[email protected]         pos += 8;
842d1dc057bS[email protected]         event[pos++] = packet[offset + 1 + data_length]; // rssi
843d1dc057bS[email protected]         event[pos++] = packet[offset++]; //data_length;
844d1dc057bS[email protected]         memcpy(&event[pos], &packet[offset], data_length);
84557c9da5bS[email protected]         pos += data_length;
846d1dc057bS[email protected]         offset += data_length + 1; // rssi
847d6b06661SMatthias Ringwald         hci_emit_event(event, pos, 1);
84857c9da5bS[email protected]     }
84957c9da5bS[email protected] }
850b2f949feS[email protected] #endif
85157c9da5bS[email protected] 
85296b53536SMatthias Ringwald static uint32_t hci_transport_uart_get_main_baud_rate(void){
85396b53536SMatthias Ringwald     if (!hci_stack->config) return 0;
8549796ebeaSMatthias Ringwald     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
85596b53536SMatthias Ringwald     // Limit baud rate for Broadcom chipsets to 3 mbps
856c6d1dbedSMatthias Ringwald     if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION && baud_rate > 3000000){
85796b53536SMatthias Ringwald         baud_rate = 3000000;
85896b53536SMatthias Ringwald     }
85996b53536SMatthias Ringwald     return baud_rate;
86096b53536SMatthias Ringwald }
86196b53536SMatthias Ringwald 
862ec820d77SMatthias Ringwald static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
8630305bdeaSMatthias Ringwald     switch (hci_stack->substate){
8640305bdeaSMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
8657b0d7667SMatthias Ringwald             log_info("Resend HCI Reset");
8660305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET;
8677b0d7667SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
8680305bdeaSMatthias Ringwald             hci_run();
8690305bdeaSMatthias Ringwald             break;
8709f007422SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
8719f007422SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
8729f007422SMatthias Ringwald             if (hci_stack->hci_transport->reset_link){
8739f007422SMatthias Ringwald                 hci_stack->hci_transport->reset_link();
8749f007422SMatthias Ringwald             }
8759f007422SMatthias Ringwald             // NOTE: explicit fallthrough to HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT
876e47e68c7SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
877e47e68c7SMatthias Ringwald             log_info("Resend HCI Reset - CSR Warm Boot");
878e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
879e47e68c7SMatthias Ringwald             hci_stack->num_cmd_packets = 1;
880e47e68c7SMatthias Ringwald             hci_run();
881688c2635SMatthias Ringwald             break;
8827dd9d0ecSMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE: {
88396b53536SMatthias Ringwald 			uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
884cd724cb7SMatthias Ringwald             log_info("Local baud rate change to %"PRIu32"(timeout handler)", baud_rate);
8857dd9d0ecSMatthias Ringwald             hci_stack->hci_transport->set_baudrate(baud_rate);
886772a36d3SMatthias Ringwald             // For CSR, HCI Reset is sent on new baud rate
8872caefae9SMatthias Ringwald             if (hci_stack->manufacturer == COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
888772a36d3SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
889772a36d3SMatthias Ringwald                 hci_run();
890772a36d3SMatthias Ringwald             }
8914696bddbSMatthias Ringwald             break;
8927dd9d0ecSMatthias Ringwald         }
8930305bdeaSMatthias Ringwald         default:
8940305bdeaSMatthias Ringwald             break;
8950305bdeaSMatthias Ringwald     }
8960305bdeaSMatthias Ringwald }
8970305bdeaSMatthias Ringwald 
89871de195eSMatthias Ringwald static void hci_initializing_next_state(void){
89974b323a9SMatthias Ringwald     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
90074b323a9SMatthias Ringwald }
90174b323a9SMatthias Ringwald 
90274b323a9SMatthias Ringwald // assumption: hci_can_send_command_packet_now() == true
90371de195eSMatthias Ringwald static void hci_initializing_run(void){
904*d58dd308SMatthias Ringwald     log_info("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
90574b323a9SMatthias Ringwald     switch (hci_stack->substate){
90674b323a9SMatthias Ringwald         case HCI_INIT_SEND_RESET:
90774b323a9SMatthias Ringwald             hci_state_reset();
908a0cf2f3fSMatthias Ringwald 
909423a3e49SMatthias Ringwald #ifndef HAVE_PLATFORM_IPHONE_OS
9100305bdeaSMatthias Ringwald             // prepare reset if command complete not received in 100ms
911528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, 100);
912528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
913528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
914a0cf2f3fSMatthias Ringwald #endif
9150305bdeaSMatthias Ringwald             // send command
91674b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
9170305bdeaSMatthias Ringwald             hci_send_cmd(&hci_reset);
91874b323a9SMatthias Ringwald             break;
91976fcb19bSMatthias Ringwald         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
92076fcb19bSMatthias Ringwald             hci_send_cmd(&hci_read_local_version_information);
92176fcb19bSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
92276fcb19bSMatthias Ringwald             break;
923e47e68c7SMatthias Ringwald         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
924e47e68c7SMatthias Ringwald             hci_state_reset();
925e47e68c7SMatthias Ringwald             // prepare reset if command complete not received in 100ms
926528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer(&hci_stack->timeout, 100);
927528a4a3bSMatthias Ringwald             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
928528a4a3bSMatthias Ringwald             btstack_run_loop_add_timer(&hci_stack->timeout);
929e47e68c7SMatthias Ringwald             // send command
930e47e68c7SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
931e47e68c7SMatthias Ringwald             hci_send_cmd(&hci_reset);
932e47e68c7SMatthias Ringwald             break;
9338d29070eSMatthias Ringwald         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
9348d29070eSMatthias Ringwald             hci_state_reset();
9358d29070eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
9368d29070eSMatthias Ringwald             hci_send_cmd(&hci_reset);
9378d29070eSMatthias Ringwald             break;
938fab26ab3SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE: {
93996b53536SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
9403fb36a29SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
941f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
94274b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
9430305bdeaSMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
9444696bddbSMatthias Ringwald             // STLC25000D: baudrate change happens within 0.5 s after command was send,
9454696bddbSMatthias Ringwald             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
946c6d1dbedSMatthias Ringwald             if (hci_stack->manufacturer == COMPANY_ID_ST_MICROELECTRONICS){
947528a4a3bSMatthias Ringwald                 btstack_run_loop_set_timer(&hci_stack->timeout, 100);
948528a4a3bSMatthias Ringwald                 btstack_run_loop_add_timer(&hci_stack->timeout);
9494696bddbSMatthias Ringwald             }
95074b323a9SMatthias Ringwald             break;
951fab26ab3SMatthias Ringwald         }
952fab26ab3SMatthias Ringwald         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
95396b53536SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
9543fb36a29SMatthias Ringwald             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
955f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
956eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
957eb3a5314SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
958eb3a5314SMatthias Ringwald             break;
959fab26ab3SMatthias Ringwald         }
96074b323a9SMatthias Ringwald         case HCI_INIT_CUSTOM_INIT:
96174b323a9SMatthias Ringwald             log_info("Custom init");
96274b323a9SMatthias Ringwald             // Custom initialization
9633fb36a29SMatthias Ringwald             if (hci_stack->chipset && hci_stack->chipset->next_command){
9643fb36a29SMatthias Ringwald                 int valid_cmd = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
96574b323a9SMatthias Ringwald                 if (valid_cmd){
96674b323a9SMatthias Ringwald                     int size = 3 + hci_stack->hci_packet_buffer[2];
967f8fbdce0SMatthias Ringwald                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
96874b323a9SMatthias Ringwald                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
969e47e68c7SMatthias Ringwald                     switch (valid_cmd) {
970e47e68c7SMatthias Ringwald                         case 1:
971e47e68c7SMatthias Ringwald                         default:
972e47e68c7SMatthias Ringwald                             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
973e47e68c7SMatthias Ringwald                             break;
974e47e68c7SMatthias Ringwald                         case 2: // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
975e47e68c7SMatthias Ringwald                             log_info("CSR Warm Boot");
976528a4a3bSMatthias Ringwald                             btstack_run_loop_set_timer(&hci_stack->timeout, 100);
977528a4a3bSMatthias Ringwald                             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
978528a4a3bSMatthias Ringwald                             btstack_run_loop_add_timer(&hci_stack->timeout);
9792caefae9SMatthias Ringwald                             if (hci_stack->manufacturer == COMPANY_ID_CAMBRIDGE_SILICON_RADIO
980772a36d3SMatthias Ringwald                                 && hci_stack->config
9813fb36a29SMatthias Ringwald                                 && hci_stack->chipset
9823fb36a29SMatthias Ringwald                                 // && hci_stack->chipset->set_baudrate_command -- there's no such command
983772a36d3SMatthias Ringwald                                 && hci_stack->hci_transport->set_baudrate
9842caefae9SMatthias Ringwald                                 && hci_transport_uart_get_main_baud_rate()){
985772a36d3SMatthias Ringwald                                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
986772a36d3SMatthias Ringwald                             } else {
9879f007422SMatthias Ringwald                                hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
988772a36d3SMatthias Ringwald                             }
989e47e68c7SMatthias Ringwald                             break;
990e47e68c7SMatthias Ringwald                     }
9910305bdeaSMatthias Ringwald                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
99274b323a9SMatthias Ringwald                     break;
99374b323a9SMatthias Ringwald                 }
99474b323a9SMatthias Ringwald                 log_info("hci_run: init script done");
99592a0d36dSMatthias Ringwald 
99692a0d36dSMatthias Ringwald                 // Init script download causes baud rate to reset on Broadcom chipsets, restore UART baud rate if needed
997c6d1dbedSMatthias Ringwald                 if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION){
99892a0d36dSMatthias Ringwald                     int need_baud_change = hci_stack->config
9993fb36a29SMatthias Ringwald                         && hci_stack->chipset
10003fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
100192a0d36dSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
10029796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
100392a0d36dSMatthias Ringwald                     if (need_baud_change) {
10049796ebeaSMatthias Ringwald                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1005cd724cb7SMatthias Ringwald                         log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate);
100692a0d36dSMatthias Ringwald                         hci_stack->hci_transport->set_baudrate(baud_rate);
100792a0d36dSMatthias Ringwald                     }
100892a0d36dSMatthias Ringwald                 }
100974b323a9SMatthias Ringwald             }
101074b323a9SMatthias Ringwald             // otherwise continue
1011a828a756SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1012a828a756SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
1013a828a756SMatthias Ringwald             break;
1014*d58dd308SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
1015*d58dd308SMatthias Ringwald             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
1016*d58dd308SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1017*d58dd308SMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_commands);
1018*d58dd308SMatthias Ringwald             break;
101953860077SMatthias Ringwald         case HCI_INIT_SET_BD_ADDR:
102053860077SMatthias Ringwald             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
10213fb36a29SMatthias Ringwald             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1022f8fbdce0SMatthias Ringwald             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
102353860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
102453860077SMatthias Ringwald             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
102553860077SMatthias Ringwald             break;
102653860077SMatthias Ringwald         case HCI_INIT_READ_BD_ADDR:
102753860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
102853860077SMatthias Ringwald             hci_send_cmd(&hci_read_bd_addr);
102953860077SMatthias Ringwald             break;
103074b323a9SMatthias Ringwald         case HCI_INIT_READ_BUFFER_SIZE:
103174b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
10320305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_buffer_size);
103374b323a9SMatthias Ringwald             break;
103453860077SMatthias Ringwald         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
103553860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
10360305bdeaSMatthias Ringwald             hci_send_cmd(&hci_read_local_supported_features);
103774b323a9SMatthias Ringwald             break;
103874b323a9SMatthias Ringwald         case HCI_INIT_SET_EVENT_MASK:
10390305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
104074b323a9SMatthias Ringwald             if (hci_le_supported()){
104174b323a9SMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
104274b323a9SMatthias Ringwald             } else {
104374b323a9SMatthias Ringwald                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
104474b323a9SMatthias Ringwald                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
104574b323a9SMatthias Ringwald             }
104674b323a9SMatthias Ringwald             break;
104774b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
104874b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
10490305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
105074b323a9SMatthias Ringwald             break;
105174b323a9SMatthias Ringwald         case HCI_INIT_WRITE_PAGE_TIMEOUT:
105274b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
10530305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
105474b323a9SMatthias Ringwald             break;
105574b323a9SMatthias Ringwald         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
105674b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
10570305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
105874b323a9SMatthias Ringwald             break;
105974b323a9SMatthias Ringwald         case HCI_INIT_WRITE_LOCAL_NAME:
10600305bdeaSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
106174b323a9SMatthias Ringwald             if (hci_stack->local_name){
106274b323a9SMatthias Ringwald                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
106374b323a9SMatthias Ringwald             } else {
106493bcd4d0SMatthias Ringwald                 char local_name[30];
106574b323a9SMatthias Ringwald                 // BTstack-11:22:33:44:55:66
106693bcd4d0SMatthias Ringwald                 strcpy(local_name, "BTstack ");
106793bcd4d0SMatthias Ringwald                 strcat(local_name, bd_addr_to_str(hci_stack->local_bd_addr));
106893bcd4d0SMatthias Ringwald                 log_info("---> Name %s", local_name);
106993bcd4d0SMatthias Ringwald                 hci_send_cmd(&hci_write_local_name, local_name);
107074b323a9SMatthias Ringwald             }
107174b323a9SMatthias Ringwald             break;
107274b323a9SMatthias Ringwald         case HCI_INIT_WRITE_SCAN_ENABLE:
107374b323a9SMatthias Ringwald             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
107474b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
107574b323a9SMatthias Ringwald             break;
1076729ed62eSMatthias Ringwald         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1077729ed62eSMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1078729ed62eSMatthias Ringwald             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1079729ed62eSMatthias Ringwald             break;
1080a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
108174b323a9SMatthias Ringwald         // LE INIT
108274b323a9SMatthias Ringwald         case HCI_INIT_LE_READ_BUFFER_SIZE:
108374b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
10840305bdeaSMatthias Ringwald             hci_send_cmd(&hci_le_read_buffer_size);
108574b323a9SMatthias Ringwald             break;
108674b323a9SMatthias Ringwald         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
108774b323a9SMatthias Ringwald             // LE Supported Host = 1, Simultaneous Host = 0
108874b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
10890305bdeaSMatthias Ringwald             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
109074b323a9SMatthias Ringwald             break;
10913b6d4121SMatthias Ringwald         case HCI_INIT_READ_WHITE_LIST_SIZE:
10923b6d4121SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
10933b6d4121SMatthias Ringwald             hci_send_cmd(&hci_le_read_white_list_size);
10943b6d4121SMatthias Ringwald             break;
109574b323a9SMatthias Ringwald         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
109674b323a9SMatthias Ringwald             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs
109774b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
10980305bdeaSMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0);
109974b323a9SMatthias Ringwald             break;
110074b323a9SMatthias Ringwald #endif
110174b323a9SMatthias Ringwald         default:
110274b323a9SMatthias Ringwald             return;
110374b323a9SMatthias Ringwald     }
110455975f88SMatthias Ringwald }
110555975f88SMatthias Ringwald 
1106a650ba4dSMatthias Ringwald static void hci_init_done(void){
1107a650ba4dSMatthias Ringwald     // done. tell the app
1108a650ba4dSMatthias Ringwald     log_info("hci_init_done -> HCI_STATE_WORKING");
1109a650ba4dSMatthias Ringwald     hci_stack->state = HCI_STATE_WORKING;
1110a650ba4dSMatthias Ringwald     hci_emit_state();
1111a650ba4dSMatthias Ringwald     hci_run();
1112a650ba4dSMatthias Ringwald }
1113a650ba4dSMatthias Ringwald 
11146155b3d3S[email protected] static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
1115a2481739S[email protected]     uint8_t command_completed = 0;
1116c4633093SMatthias Ringwald 
11170e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1118f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
11196155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
1120a2481739S[email protected]             command_completed = 1;
112176fcb19bSMatthias Ringwald             log_info("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
11226155b3d3S[email protected]         } else {
1123*d58dd308SMatthias Ringwald             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
11246155b3d3S[email protected]         }
11256155b3d3S[email protected]     }
11260f97eae7SMatthias Ringwald 
11270e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
11286155b3d3S[email protected]         uint8_t  status = packet[2];
1129f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,4);
11306155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
11316155b3d3S[email protected]             if (status){
1132a2481739S[email protected]                 command_completed = 1;
113376fcb19bSMatthias Ringwald                 log_error("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
11346155b3d3S[email protected]             } else {
11356155b3d3S[email protected]                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
11366155b3d3S[email protected]             }
11376155b3d3S[email protected]         } else {
11386155b3d3S[email protected]             log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
11396155b3d3S[email protected]         }
11406155b3d3S[email protected]     }
11410f97eae7SMatthias Ringwald 
1142e47e68c7SMatthias Ringwald     // Vendor == CSR
11430e2df43fSMatthias Ringwald     if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1144e47e68c7SMatthias Ringwald         // TODO: track actual command
1145e47e68c7SMatthias Ringwald         command_completed = 1;
1146e47e68c7SMatthias Ringwald     }
1147a2481739S[email protected] 
11484e9daa6fSMatthias Ringwald     // Vendor == Toshiba
11490e2df43fSMatthias Ringwald     if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
11504e9daa6fSMatthias Ringwald         // TODO: track actual command
11514e9daa6fSMatthias Ringwald         command_completed = 1;
11524e9daa6fSMatthias Ringwald     }
11534e9daa6fSMatthias Ringwald 
11540f97eae7SMatthias Ringwald     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
11550f97eae7SMatthias Ringwald     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
11560f97eae7SMatthias Ringwald     //
11570f97eae7SMatthias Ringwald     // HCI Reset
11580f97eae7SMatthias Ringwald     // Timeout 100 ms
11590f97eae7SMatthias Ringwald     // HCI Reset
11600f97eae7SMatthias Ringwald     // Command Complete Reset
11610f97eae7SMatthias Ringwald     // HCI Read Local Version Information
11620f97eae7SMatthias Ringwald     // Command Complete Reset - but we expected Command Complete Read Local Version Information
11630f97eae7SMatthias Ringwald     // hang...
11640f97eae7SMatthias Ringwald     //
11650f97eae7SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
11660f97eae7SMatthias Ringwald     if (!command_completed
11670e2df43fSMatthias Ringwald             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
11680f97eae7SMatthias Ringwald             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
11690f97eae7SMatthias Ringwald 
1170f8fbdce0SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
11710f97eae7SMatthias Ringwald         if (opcode == hci_reset.opcode){
11720f97eae7SMatthias Ringwald             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
11730f97eae7SMatthias Ringwald             return;
11740f97eae7SMatthias Ringwald         }
11750f97eae7SMatthias Ringwald     }
11760f97eae7SMatthias Ringwald 
11779f007422SMatthias Ringwald     // CSR & H5
11789f007422SMatthias Ringwald     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
11799f007422SMatthias Ringwald     if (!command_completed
11809f007422SMatthias Ringwald             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
11819f007422SMatthias Ringwald             && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){
11829f007422SMatthias Ringwald 
11839f007422SMatthias Ringwald         uint16_t opcode = little_endian_read_16(packet,3);
11849f007422SMatthias Ringwald         if (opcode == hci_reset.opcode){
11859f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
11869f007422SMatthias Ringwald             return;
11879f007422SMatthias Ringwald         }
11889f007422SMatthias Ringwald     }
11899f007422SMatthias Ringwald 
11909f007422SMatthias 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
11919f007422SMatthias Ringwald     // fix: Correct substate and behave as command below
11929f007422SMatthias Ringwald     if (command_completed){
11939f007422SMatthias Ringwald         switch (hci_stack->substate){
11949f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET:
11959f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
11969f007422SMatthias Ringwald                 break;
11979f007422SMatthias Ringwald             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
11989f007422SMatthias Ringwald                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
11999f007422SMatthias Ringwald                 break;
12009f007422SMatthias Ringwald             default:
12019f007422SMatthias Ringwald                 break;
12029f007422SMatthias Ringwald         }
12039f007422SMatthias Ringwald     }
12040f97eae7SMatthias Ringwald 
12050f97eae7SMatthias Ringwald 
1206a2481739S[email protected]     if (!command_completed) return;
1207a2481739S[email protected] 
1208db8bc6ffSMatthias Ringwald     int need_baud_change = hci_stack->config
12093fb36a29SMatthias Ringwald                         && hci_stack->chipset
12103fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_baudrate_command
1211db8bc6ffSMatthias Ringwald                         && hci_stack->hci_transport->set_baudrate
12129796ebeaSMatthias Ringwald                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1213db8bc6ffSMatthias Ringwald 
1214db8bc6ffSMatthias Ringwald     int need_addr_change = hci_stack->custom_bd_addr_set
12153fb36a29SMatthias Ringwald                         && hci_stack->chipset
12163fb36a29SMatthias Ringwald                         && hci_stack->chipset->set_bd_addr_command;
1217a80162e9SMatthias Ringwald 
12185c363727SMatthias Ringwald     switch(hci_stack->substate){
12199f007422SMatthias Ringwald         case HCI_INIT_SEND_RESET:
1220*d58dd308SMatthias Ringwald             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
12219f007422SMatthias Ringwald             // fix: just correct substate and behave as command below
12229f007422SMatthias Ringwald             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
12239f007422SMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
12249f007422SMatthias Ringwald             break;
122574b323a9SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET:
1226528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
122776fcb19bSMatthias Ringwald             break;
122876fcb19bSMatthias Ringwald         case HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION:
1229cd724cb7SMatthias Ringwald             log_info("Received local version info, need baud change %u", need_baud_change);
12302f48d920SMatthias Ringwald             if (need_baud_change){
12312f48d920SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
12322f48d920SMatthias Ringwald                 return;
12332f48d920SMatthias Ringwald             }
123453860077SMatthias Ringwald             // skip baud change
123574b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
123674b323a9SMatthias Ringwald             return;
1237a80162e9SMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE:
12384696bddbSMatthias Ringwald             // for STLC2500D, baud rate change already happened.
1239fab26ab3SMatthias Ringwald             // for others, baud rate gets changed now
1240c6d1dbedSMatthias Ringwald             if (hci_stack->manufacturer != COMPANY_ID_ST_MICROELECTRONICS){
124196b53536SMatthias Ringwald                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1242cd724cb7SMatthias Ringwald                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1243fab26ab3SMatthias Ringwald                 hci_stack->hci_transport->set_baudrate(baud_rate);
12444696bddbSMatthias Ringwald             }
124574b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
124674b323a9SMatthias Ringwald             return;
1247a80162e9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1248528a4a3bSMatthias Ringwald             btstack_run_loop_remove_timer(&hci_stack->timeout);
1249a80162e9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1250a80162e9SMatthias Ringwald             return;
125174b323a9SMatthias Ringwald         case HCI_INIT_W4_CUSTOM_INIT:
125274b323a9SMatthias Ringwald             // repeat custom init
125374b323a9SMatthias Ringwald             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
125474b323a9SMatthias Ringwald             return;
1255a828a756SMatthias Ringwald         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1256c6d1dbedSMatthias Ringwald             if (need_baud_change && hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION){
1257eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1258eb3a5314SMatthias Ringwald                 return;
1259eb3a5314SMatthias Ringwald             }
126053860077SMatthias Ringwald             if (need_addr_change){
126153860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
126253860077SMatthias Ringwald                 return;
126353860077SMatthias Ringwald             }
126453860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
126553860077SMatthias Ringwald             return;
1266eb3a5314SMatthias Ringwald         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM: {
126796b53536SMatthias Ringwald             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1268cd724cb7SMatthias Ringwald             log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1269fab26ab3SMatthias Ringwald             hci_stack->hci_transport->set_baudrate(baud_rate);
1270eb3a5314SMatthias Ringwald             if (need_addr_change){
1271eb3a5314SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1272eb3a5314SMatthias Ringwald                 return;
1273eb3a5314SMatthias Ringwald             }
1274eb3a5314SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1275eb3a5314SMatthias Ringwald             return;
1276eb3a5314SMatthias Ringwald         }
127753860077SMatthias Ringwald         case HCI_INIT_W4_SET_BD_ADDR:
127853860077SMatthias Ringwald             // for STLC2500D, bd addr change only gets active after sending reset command
1279c6d1dbedSMatthias Ringwald             if (hci_stack->manufacturer == COMPANY_ID_ST_MICROELECTRONICS){
128053860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
128153860077SMatthias Ringwald                 return;
128253860077SMatthias Ringwald             }
128353860077SMatthias Ringwald             // skipping st warm boot
128453860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
128553860077SMatthias Ringwald             return;
128653860077SMatthias Ringwald         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
128753860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
128853860077SMatthias Ringwald             return;
128953860077SMatthias Ringwald         case HCI_INIT_W4_READ_BD_ADDR:
129053860077SMatthias Ringwald             // only read buffer size if supported
129153860077SMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x01) {
129253860077SMatthias Ringwald                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
129353860077SMatthias Ringwald                 return;
129453860077SMatthias Ringwald             }
129553860077SMatthias Ringwald             // skipping read buffer size
129653860077SMatthias Ringwald             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1297a828a756SMatthias Ringwald             return;
129874b323a9SMatthias Ringwald         case HCI_INIT_W4_SET_EVENT_MASK:
12996155b3d3S[email protected]             // skip Classic init commands for LE only chipsets
13006155b3d3S[email protected]             if (!hci_classic_supported()){
13016155b3d3S[email protected]                 if (hci_le_supported()){
130274b323a9SMatthias Ringwald                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
130374b323a9SMatthias Ringwald                     return;
13046155b3d3S[email protected]                 } else {
13056155b3d3S[email protected]                     log_error("Neither BR/EDR nor LE supported");
1306a650ba4dSMatthias Ringwald                     hci_init_done();
130774b323a9SMatthias Ringwald                     return;
13086155b3d3S[email protected]                 }
13096155b3d3S[email protected]             }
131015a95bd5SMatthias Ringwald             if (!gap_ssp_supported()){
13115c363727SMatthias Ringwald                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
131274b323a9SMatthias Ringwald                 return;
13136155b3d3S[email protected]             }
13146155b3d3S[email protected]             break;
1315729ed62eSMatthias Ringwald         case HCI_INIT_W4_WRITE_PAGE_TIMEOUT:
1316729ed62eSMatthias Ringwald             break;
1317a828a756SMatthias Ringwald         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1318a828a756SMatthias Ringwald             // skip write le host if not supported (e.g. on LE only EM9301)
1319a828a756SMatthias Ringwald             if (hci_stack->local_supported_commands[0] & 0x02) break;
1320a828a756SMatthias Ringwald             hci_stack->substate = HCI_INIT_LE_SET_SCAN_PARAMETERS;
1321a828a756SMatthias Ringwald             return;
1322729ed62eSMatthias Ringwald 
132371c4de7aSMatthias Ringwald #ifdef ENABLE_SCO_OVER_HCI
1324729ed62eSMatthias Ringwald         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1325729ed62eSMatthias Ringwald             // just go to next state
1326729ed62eSMatthias Ringwald             break;
1327729ed62eSMatthias Ringwald         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1328729ed62eSMatthias Ringwald             if (!hci_le_supported()){
1329729ed62eSMatthias Ringwald                 // SKIP LE init for Classic only configuration
1330a650ba4dSMatthias Ringwald                 hci_init_done();
1331729ed62eSMatthias Ringwald                 return;
1332729ed62eSMatthias Ringwald             }
1333729ed62eSMatthias Ringwald             break;
1334729ed62eSMatthias Ringwald #else
133574b323a9SMatthias Ringwald         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
13366155b3d3S[email protected]             if (!hci_le_supported()){
13376155b3d3S[email protected]                 // SKIP LE init for Classic only configuration
1338a650ba4dSMatthias Ringwald                 hci_init_done();
133974b323a9SMatthias Ringwald                 return;
13406155b3d3S[email protected]             }
1341729ed62eSMatthias Ringwald #endif
1342729ed62eSMatthias Ringwald             break;
1343a650ba4dSMatthias Ringwald         // Response to command before init done state -> init done
1344a650ba4dSMatthias Ringwald         case (HCI_INIT_DONE-1):
1345a650ba4dSMatthias Ringwald             hci_init_done();
1346a650ba4dSMatthias Ringwald             return;
1347a650ba4dSMatthias Ringwald 
13486155b3d3S[email protected]         default:
134974b323a9SMatthias Ringwald             break;
13506155b3d3S[email protected]     }
135155975f88SMatthias Ringwald     hci_initializing_next_state();
13526155b3d3S[email protected] }
13536155b3d3S[email protected] 
135416833f0aSmatthias.ringwald static void event_handler(uint8_t *packet, int size){
1355e76a89eeS[email protected] 
1356e76a89eeS[email protected]     uint16_t event_length = packet[1];
1357e76a89eeS[email protected] 
1358e76a89eeS[email protected]     // assert packet is complete
1359e76a89eeS[email protected]     if (size != event_length + 2){
1360e76a89eeS[email protected]         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
1361e76a89eeS[email protected]         return;
1362e76a89eeS[email protected]     }
1363e76a89eeS[email protected] 
13641281a47eSmatthias.ringwald     bd_addr_t addr;
136596a45072S[email protected]     bd_addr_type_t addr_type;
13662d00edd4Smatthias.ringwald     uint8_t link_type;
1367fe1ed1b8Smatthias.ringwald     hci_con_handle_t handle;
13681f7b95a1Smatthias.ringwald     hci_connection_t * conn;
136956cf178bSmatthias.ringwald     int i;
137022909952Smatthias.ringwald 
13710e2df43fSMatthias Ringwald     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
13725909f7f2Smatthias.ringwald 
13730e2df43fSMatthias Ringwald     switch (hci_event_packet_get_type(packet)) {
137422909952Smatthias.ringwald 
13756772a24cSmatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
13767ec5eeaaSmatthias.ringwald             // get num cmd packets
13779da54300S[email protected]             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]);
13783a9fb326S[email protected]             hci_stack->num_cmd_packets = packet[2];
13797ec5eeaaSmatthias.ringwald 
1380073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1381e2edc0c3Smatthias.ringwald                 // from offset 5
1382e2edc0c3Smatthias.ringwald                 // status
13831d279b20Smatthias.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"
1384f8fbdce0SMatthias Ringwald                 hci_stack->acl_data_packet_length = little_endian_read_16(packet, 6);
1385a8b12447S[email protected]                 hci_stack->sco_data_packet_length = packet[8];
1386f8fbdce0SMatthias Ringwald                 hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1387f8fbdce0SMatthias Ringwald                 hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1388a8b12447S[email protected] 
13893a9fb326S[email protected]                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1390a7a04bd9Smatthias.ringwald                     // determine usable ACL payload size
13913a9fb326S[email protected]                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
13923a9fb326S[email protected]                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
13938f8108aaSmatthias.ringwald                     }
13941a06f663S[email protected]                     log_info("hci_read_buffer_size: acl used size %u, count %u / sco size %u, count %u",
13951a06f663S[email protected]                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
13961a06f663S[email protected]                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1397e2edc0c3Smatthias.ringwald                 }
139856cf178bSmatthias.ringwald             }
1399a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
1400073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1401f8fbdce0SMatthias Ringwald                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1402ee303eddS[email protected]                 hci_stack->le_acl_packets_total_num  = packet[8];
14036c26b087S[email protected]                     // determine usable ACL payload size
14046c26b087S[email protected]                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
14056c26b087S[email protected]                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
14066c26b087S[email protected]                     }
14079da54300S[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);
140865a46ef3S[email protected]             }
1409073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1410f8fbdce0SMatthias Ringwald                 hci_stack->le_whitelist_capacity = little_endian_read_16(packet, 6);
141115d0a15bSMatthias Ringwald                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
14123b6d4121SMatthias Ringwald             }
141365a46ef3S[email protected] #endif
1414188981d2Smatthias.ringwald             // Dump local address
1415073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1416724d70a2SMatthias Ringwald                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1417724d70a2SMatthias Ringwald 				hci_stack->local_bd_addr);
14189da54300S[email protected]                 log_info("Local Address, Status: 0x%02x: Addr: %s",
14193a9fb326S[email protected]                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1420188981d2Smatthias.ringwald             }
1421073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
14223a9fb326S[email protected]                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1423381fbed8Smatthias.ringwald             }
142465389bfcS[email protected]             // Note: HCI init checks
1425073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
14263a9fb326S[email protected]                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
142765389bfcS[email protected] 
1428a5a23fc2S[email protected]                 // determine usable ACL packet types based on host buffer size and supported features
1429a5a23fc2S[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]);
14303a9fb326S[email protected]                 log_info("packet types %04x", hci_stack->packet_types);
1431f5d8d141S[email protected] 
1432f5d8d141S[email protected]                 // Classic/LE
1433f5d8d141S[email protected]                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1434559e517eS[email protected]             }
1435073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1436f8fbdce0SMatthias Ringwald                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1437f8fbdce0SMatthias Ringwald                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1438f8fbdce0SMatthias Ringwald                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1439f8fbdce0SMatthias Ringwald                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1440f8fbdce0SMatthias Ringwald                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
14414696bddbSMatthias Ringwald                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1442a6ddbcb9SMatthias Ringwald                 // notify app
1443a6ddbcb9SMatthias Ringwald                 if (hci_stack->local_version_information_callback){
1444a6ddbcb9SMatthias Ringwald                     hci_stack->local_version_information_callback(packet);
1445a6ddbcb9SMatthias Ringwald                 }
14464696bddbSMatthias Ringwald             }
1447073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1448a828a756SMatthias Ringwald                 hci_stack->local_supported_commands[0] =
1449a828a756SMatthias Ringwald                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0X80) >> 7 |  // Octet 14, bit 7
1450a828a756SMatthias Ringwald                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5;   // Octet 24, bit 6
1451a828a756SMatthias Ringwald             }
1452073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
14535b9b590fSMatthias Ringwald                 if (packet[5] == 0){
14545b9b590fSMatthias Ringwald                     hci_stack->synchronous_flow_control_enabled = 1;
14555b9b590fSMatthias Ringwald                 }
14565b9b590fSMatthias Ringwald             }
145756cf178bSmatthias.ringwald             break;
145856cf178bSmatthias.ringwald 
14597ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
14607ec5eeaaSmatthias.ringwald             // get num cmd packets
14619da54300S[email protected]             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]);
14623a9fb326S[email protected]             hci_stack->num_cmd_packets = packet[3];
14637ec5eeaaSmatthias.ringwald             break;
14647ec5eeaaSmatthias.ringwald 
14652e440c8aS[email protected]         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
14662e440c8aS[email protected]             int offset = 3;
146756cf178bSmatthias.ringwald             for (i=0; i<packet[2];i++){
1468f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, offset);
14692e440c8aS[email protected]                 offset += 2;
1470f8fbdce0SMatthias Ringwald                 uint16_t num_packets = little_endian_read_16(packet, offset);
14712e440c8aS[email protected]                 offset += 2;
14722e440c8aS[email protected] 
14735061f3afS[email protected]                 conn = hci_connection_for_handle(handle);
147456cf178bSmatthias.ringwald                 if (!conn){
14759da54300S[email protected]                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
147656cf178bSmatthias.ringwald                     continue;
147756cf178bSmatthias.ringwald                 }
147823bed257S[email protected] 
1479e35edcc1S[email protected]                 if (conn->address_type == BD_ADDR_TYPE_SCO){
1480e35edcc1S[email protected]                     if (conn->num_sco_packets_sent >= num_packets){
1481e35edcc1S[email protected]                         conn->num_sco_packets_sent -= num_packets;
1482e35edcc1S[email protected]                     } else {
1483e35edcc1S[email protected]                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1484e35edcc1S[email protected]                         conn->num_sco_packets_sent = 0;
1485e35edcc1S[email protected]                     }
1486701e3307SMatthias Ringwald                     hci_notify_if_sco_can_send_now();
1487e35edcc1S[email protected]                 } else {
148823bed257S[email protected]                     if (conn->num_acl_packets_sent >= num_packets){
148956cf178bSmatthias.ringwald                         conn->num_acl_packets_sent -= num_packets;
149023bed257S[email protected]                     } else {
1491e35edcc1S[email protected]                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
149223bed257S[email protected]                         conn->num_acl_packets_sent = 0;
149323bed257S[email protected]                     }
1494e35edcc1S[email protected]                 }
14959da54300S[email protected]                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
149656cf178bSmatthias.ringwald             }
14976772a24cSmatthias.ringwald             break;
14982e440c8aS[email protected]         }
14991f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
1500724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[2], addr);
150137eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
15022d00edd4Smatthias.ringwald             link_type = packet[11];
15039da54300S[email protected]             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1504e35edcc1S[email protected]             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
15052e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
15061f7b95a1Smatthias.ringwald             if (!conn) {
15075293c072S[email protected]                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
15081f7b95a1Smatthias.ringwald             }
1509ce4c8fabSmatthias.ringwald             if (!conn) {
1510ce4c8fabSmatthias.ringwald                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
15113a9fb326S[email protected]                 hci_stack->decline_reason = 0x0d;
1512058e3d6bSMatthias Ringwald                 bd_addr_copy(hci_stack->decline_addr, addr);
1513ce4c8fabSmatthias.ringwald                 break;
1514ce4c8fabSmatthias.ringwald             }
15155cf766e8SMatthias Ringwald             conn->role  = HCI_ROLE_SLAVE;
151632ab9390Smatthias.ringwald             conn->state = RECEIVED_CONNECTION_REQUEST;
1517f3a16b9aSMatthias Ringwald             // store info about eSCO
1518f3a16b9aSMatthias Ringwald             if (link_type == 0x02){
1519f3a16b9aSMatthias Ringwald                 conn->remote_supported_feature_eSCO = 1;
1520f3a16b9aSMatthias Ringwald             }
152132ab9390Smatthias.ringwald             hci_run();
15221f7b95a1Smatthias.ringwald             break;
15231f7b95a1Smatthias.ringwald 
15246772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1525fe1ed1b8Smatthias.ringwald             // Connection management
1526724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
15279da54300S[email protected]             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
152896a45072S[email protected]             addr_type = BD_ADDR_TYPE_CLASSIC;
15292e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1530fe1ed1b8Smatthias.ringwald             if (conn) {
1531b448a0e7Smatthias.ringwald                 if (!packet[2]){
1532c8e4258aSmatthias.ringwald                     conn->state = OPEN;
1533f8fbdce0SMatthias Ringwald                     conn->con_handle = little_endian_read_16(packet, 3);
1534ad83dc6aS[email protected]                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1535ee091cf1Smatthias.ringwald 
1536c785ef68Smatthias.ringwald                     // restart timer
1537528a4a3bSMatthias Ringwald                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1538528a4a3bSMatthias Ringwald                     btstack_run_loop_add_timer(&conn->timeout);
1539c785ef68Smatthias.ringwald 
15409da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
154143bfb1bdSmatthias.ringwald 
154243bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
1543b448a0e7Smatthias.ringwald                 } else {
15441bd5283dS[email protected]                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
15451bd5283dS[email protected]                     uint8_t status = packet[2];
15461bd5283dS[email protected]                     bd_addr_t bd_address;
15471bd5283dS[email protected]                     memcpy(&bd_address, conn->address, 6);
1548ad83dc6aS[email protected] 
1549b448a0e7Smatthias.ringwald                     // connection failed, remove entry
1550665d90f2SMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1551a3b02b71Smatthias.ringwald                     btstack_memory_hci_connection_free( conn );
1552c12e46e7Smatthias.ringwald 
15531bd5283dS[email protected]                     // notify client if dedicated bonding
15541bd5283dS[email protected]                     if (notify_dedicated_bonding_failed){
15551bd5283dS[email protected]                         log_info("hci notify_dedicated_bonding_failed");
15561bd5283dS[email protected]                         hci_emit_dedicated_bonding_result(bd_address, status);
15571bd5283dS[email protected]                     }
15581bd5283dS[email protected] 
1559c12e46e7Smatthias.ringwald                     // if authentication error, also delete link key
1560c12e46e7Smatthias.ringwald                     if (packet[2] == 0x05) {
156115a95bd5SMatthias Ringwald                         gap_drop_link_key_for_bd_addr(addr);
1562c12e46e7Smatthias.ringwald                     }
1563fe1ed1b8Smatthias.ringwald                 }
1564fe1ed1b8Smatthias.ringwald             }
15656772a24cSmatthias.ringwald             break;
1566fe1ed1b8Smatthias.ringwald 
156744d0e3d5S[email protected]         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1568724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], addr);
156944d0e3d5S[email protected]             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
15701a06f663S[email protected]             if (packet[2]){
157144d0e3d5S[email protected]                 // connection failed
157244d0e3d5S[email protected]                 break;
157344d0e3d5S[email protected]             }
15742e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1575e35edcc1S[email protected]             if (!conn) {
1576e35edcc1S[email protected]                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1577e35edcc1S[email protected]             }
1578e35edcc1S[email protected]             if (!conn) {
1579e35edcc1S[email protected]                 break;
1580e35edcc1S[email protected]             }
15811a06f663S[email protected]             conn->state = OPEN;
1582f8fbdce0SMatthias Ringwald             conn->con_handle = little_endian_read_16(packet, 3);
158344d0e3d5S[email protected]             break;
158444d0e3d5S[email protected] 
1585afd4e962S[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1586f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1587afd4e962S[email protected]             conn = hci_connection_for_handle(handle);
1588afd4e962S[email protected]             if (!conn) break;
1589afd4e962S[email protected]             if (!packet[2]){
1590afd4e962S[email protected]                 uint8_t * features = &packet[5];
1591afd4e962S[email protected]                 if (features[6] & (1 << 3)){
1592afd4e962S[email protected]                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1593afd4e962S[email protected]                 }
159498a2fd1cSMatthias Ringwald                 if (features[3] & (1<<7)){
159598a2fd1cSMatthias Ringwald                     conn->remote_supported_feature_eSCO = 1;
159698a2fd1cSMatthias Ringwald                 }
1597afd4e962S[email protected]             }
1598afd4e962S[email protected]             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
159998a2fd1cSMatthias Ringwald             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
1600ad83dc6aS[email protected]             if (conn->bonding_flags & BONDING_DEDICATED){
1601ad83dc6aS[email protected]                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1602ad83dc6aS[email protected]             }
1603afd4e962S[email protected]             break;
1604afd4e962S[email protected] 
16057fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
16069da54300S[email protected]             log_info("HCI_EVENT_LINK_KEY_REQUEST");
16077fde4af9Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
160874d716b5S[email protected]             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1609a98592bcSMatthias Ringwald             if (hci_stack->bondable && !hci_stack->link_key_db) break;
161032ab9390Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
161164472d52Smatthias.ringwald             hci_run();
1612d9a327f9Smatthias.ringwald             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
161329d53098Smatthias.ringwald             return;
16147fde4af9Smatthias.ringwald 
16159ab95c90S[email protected]         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1616724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[2], addr);
16172e77e513S[email protected]             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
16189ab95c90S[email protected]             if (!conn) break;
16199ab95c90S[email protected]             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
16207bdc6798S[email protected]             link_key_type_t link_key_type = (link_key_type_t)packet[24];
16219ab95c90S[email protected]             // Change Connection Encryption keeps link key type
16229ab95c90S[email protected]             if (link_key_type != CHANGED_COMBINATION_KEY){
16239ab95c90S[email protected]                 conn->link_key_type = link_key_type;
16249ab95c90S[email protected]             }
1625a98592bcSMatthias Ringwald             if (!hci_stack->link_key_db) break;
1626a98592bcSMatthias Ringwald             hci_stack->link_key_db->put_link_key(addr, &packet[8], conn->link_key_type);
162729d53098Smatthias.ringwald             // still forward event to allow dismiss of pairing dialog
16287fde4af9Smatthias.ringwald             break;
16299ab95c90S[email protected]         }
16307fde4af9Smatthias.ringwald 
16317fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
16326724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
16334c57c146S[email protected]             // non-bondable mode: pin code negative reply will be sent
16343a9fb326S[email protected]             if (!hci_stack->bondable){
1635899283eaS[email protected]                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1636f8fb5f6eS[email protected]                 hci_run();
1637f8fb5f6eS[email protected]                 return;
16384c57c146S[email protected]             }
1639d9a327f9Smatthias.ringwald             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1640a98592bcSMatthias Ringwald             if (!hci_stack->link_key_db) break;
1641a6ef64baSMilanka Ringwald             hci_event_pin_code_request_get_bd_addr(packet, addr);
1642a98592bcSMatthias Ringwald             hci_stack->link_key_db->delete_link_key(addr);
16437fde4af9Smatthias.ringwald             break;
16447fde4af9Smatthias.ringwald 
16451d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
16461d6b20aeS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1647dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1648dbe1a790S[email protected]             break;
1649dbe1a790S[email protected] 
1650dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
16516724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
16523a9fb326S[email protected]             if (!hci_stack->ssp_auto_accept) break;
1653dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1654dbe1a790S[email protected]             break;
1655dbe1a790S[email protected] 
1656dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
16576724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
16583a9fb326S[email protected]             if (!hci_stack->ssp_auto_accept) break;
1659dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
16601d6b20aeS[email protected]             break;
16611d6b20aeS[email protected] 
1662f0944df2S[email protected]         case HCI_EVENT_ENCRYPTION_CHANGE:
1663f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1664f0944df2S[email protected]             conn = hci_connection_for_handle(handle);
1665f0944df2S[email protected]             if (!conn) break;
1666ad83dc6aS[email protected]             if (packet[2] == 0) {
1667f0944df2S[email protected]                 if (packet[5]){
1668f0944df2S[email protected]                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1669f0944df2S[email protected]                 } else {
1670536f9994S[email protected]                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1671f0944df2S[email protected]                 }
1672ad83dc6aS[email protected]             }
1673a00031e2S[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1674f0944df2S[email protected]             break;
1675f0944df2S[email protected] 
16761eb2563eS[email protected]         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1677f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
16781eb2563eS[email protected]             conn = hci_connection_for_handle(handle);
16791eb2563eS[email protected]             if (!conn) break;
1680ad83dc6aS[email protected] 
1681ad83dc6aS[email protected]             // dedicated bonding: send result and disconnect
1682ad83dc6aS[email protected]             if (conn->bonding_flags & BONDING_DEDICATED){
1683ad83dc6aS[email protected]                 conn->bonding_flags &= ~BONDING_DEDICATED;
1684ad83dc6aS[email protected]                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
16851bd5283dS[email protected]                 conn->bonding_status = packet[2];
1686ad83dc6aS[email protected]                 break;
1687ad83dc6aS[email protected]             }
1688ad83dc6aS[email protected] 
1689b5cb6874S[email protected]             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
16901eb2563eS[email protected]                 // link key sufficient for requested security
16911eb2563eS[email protected]                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1692ad83dc6aS[email protected]                 break;
1693ad83dc6aS[email protected]             }
16941eb2563eS[email protected]             // not enough
16951eb2563eS[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
16961eb2563eS[email protected]             break;
169734d2123cS[email protected] 
169886805605S[email protected]         // HCI_EVENT_DISCONNECTION_COMPLETE
1699ccda6e14S[email protected]         // has been split, to first notify stack before shutting connection down
1700ccda6e14S[email protected]         // see end of function, too.
1701a4f30ec0S[email protected]         case HCI_EVENT_DISCONNECTION_COMPLETE:
1702a4f30ec0S[email protected]             if (packet[2]) break;   // status != 0
1703f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
17046da48142SSean Wilson             conn = hci_connection_for_handle(handle);
1705a4f30ec0S[email protected]             if (!conn) break;       // no conn struct anymore
17069a2e4658SMatthias Ringwald             // re-enable advertisements for le connections if active
17079a2e4658SMatthias Ringwald             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
17089a2e4658SMatthias Ringwald                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
17099a2e4658SMatthias Ringwald             }
1710ccda6e14S[email protected]             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1711ccda6e14S[email protected]             break;
17126772a24cSmatthias.ringwald 
1713c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
1714d23838ecSMatthias Ringwald             if (hci_stack->hardware_error_callback){
1715d23838ecSMatthias Ringwald                 (*hci_stack->hardware_error_callback)();
17167586ee35S[email protected]             } else {
17177586ee35S[email protected]                 // if no special requests, just reboot stack
17187586ee35S[email protected]                 hci_power_control_off();
17197586ee35S[email protected]                 hci_power_control_on();
1720c68bdf90Smatthias.ringwald             }
1721c68bdf90Smatthias.ringwald             break;
1722c68bdf90Smatthias.ringwald 
17235cf766e8SMatthias Ringwald         case HCI_EVENT_ROLE_CHANGE:
17245cf766e8SMatthias Ringwald             if (packet[2]) break;   // status != 0
1725f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
17265cf766e8SMatthias Ringwald             conn = hci_connection_for_handle(handle);
17275cf766e8SMatthias Ringwald             if (!conn) break;       // no conn
17285cf766e8SMatthias Ringwald             conn->role = packet[9];
17295cf766e8SMatthias Ringwald             break;
17305cf766e8SMatthias Ringwald 
173163fa3374SMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
1732d051460cS[email protected]             // release packet buffer only for asynchronous transport and if there are not further fragements
17334fa24b5fS[email protected]             if (hci_transport_synchronous()) {
173463fa3374SMatthias Ringwald                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
17354fa24b5fS[email protected]                 return; // instead of break: to avoid re-entering hci_run()
17364fa24b5fS[email protected]             }
1737d051460cS[email protected]             if (hci_stack->acl_fragmentation_total_size) break;
1738d051460cS[email protected]             hci_release_packet_buffer();
1739701e3307SMatthias Ringwald 
174063fa3374SMatthias Ringwald             // L2CAP receives this event via the hci_emit_event below
174163fa3374SMatthias Ringwald 
174263fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
1743701e3307SMatthias Ringwald             hci_notify_if_sco_can_send_now();
17446b4af23dS[email protected]             break;
17456b4af23dS[email protected] 
174663fa3374SMatthias Ringwald         case HCI_EVENT_SCO_CAN_SEND_NOW:
174763fa3374SMatthias Ringwald             // For SCO, we do the can_send_now_check here
174863fa3374SMatthias Ringwald             hci_notify_if_sco_can_send_now();
174963fa3374SMatthias Ringwald             return;
175063fa3374SMatthias Ringwald 
1751a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
17525909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
17535909f7f2Smatthias.ringwald             switch (packet[2]){
175457c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
17554f4e0224SMatthias Ringwald                     // log_info("advertising report received");
17567bdc6798S[email protected]                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
175757c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
17587bdc6798S[email protected]                     break;
17595909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
17605909f7f2Smatthias.ringwald                     // Connection management
1761724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[8], addr);
17627bdc6798S[email protected]                     addr_type = (bd_addr_type_t)packet[7];
17639da54300S[email protected]                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
17642e77e513S[email protected]                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
176542ff5ba1SMatthias Ringwald                     // if auto-connect, remove from whitelist in both roles
176642ff5ba1SMatthias Ringwald                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
176742ff5ba1SMatthias Ringwald                         hci_remove_from_whitelist(addr_type, addr);
176842ff5ba1SMatthias Ringwald                     }
176942ff5ba1SMatthias Ringwald                     // handle error: error is reported only to the initiator -> outgoing connection
17705909f7f2Smatthias.ringwald                     if (packet[3]){
177142ff5ba1SMatthias Ringwald                         // outgoing connection establishment is done
177242ff5ba1SMatthias Ringwald                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
177342ff5ba1SMatthias Ringwald                         // remove entry
17745909f7f2Smatthias.ringwald                         if (conn){
1775665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
17765909f7f2Smatthias.ringwald                             btstack_memory_hci_connection_free( conn );
17775909f7f2Smatthias.ringwald                         }
17785909f7f2Smatthias.ringwald                         break;
17795909f7f2Smatthias.ringwald                     }
178042ff5ba1SMatthias Ringwald                     // on success, both hosts receive connection complete event
17815cf766e8SMatthias Ringwald                     if (packet[6] == HCI_ROLE_MASTER){
178242ff5ba1SMatthias Ringwald                         // if we're master, it was an outgoing connection and we're done with it
178342ff5ba1SMatthias Ringwald                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
178442ff5ba1SMatthias Ringwald                     } else {
178542ff5ba1SMatthias Ringwald                         // if we're slave, it was an incoming connection, advertisements have stopped
1786171293d3SMatthias Ringwald                         hci_stack->le_advertisements_active = 0;
178742ff5ba1SMatthias Ringwald                     }
1788171293d3SMatthias Ringwald                     // LE connections are auto-accepted, so just create a connection if there isn't one already
178942ff5ba1SMatthias Ringwald                     if (!conn){
179096a45072S[email protected]                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
17915909f7f2Smatthias.ringwald                     }
179242ff5ba1SMatthias Ringwald                     // no memory, sorry.
17935909f7f2Smatthias.ringwald                     if (!conn){
17945909f7f2Smatthias.ringwald                         break;
17955909f7f2Smatthias.ringwald                     }
17965909f7f2Smatthias.ringwald 
17975909f7f2Smatthias.ringwald                     conn->state = OPEN;
17985cf766e8SMatthias Ringwald                     conn->role  = packet[6];
1799f8fbdce0SMatthias Ringwald                     conn->con_handle = little_endian_read_16(packet, 4);
18005909f7f2Smatthias.ringwald 
18015909f7f2Smatthias.ringwald                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
18025909f7f2Smatthias.ringwald 
18035909f7f2Smatthias.ringwald                     // restart timer
1804528a4a3bSMatthias Ringwald                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1805528a4a3bSMatthias Ringwald                     // btstack_run_loop_add_timer(&conn->timeout);
18065909f7f2Smatthias.ringwald 
18079da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
18085909f7f2Smatthias.ringwald 
18095909f7f2Smatthias.ringwald                     hci_emit_nr_connections_changed();
18105909f7f2Smatthias.ringwald                     break;
18115909f7f2Smatthias.ringwald 
1812f8fbdce0SMatthias Ringwald             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
181365a46ef3S[email protected] 
18145909f7f2Smatthias.ringwald                 default:
18155909f7f2Smatthias.ringwald                     break;
18165909f7f2Smatthias.ringwald             }
18175909f7f2Smatthias.ringwald             break;
18185909f7f2Smatthias.ringwald #endif
18196772a24cSmatthias.ringwald         default:
18206772a24cSmatthias.ringwald             break;
1821fe1ed1b8Smatthias.ringwald     }
1822fe1ed1b8Smatthias.ringwald 
18233429f56bSmatthias.ringwald     // handle BT initialization
18243a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_INITIALIZING){
18256155b3d3S[email protected]         hci_initializing_event_handler(packet, size);
1826c9af4d3fS[email protected]     }
182722909952Smatthias.ringwald 
182889db417bSmatthias.ringwald     // help with BT sleep
18293a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
183074b323a9SMatthias Ringwald         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
1831073bd0faSMatthias Ringwald         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
183255975f88SMatthias Ringwald         hci_initializing_next_state();
183389db417bSmatthias.ringwald     }
183489db417bSmatthias.ringwald 
183586805605S[email protected]     // notify upper stack
1836d6b06661SMatthias Ringwald 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
183794ab26f8Smatthias.ringwald 
183886805605S[email protected]     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
18390e2df43fSMatthias Ringwald     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
184086805605S[email protected]         if (!packet[2]){
1841f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
184205ae8de3SMatthias Ringwald             hci_connection_t * aConn = hci_connection_for_handle(handle);
184305ae8de3SMatthias Ringwald             if (aConn) {
184405ae8de3SMatthias Ringwald                 uint8_t status = aConn->bonding_status;
184505ae8de3SMatthias Ringwald                 uint16_t flags = aConn->bonding_flags;
184686805605S[email protected]                 bd_addr_t bd_address;
184705ae8de3SMatthias Ringwald                 memcpy(&bd_address, aConn->address, 6);
184805ae8de3SMatthias Ringwald                 hci_shutdown_connection(aConn);
1849bb820044S[email protected]                 // connection struct is gone, don't access anymore
1850bb820044S[email protected]                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
185186805605S[email protected]                     hci_emit_dedicated_bonding_result(bd_address, status);
185286805605S[email protected]                 }
185386805605S[email protected]             }
185486805605S[email protected]         }
185586805605S[email protected]     }
185686805605S[email protected] 
185794ab26f8Smatthias.ringwald 	// execute main loop
185894ab26f8Smatthias.ringwald 	hci_run();
185916833f0aSmatthias.ringwald }
186016833f0aSmatthias.ringwald 
1861c91d150bS[email protected] static void sco_handler(uint8_t * packet, uint16_t size){
18628abbe8b5SMatthias Ringwald     if (!hci_stack->sco_packet_handler) return;
18638abbe8b5SMatthias Ringwald     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, packet, size);
1864c91d150bS[email protected] }
1865c91d150bS[email protected] 
18660a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
18675bb5bc3eS[email protected]     hci_dump_packet(packet_type, 1, packet, size);
186810e830c9Smatthias.ringwald     switch (packet_type) {
186910e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
187010e830c9Smatthias.ringwald             event_handler(packet, size);
187110e830c9Smatthias.ringwald             break;
187210e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
187310e830c9Smatthias.ringwald             acl_handler(packet, size);
187410e830c9Smatthias.ringwald             break;
1875c91d150bS[email protected]         case HCI_SCO_DATA_PACKET:
1876c91d150bS[email protected]             sco_handler(packet, size);
187710e830c9Smatthias.ringwald         default:
187810e830c9Smatthias.ringwald             break;
187910e830c9Smatthias.ringwald     }
188010e830c9Smatthias.ringwald }
188110e830c9Smatthias.ringwald 
1882d6b06661SMatthias Ringwald /**
1883d6b06661SMatthias Ringwald  * @brief Add event packet handler.
1884d6b06661SMatthias Ringwald  */
1885d6b06661SMatthias Ringwald void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
1886d6b06661SMatthias Ringwald     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
1887d6b06661SMatthias Ringwald }
1888d6b06661SMatthias Ringwald 
1889d6b06661SMatthias Ringwald 
1890fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
1891fb37a842SMatthias Ringwald void hci_register_acl_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1892fb37a842SMatthias Ringwald     hci_stack->acl_packet_handler = handler;
189316833f0aSmatthias.ringwald }
189416833f0aSmatthias.ringwald 
18958abbe8b5SMatthias Ringwald /**
18968abbe8b5SMatthias Ringwald  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
18978abbe8b5SMatthias Ringwald  */
18988abbe8b5SMatthias Ringwald void hci_register_sco_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
18998abbe8b5SMatthias Ringwald     hci_stack->sco_packet_handler = handler;
19008abbe8b5SMatthias Ringwald }
19018abbe8b5SMatthias Ringwald 
190271de195eSMatthias Ringwald static void hci_state_reset(void){
1903595bdbfbS[email protected]     // no connections yet
1904595bdbfbS[email protected]     hci_stack->connections = NULL;
190574308b23Smatthias.ringwald 
190674308b23Smatthias.ringwald     // keep discoverable/connectable as this has been requested by the client(s)
190774308b23Smatthias.ringwald     // hci_stack->discoverable = 0;
190874308b23Smatthias.ringwald     // hci_stack->connectable = 0;
190974308b23Smatthias.ringwald     // hci_stack->bondable = 1;
1910595bdbfbS[email protected] 
191144935e40S[email protected]     // buffer is free
191244935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
191344935e40S[email protected] 
1914595bdbfbS[email protected]     // no pending cmds
1915595bdbfbS[email protected]     hci_stack->decline_reason = 0;
1916595bdbfbS[email protected]     hci_stack->new_scan_enable_value = 0xff;
1917595bdbfbS[email protected] 
1918595bdbfbS[email protected]     // LE
1919595bdbfbS[email protected]     hci_stack->adv_addr_type = 0;
1920595bdbfbS[email protected]     memset(hci_stack->adv_address, 0, 6);
1921595bdbfbS[email protected]     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1922e2602ea2Smatthias.ringwald     hci_stack->le_scan_type = 0xff;
1923b04dfa37SMatthias Ringwald     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
1924e83201bcSMatthias Ringwald     hci_stack->le_whitelist = 0;
1925e83201bcSMatthias Ringwald     hci_stack->le_whitelist_capacity = 0;
1926e21192abSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
1927e21192abSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
1928e21192abSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
1929e21192abSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
1930e21192abSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
1931e21192abSMatthias Ringwald     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
1932595bdbfbS[email protected] }
1933595bdbfbS[email protected] 
19342d5e09d6SMatthias Ringwald /**
19352d5e09d6SMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called before power on.
19362d5e09d6SMatthias Ringwald  */
19372d5e09d6SMatthias Ringwald void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
19382d5e09d6SMatthias Ringwald     // store and open remote device db
19392d5e09d6SMatthias Ringwald     hci_stack->link_key_db = link_key_db;
19402d5e09d6SMatthias Ringwald     if (hci_stack->link_key_db) {
19412d5e09d6SMatthias Ringwald         hci_stack->link_key_db->open();
19422d5e09d6SMatthias Ringwald     }
19432d5e09d6SMatthias Ringwald }
19442d5e09d6SMatthias Ringwald 
19452d5e09d6SMatthias Ringwald void hci_init(const hci_transport_t *transport, const void *config){
1946475c8125Smatthias.ringwald 
19473a9fb326S[email protected] #ifdef HAVE_MALLOC
19483a9fb326S[email protected]     if (!hci_stack) {
19493a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
19503a9fb326S[email protected]     }
19513a9fb326S[email protected] #else
19523a9fb326S[email protected]     hci_stack = &hci_stack_static;
19533a9fb326S[email protected] #endif
195466fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
19553a9fb326S[email protected] 
1956475c8125Smatthias.ringwald     // reference to use transport layer implementation
19573a9fb326S[email protected]     hci_stack->hci_transport = transport;
1958475c8125Smatthias.ringwald 
195911e23e5fSmatthias.ringwald     // reference to used config
19603a9fb326S[email protected]     hci_stack->config = config;
196111e23e5fSmatthias.ringwald 
19628fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
19633a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
19648fcba05dSmatthias.ringwald 
196516833f0aSmatthias.ringwald     // register packet handlers with transport
196610e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
1967f5454fc6Smatthias.ringwald 
19683a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
1969e2386ba1S[email protected] 
1970e2386ba1S[email protected]     // class of device
19713a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
1972a45d6b9fS[email protected] 
1973f20168b8Smatthias.ringwald     // bondable by default
1974f20168b8Smatthias.ringwald     hci_stack->bondable = 1;
1975f20168b8Smatthias.ringwald 
197663048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
19773a9fb326S[email protected]     hci_stack->ssp_enable = 1;
19783a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
19793a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
19803a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
198169a97523S[email protected] 
1982d950d659SMatthias Ringwald     // voice setting - signed 8 bit pcm data with CVSD over the air
1983d950d659SMatthias Ringwald     hci_stack->sco_voice_setting = 0x40;
1984d950d659SMatthias Ringwald 
1985595bdbfbS[email protected]     hci_state_reset();
1986475c8125Smatthias.ringwald }
1987475c8125Smatthias.ringwald 
19883fb36a29SMatthias Ringwald /**
19893fb36a29SMatthias Ringwald  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
19903fb36a29SMatthias Ringwald  */
19913fb36a29SMatthias Ringwald void hci_set_chipset(const btstack_chipset_t *chipset_driver){
19923fb36a29SMatthias Ringwald     hci_stack->chipset = chipset_driver;
19933fb36a29SMatthias Ringwald 
19943fb36a29SMatthias Ringwald     // reset chipset driver - init is also called on power_up
19953fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
19963fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
19973fb36a29SMatthias Ringwald     }
19983fb36a29SMatthias Ringwald }
19993fb36a29SMatthias Ringwald 
2000fb55bd0aSMatthias Ringwald /**
2001d0b87befSMatthias Ringwald  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2002fb55bd0aSMatthias Ringwald  */
2003fb55bd0aSMatthias Ringwald void hci_set_control(const btstack_control_t *hardware_control){
2004fb55bd0aSMatthias Ringwald     // references to used control implementation
2005fb55bd0aSMatthias Ringwald     hci_stack->control = hardware_control;
2006d0b87befSMatthias Ringwald     // init with transport config
2007d0b87befSMatthias Ringwald     hardware_control->init(hci_stack->config);
2008fb55bd0aSMatthias Ringwald }
2009fb55bd0aSMatthias Ringwald 
201071de195eSMatthias Ringwald void hci_close(void){
2011404843c1Smatthias.ringwald     // close remote device db
2012a98592bcSMatthias Ringwald     if (hci_stack->link_key_db) {
2013a98592bcSMatthias Ringwald         hci_stack->link_key_db->close();
2014404843c1Smatthias.ringwald     }
20153a9fb326S[email protected]     while (hci_stack->connections) {
2016bc68afe2S[email protected]         // cancel all l2cap connections
2017bc68afe2S[email protected]         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
20183a9fb326S[email protected]         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
2019f5454fc6Smatthias.ringwald     }
2020f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
20213a9fb326S[email protected] 
20223a9fb326S[email protected] #ifdef HAVE_MALLOC
20233a9fb326S[email protected]     free(hci_stack);
20243a9fb326S[email protected] #endif
20253a9fb326S[email protected]     hci_stack = NULL;
2026404843c1Smatthias.ringwald }
2027404843c1Smatthias.ringwald 
202860b9e82fSMatthias Ringwald void gap_set_class_of_device(uint32_t class_of_device){
20299e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
20309e61646fS[email protected] }
20319e61646fS[email protected] 
2032f456b2d0S[email protected] // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2033f456b2d0S[email protected] void hci_set_bd_addr(bd_addr_t addr){
2034f456b2d0S[email protected]     memcpy(hci_stack->custom_bd_addr, addr, 6);
2035f456b2d0S[email protected]     hci_stack->custom_bd_addr_set = 1;
2036f456b2d0S[email protected] }
2037f456b2d0S[email protected] 
203871de195eSMatthias Ringwald void hci_disable_l2cap_timeout_check(void){
203966fb9560S[email protected]     disable_l2cap_timeouts = 1;
204066fb9560S[email protected] }
20418d213e1aSmatthias.ringwald // State-Module-Driver overview
20428d213e1aSmatthias.ringwald // state                    module  low-level
20438d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
20448d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
20458d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
20468d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
2047d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
2048d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
2049c7e0c5f6Smatthias.ringwald 
205040d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
20517301ad89Smatthias.ringwald 
2052038bc64cSmatthias.ringwald     // power on
2053f9a30166Smatthias.ringwald     int err = 0;
20543a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
2055d0b87befSMatthias Ringwald         err = (*hci_stack->control->on)();
2056f9a30166Smatthias.ringwald     }
2057038bc64cSmatthias.ringwald     if (err){
20589da54300S[email protected]         log_error( "POWER_ON failed");
2059038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
2060038bc64cSmatthias.ringwald         return err;
2061038bc64cSmatthias.ringwald     }
2062038bc64cSmatthias.ringwald 
206324b3c629SMatthias Ringwald     // int chipset driver
20643fb36a29SMatthias Ringwald     if (hci_stack->chipset && hci_stack->chipset->init){
20653fb36a29SMatthias Ringwald         hci_stack->chipset->init(hci_stack->config);
20663fb36a29SMatthias Ringwald     }
20673fb36a29SMatthias Ringwald 
206824b3c629SMatthias Ringwald     // init transport
206924b3c629SMatthias Ringwald     if (hci_stack->hci_transport->init){
207024b3c629SMatthias Ringwald         hci_stack->hci_transport->init(hci_stack->config);
207124b3c629SMatthias Ringwald     }
207224b3c629SMatthias Ringwald 
207324b3c629SMatthias Ringwald     // open transport
207424b3c629SMatthias Ringwald     err = hci_stack->hci_transport->open();
2075038bc64cSmatthias.ringwald     if (err){
20769da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
20773a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
2078d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
2079f9a30166Smatthias.ringwald         }
2080038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
2081038bc64cSmatthias.ringwald         return err;
2082038bc64cSmatthias.ringwald     }
20838d213e1aSmatthias.ringwald     return 0;
20848d213e1aSmatthias.ringwald }
2085038bc64cSmatthias.ringwald 
208640d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
20878d213e1aSmatthias.ringwald 
20889da54300S[email protected]     log_info("hci_power_control_off");
20899418f9c9Smatthias.ringwald 
20908d213e1aSmatthias.ringwald     // close low-level device
209124b3c629SMatthias Ringwald     hci_stack->hci_transport->close();
20928d213e1aSmatthias.ringwald 
20939da54300S[email protected]     log_info("hci_power_control_off - hci_transport closed");
20949418f9c9Smatthias.ringwald 
20958d213e1aSmatthias.ringwald     // power off
20963a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
2097d0b87befSMatthias Ringwald         (*hci_stack->control->off)();
20988d213e1aSmatthias.ringwald     }
20999418f9c9Smatthias.ringwald 
21009da54300S[email protected]     log_info("hci_power_control_off - control closed");
21019418f9c9Smatthias.ringwald 
21023a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
210372ea5239Smatthias.ringwald }
210472ea5239Smatthias.ringwald 
210540d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
210672ea5239Smatthias.ringwald 
21079da54300S[email protected]     log_info("hci_power_control_sleep");
21083144bce4Smatthias.ringwald 
2109b429b9b7Smatthias.ringwald #if 0
2110b429b9b7Smatthias.ringwald     // don't close serial port during sleep
2111b429b9b7Smatthias.ringwald 
211272ea5239Smatthias.ringwald     // close low-level device
21133a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
2114b429b9b7Smatthias.ringwald #endif
211572ea5239Smatthias.ringwald 
211672ea5239Smatthias.ringwald     // sleep mode
21173a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
2118d0b87befSMatthias Ringwald         (*hci_stack->control->sleep)();
211972ea5239Smatthias.ringwald     }
2120b429b9b7Smatthias.ringwald 
21213a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
21228d213e1aSmatthias.ringwald }
21238d213e1aSmatthias.ringwald 
212440d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
2125b429b9b7Smatthias.ringwald 
21269da54300S[email protected]     log_info("hci_power_control_wake");
2127b429b9b7Smatthias.ringwald 
2128b429b9b7Smatthias.ringwald     // wake on
21293a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
2130d0b87befSMatthias Ringwald         (*hci_stack->control->wake)();
2131b429b9b7Smatthias.ringwald     }
2132b429b9b7Smatthias.ringwald 
2133b429b9b7Smatthias.ringwald #if 0
2134b429b9b7Smatthias.ringwald     // open low-level device
21353a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
2136b429b9b7Smatthias.ringwald     if (err){
21379da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
21383a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
2139d0b87befSMatthias Ringwald             (*hci_stack->control->off)();
2140b429b9b7Smatthias.ringwald         }
2141b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
2142b429b9b7Smatthias.ringwald         return err;
2143b429b9b7Smatthias.ringwald     }
2144b429b9b7Smatthias.ringwald #endif
2145b429b9b7Smatthias.ringwald 
2146b429b9b7Smatthias.ringwald     return 0;
2147b429b9b7Smatthias.ringwald }
2148b429b9b7Smatthias.ringwald 
214944935e40S[email protected] static void hci_power_transition_to_initializing(void){
215044935e40S[email protected]     // set up state machine
215144935e40S[email protected]     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
215244935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
215344935e40S[email protected]     hci_stack->state = HCI_STATE_INITIALIZING;
21545c363727SMatthias Ringwald     hci_stack->substate = HCI_INIT_SEND_RESET;
215544935e40S[email protected] }
2156b429b9b7Smatthias.ringwald 
21578d213e1aSmatthias.ringwald int hci_power_control(HCI_POWER_MODE power_mode){
2158d661ed19Smatthias.ringwald 
21599da54300S[email protected]     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
2160d661ed19Smatthias.ringwald 
21618d213e1aSmatthias.ringwald     int err = 0;
21623a9fb326S[email protected]     switch (hci_stack->state){
21638d213e1aSmatthias.ringwald 
21648d213e1aSmatthias.ringwald         case HCI_STATE_OFF:
21658d213e1aSmatthias.ringwald             switch (power_mode){
21668d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
21678d213e1aSmatthias.ringwald                     err = hci_power_control_on();
216897b61c7bS[email protected]                     if (err) {
216997b61c7bS[email protected]                         log_error("hci_power_control_on() error %u", err);
217097b61c7bS[email protected]                         return err;
217197b61c7bS[email protected]                     }
217244935e40S[email protected]                     hci_power_transition_to_initializing();
21738d213e1aSmatthias.ringwald                     break;
21748d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
21758d213e1aSmatthias.ringwald                     // do nothing
21768d213e1aSmatthias.ringwald                     break;
21778d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
2178b546ac54Smatthias.ringwald                     // do nothing (with SLEEP == OFF)
21798d213e1aSmatthias.ringwald                     break;
21808d213e1aSmatthias.ringwald             }
21818d213e1aSmatthias.ringwald             break;
21827301ad89Smatthias.ringwald 
21838d213e1aSmatthias.ringwald         case HCI_STATE_INITIALIZING:
21848d213e1aSmatthias.ringwald             switch (power_mode){
21858d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
21868d213e1aSmatthias.ringwald                     // do nothing
21878d213e1aSmatthias.ringwald                     break;
21888d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
21898d213e1aSmatthias.ringwald                     // no connections yet, just turn it off
21908d213e1aSmatthias.ringwald                     hci_power_control_off();
21918d213e1aSmatthias.ringwald                     break;
21928d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
2193b546ac54Smatthias.ringwald                     // no connections yet, just turn it off
219472ea5239Smatthias.ringwald                     hci_power_control_sleep();
21958d213e1aSmatthias.ringwald                     break;
21968d213e1aSmatthias.ringwald             }
21978d213e1aSmatthias.ringwald             break;
21987301ad89Smatthias.ringwald 
21998d213e1aSmatthias.ringwald         case HCI_STATE_WORKING:
22008d213e1aSmatthias.ringwald             switch (power_mode){
22018d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
22028d213e1aSmatthias.ringwald                     // do nothing
22038d213e1aSmatthias.ringwald                     break;
22048d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
2205c7e0c5f6Smatthias.ringwald                     // see hci_run
22063a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
22078d213e1aSmatthias.ringwald                     break;
22088d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
2209b546ac54Smatthias.ringwald                     // see hci_run
22103a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
221174b323a9SMatthias Ringwald                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
22128d213e1aSmatthias.ringwald                     break;
22138d213e1aSmatthias.ringwald             }
22148d213e1aSmatthias.ringwald             break;
22157301ad89Smatthias.ringwald 
22168d213e1aSmatthias.ringwald         case HCI_STATE_HALTING:
22178d213e1aSmatthias.ringwald             switch (power_mode){
22188d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
221944935e40S[email protected]                     hci_power_transition_to_initializing();
22208d213e1aSmatthias.ringwald                     break;
22218d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
22228d213e1aSmatthias.ringwald                     // do nothing
22238d213e1aSmatthias.ringwald                     break;
22248d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
2225b546ac54Smatthias.ringwald                     // see hci_run
22263a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
222774b323a9SMatthias Ringwald                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
22288d213e1aSmatthias.ringwald                     break;
22298d213e1aSmatthias.ringwald             }
22308d213e1aSmatthias.ringwald             break;
22318d213e1aSmatthias.ringwald 
22328d213e1aSmatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
22338d213e1aSmatthias.ringwald             switch (power_mode){
22348d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
223528171530Smatthias.ringwald 
2236423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
223728171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
2238d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
22393a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
224074b323a9SMatthias Ringwald                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
224128171530Smatthias.ringwald                         break;
224228171530Smatthias.ringwald                     }
224328171530Smatthias.ringwald #endif
224444935e40S[email protected]                     hci_power_transition_to_initializing();
22458d213e1aSmatthias.ringwald                     break;
22468d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
2247b546ac54Smatthias.ringwald                     // see hci_run
22483a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
22498d213e1aSmatthias.ringwald                     break;
22508d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
2251b546ac54Smatthias.ringwald                     // do nothing
22528d213e1aSmatthias.ringwald                     break;
22538d213e1aSmatthias.ringwald             }
22548d213e1aSmatthias.ringwald             break;
22558d213e1aSmatthias.ringwald 
22568d213e1aSmatthias.ringwald         case HCI_STATE_SLEEPING:
22578d213e1aSmatthias.ringwald             switch (power_mode){
22588d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
225928171530Smatthias.ringwald 
2260423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
226128171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
2262d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
22633a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
22645c363727SMatthias Ringwald                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2265758b46ceSmatthias.ringwald                         hci_update_scan_enable();
226628171530Smatthias.ringwald                         break;
226728171530Smatthias.ringwald                     }
226828171530Smatthias.ringwald #endif
22693144bce4Smatthias.ringwald                     err = hci_power_control_wake();
22703144bce4Smatthias.ringwald                     if (err) return err;
227144935e40S[email protected]                     hci_power_transition_to_initializing();
22728d213e1aSmatthias.ringwald                     break;
22738d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
22743a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
22758d213e1aSmatthias.ringwald                     break;
22768d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
2277b546ac54Smatthias.ringwald                     // do nothing
22788d213e1aSmatthias.ringwald                     break;
22798d213e1aSmatthias.ringwald             }
22808d213e1aSmatthias.ringwald             break;
228111e23e5fSmatthias.ringwald     }
228268d92d03Smatthias.ringwald 
2283038bc64cSmatthias.ringwald     // create internal event
2284ee8bf225Smatthias.ringwald 	hci_emit_state();
2285ee8bf225Smatthias.ringwald 
228668d92d03Smatthias.ringwald 	// trigger next/first action
228768d92d03Smatthias.ringwald 	hci_run();
228868d92d03Smatthias.ringwald 
2289475c8125Smatthias.ringwald     return 0;
2290475c8125Smatthias.ringwald }
2291475c8125Smatthias.ringwald 
2292758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
2293758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
22943a9fb326S[email protected]     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2295758b46ceSmatthias.ringwald     hci_run();
2296758b46ceSmatthias.ringwald }
2297758b46ceSmatthias.ringwald 
229815a95bd5SMatthias Ringwald void gap_discoverable_control(uint8_t enable){
2299381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
2300381fbed8Smatthias.ringwald 
23013a9fb326S[email protected]     if (hci_stack->discoverable == enable){
23023a9fb326S[email protected]         hci_emit_discoverable_enabled(hci_stack->discoverable);
2303381fbed8Smatthias.ringwald         return;
2304381fbed8Smatthias.ringwald     }
2305381fbed8Smatthias.ringwald 
23063a9fb326S[email protected]     hci_stack->discoverable = enable;
2307758b46ceSmatthias.ringwald     hci_update_scan_enable();
2308758b46ceSmatthias.ringwald }
2309b031bebbSmatthias.ringwald 
231015a95bd5SMatthias Ringwald void gap_connectable_control(uint8_t enable){
2311758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
2312758b46ceSmatthias.ringwald 
2313758b46ceSmatthias.ringwald     // don't emit event
23143a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
2315758b46ceSmatthias.ringwald 
23163a9fb326S[email protected]     hci_stack->connectable = enable;
2317758b46ceSmatthias.ringwald     hci_update_scan_enable();
2318381fbed8Smatthias.ringwald }
2319381fbed8Smatthias.ringwald 
232015a95bd5SMatthias Ringwald void gap_local_bd_addr(bd_addr_t address_buffer){
2321690bd0baS[email protected]     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
23225061f3afS[email protected] }
23235061f3afS[email protected] 
232495d71764SMatthias Ringwald static void hci_run(void){
23258a485f27Smatthias.ringwald 
2326db8bc6ffSMatthias Ringwald     // log_info("hci_run: entered");
2327665d90f2SMatthias Ringwald     btstack_linked_item_t * it;
232832ab9390Smatthias.ringwald 
2329b5d8b22bS[email protected]     // send continuation fragments first, as they block the prepared packet buffer
2330b5d8b22bS[email protected]     if (hci_stack->acl_fragmentation_total_size > 0) {
2331b5d8b22bS[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2332b5d8b22bS[email protected]         if (hci_can_send_prepared_acl_packet_now(con_handle)){
2333b5d8b22bS[email protected]             hci_connection_t *connection = hci_connection_for_handle(con_handle);
2334b5d8b22bS[email protected]             if (connection) {
2335b5d8b22bS[email protected]                 hci_send_acl_packet_fragments(connection);
2336b5d8b22bS[email protected]                 return;
2337b5d8b22bS[email protected]             }
2338b5d8b22bS[email protected]             // connection gone -> discard further fragments
2339b5d8b22bS[email protected]             hci_stack->acl_fragmentation_total_size = 0;
2340b5d8b22bS[email protected]             hci_stack->acl_fragmentation_pos = 0;
2341b5d8b22bS[email protected]         }
2342b5d8b22bS[email protected]     }
2343b5d8b22bS[email protected] 
2344d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()) return;
2345ce4c8fabSmatthias.ringwald 
2346b031bebbSmatthias.ringwald     // global/non-connection oriented commands
2347b031bebbSmatthias.ringwald 
2348b031bebbSmatthias.ringwald     // decline incoming connections
23493a9fb326S[email protected]     if (hci_stack->decline_reason){
23503a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
23513a9fb326S[email protected]         hci_stack->decline_reason = 0;
23523a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2353dbe1a790S[email protected]         return;
2354ce4c8fabSmatthias.ringwald     }
2355ce4c8fabSmatthias.ringwald 
2356b031bebbSmatthias.ringwald     // send scan enable
23573a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
23583a9fb326S[email protected]         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
23593a9fb326S[email protected]         hci_stack->new_scan_enable_value = 0xff;
2360dbe1a790S[email protected]         return;
2361b031bebbSmatthias.ringwald     }
2362b031bebbSmatthias.ringwald 
2363a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
23647bdc6798S[email protected]     if (hci_stack->state == HCI_STATE_WORKING){
236545c102fdSMatthias Ringwald         // handle le scan
23667bdc6798S[email protected]         switch(hci_stack->le_scanning_state){
23677bdc6798S[email protected]             case LE_START_SCAN:
23687bdc6798S[email protected]                 hci_stack->le_scanning_state = LE_SCANNING;
23697bdc6798S[email protected]                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
23707bdc6798S[email protected]                 return;
23717bdc6798S[email protected] 
23727bdc6798S[email protected]             case LE_STOP_SCAN:
23737bdc6798S[email protected]                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
23747bdc6798S[email protected]                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
23757bdc6798S[email protected]                 return;
23767bdc6798S[email protected]             default:
23777bdc6798S[email protected]                 break;
23787bdc6798S[email protected]         }
2379e2602ea2Smatthias.ringwald         if (hci_stack->le_scan_type != 0xff){
2380e2602ea2Smatthias.ringwald             // defaults: active scanning, accept all advertisement packets
2381e2602ea2Smatthias.ringwald             int scan_type = hci_stack->le_scan_type;
2382e2602ea2Smatthias.ringwald             hci_stack->le_scan_type = 0xff;
2383e2602ea2Smatthias.ringwald             hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->adv_addr_type, 0);
2384e2602ea2Smatthias.ringwald             return;
2385e2602ea2Smatthias.ringwald         }
238645c102fdSMatthias Ringwald         // le advertisement control
23879a2e4658SMatthias Ringwald         if (hci_stack->le_advertisements_todo){
23889a2e4658SMatthias Ringwald             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
23899a2e4658SMatthias Ringwald         }
239045c102fdSMatthias Ringwald         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
239145c102fdSMatthias Ringwald             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
239245c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertise_enable, 0);
239345c102fdSMatthias Ringwald             return;
239445c102fdSMatthias Ringwald         }
239545c102fdSMatthias Ringwald         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
239645c102fdSMatthias Ringwald             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
239745c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_parameters,
239845c102fdSMatthias Ringwald                  hci_stack->le_advertisements_interval_min,
239945c102fdSMatthias Ringwald                  hci_stack->le_advertisements_interval_max,
240045c102fdSMatthias Ringwald                  hci_stack->le_advertisements_type,
240145c102fdSMatthias Ringwald                  hci_stack->le_advertisements_own_address_type,
240245c102fdSMatthias Ringwald                  hci_stack->le_advertisements_direct_address_type,
240345c102fdSMatthias Ringwald                  hci_stack->le_advertisements_direct_address,
240445c102fdSMatthias Ringwald                  hci_stack->le_advertisements_channel_map,
240545c102fdSMatthias Ringwald                  hci_stack->le_advertisements_filter_policy);
240645c102fdSMatthias Ringwald             return;
240745c102fdSMatthias Ringwald         }
2408501f56b3SMatthias Ringwald         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
2409501f56b3SMatthias Ringwald             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
241045c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len,
241145c102fdSMatthias Ringwald                 hci_stack->le_advertisements_data);
241245c102fdSMatthias Ringwald             return;
241345c102fdSMatthias Ringwald         }
2414501f56b3SMatthias Ringwald         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
2415501f56b3SMatthias Ringwald             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
2416501f56b3SMatthias Ringwald             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len,
2417501f56b3SMatthias Ringwald                 hci_stack->le_scan_response_data);
2418501f56b3SMatthias Ringwald             return;
2419501f56b3SMatthias Ringwald         }
242045c102fdSMatthias Ringwald         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
242145c102fdSMatthias Ringwald             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
242245c102fdSMatthias Ringwald             hci_send_cmd(&hci_le_set_advertise_enable, 1);
242345c102fdSMatthias Ringwald             return;
242445c102fdSMatthias Ringwald         }
24259956955bSMatthias Ringwald 
24269956955bSMatthias Ringwald         //
24279956955bSMatthias Ringwald         // LE Whitelist Management
24289956955bSMatthias Ringwald         //
24299956955bSMatthias Ringwald 
24309956955bSMatthias Ringwald         // check if whitelist needs modification
2431665d90f2SMatthias Ringwald         btstack_linked_list_iterator_t lit;
24329956955bSMatthias Ringwald         int modification_pending = 0;
2433665d90f2SMatthias Ringwald         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2434665d90f2SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&lit)){
2435665d90f2SMatthias Ringwald             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
24369956955bSMatthias Ringwald             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
24379956955bSMatthias Ringwald                 modification_pending = 1;
24389956955bSMatthias Ringwald                 break;
24399956955bSMatthias Ringwald             }
24409956955bSMatthias Ringwald         }
244191915b0bSMatthias Ringwald 
24429956955bSMatthias Ringwald         if (modification_pending){
244391915b0bSMatthias Ringwald             // stop connnecting if modification pending
24449956955bSMatthias Ringwald             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
24459956955bSMatthias Ringwald                 hci_send_cmd(&hci_le_create_connection_cancel);
24469956955bSMatthias Ringwald                 return;
24479956955bSMatthias Ringwald             }
24489956955bSMatthias Ringwald 
24499956955bSMatthias Ringwald             // add/remove entries
2450665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2451665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&lit)){
2452665d90f2SMatthias Ringwald                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
24539956955bSMatthias Ringwald                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
24549956955bSMatthias Ringwald                     entry->state = LE_WHITELIST_ON_CONTROLLER;
24559956955bSMatthias Ringwald                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
24569956955bSMatthias Ringwald                     return;
24579956955bSMatthias Ringwald 
24589956955bSMatthias Ringwald                 }
24599956955bSMatthias Ringwald                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
24609ecbe201SMatthias Ringwald                     bd_addr_t address;
24619ecbe201SMatthias Ringwald                     bd_addr_type_t address_type = entry->address_type;
24629ecbe201SMatthias Ringwald                     memcpy(address, entry->address, 6);
2463665d90f2SMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
24649956955bSMatthias Ringwald                     btstack_memory_whitelist_entry_free(entry);
24659ecbe201SMatthias Ringwald                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
24669956955bSMatthias Ringwald                     return;
24679956955bSMatthias Ringwald                 }
24689956955bSMatthias Ringwald             }
246991915b0bSMatthias Ringwald         }
24709956955bSMatthias Ringwald 
24719956955bSMatthias Ringwald         // start connecting
247291915b0bSMatthias Ringwald         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
2473665d90f2SMatthias Ringwald             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
24749956955bSMatthias Ringwald             bd_addr_t null_addr;
24759956955bSMatthias Ringwald             memset(null_addr, 0, 6);
24769956955bSMatthias Ringwald             hci_send_cmd(&hci_le_create_connection,
24779956955bSMatthias Ringwald                  0x0060,    // scan interval: 60 ms
24789956955bSMatthias Ringwald                  0x0030,    // scan interval: 30 ms
24799956955bSMatthias Ringwald                  1,         // use whitelist
24809956955bSMatthias Ringwald                  0,         // peer address type
24819956955bSMatthias Ringwald                  null_addr,      // peer bd addr
24829956955bSMatthias Ringwald                  hci_stack->adv_addr_type, // our addr type:
24839956955bSMatthias Ringwald                  0x0008,    // conn interval min
24849956955bSMatthias Ringwald                  0x0018,    // conn interval max
24859956955bSMatthias Ringwald                  0,         // conn latency
24869956955bSMatthias Ringwald                  0x0048,    // supervision timeout
24879956955bSMatthias Ringwald                  0x0001,    // min ce length
24889956955bSMatthias Ringwald                  0x0001     // max ce length
24899956955bSMatthias Ringwald                  );
24909956955bSMatthias Ringwald             return;
24919956955bSMatthias Ringwald         }
24927bdc6798S[email protected]     }
2493b2f949feS[email protected] #endif
24947bdc6798S[email protected] 
249532ab9390Smatthias.ringwald     // send pending HCI commands
2496665d90f2SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
249705ae8de3SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) it;
249832ab9390Smatthias.ringwald 
24990bf6344aS[email protected]         switch(connection->state){
25000bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
25014f3229d8S[email protected]                 switch(connection->address_type){
25024f3229d8S[email protected]                     case BD_ADDR_TYPE_CLASSIC:
25039da54300S[email protected]                         log_info("sending hci_create_connection");
2504ad83dc6aS[email protected]                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
25054f3229d8S[email protected]                         break;
25064f3229d8S[email protected]                     default:
2507a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
25089da54300S[email protected]                         log_info("sending hci_le_create_connection");
25094f3229d8S[email protected]                         hci_send_cmd(&hci_le_create_connection,
2510b2571179Smatthias.ringwald                                      0x0060,    // scan interval: 60 ms
2511b2571179Smatthias.ringwald                                      0x0030,    // scan interval: 30 ms
25124f3229d8S[email protected]                                      0,         // don't use whitelist
25134f3229d8S[email protected]                                      connection->address_type, // peer address type
25144f3229d8S[email protected]                                      connection->address,      // peer bd addr
2515b2571179Smatthias.ringwald                                      hci_stack->adv_addr_type, // our addr type:
2516b2571179Smatthias.ringwald                                      0x0008,    // conn interval min
2517b2571179Smatthias.ringwald                                      0x0018,    // conn interval max
25184f3229d8S[email protected]                                      0,         // conn latency
2519b2571179Smatthias.ringwald                                      0x0048,    // supervision timeout
2520b2571179Smatthias.ringwald                                      0x0001,    // min ce length
2521b2571179Smatthias.ringwald                                      0x0001     // max ce length
25224f3229d8S[email protected]                                      );
25234f3229d8S[email protected] 
25244f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
2525b2f949feS[email protected] #endif
25264f3229d8S[email protected]                         break;
25274f3229d8S[email protected]                 }
2528ad83dc6aS[email protected]                 return;
2529ad83dc6aS[email protected] 
25300bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
253194e4aaa2SMatthias Ringwald                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
253232ab9390Smatthias.ringwald                 connection->state = ACCEPTED_CONNECTION_REQUEST;
25335cf766e8SMatthias Ringwald                 connection->role  = HCI_ROLE_SLAVE;
2534e35edcc1S[email protected]                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
253534d2123cS[email protected]                     hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
2536e35edcc1S[email protected]                 } else {
2537f3a16b9aSMatthias Ringwald                     // remote supported feature eSCO is set if link type is eSCO
2538f36c2fcfSMatthias Ringwald                     uint16_t max_latency;
2539f36c2fcfSMatthias Ringwald                     uint8_t  retransmission_effort;
2540f36c2fcfSMatthias Ringwald                     uint16_t packet_types;
2541f36c2fcfSMatthias Ringwald                     // remote supported feature eSCO is set if link type is eSCO
2542f3a16b9aSMatthias Ringwald                     if (connection->remote_supported_feature_eSCO){
2543f3a16b9aSMatthias Ringwald                         // eSCO: S4 - max latency == transmission interval = 0x000c == 12 ms,
2544f36c2fcfSMatthias Ringwald                         max_latency = 0x000c;
2545f36c2fcfSMatthias Ringwald                         retransmission_effort = 0x02;
2546f36c2fcfSMatthias Ringwald                         packet_types = 0x388;
2547f3a16b9aSMatthias Ringwald                     } else {
2548f3a16b9aSMatthias Ringwald                         // SCO: max latency, retransmission interval: N/A. any packet type
2549f36c2fcfSMatthias Ringwald                         max_latency = 0xffff;
255036139edcSMatthias Ringwald                         retransmission_effort = 0xff;
2551f36c2fcfSMatthias Ringwald                         packet_types = 0x003f;
255298a2fd1cSMatthias Ringwald                     }
2553f36c2fcfSMatthias Ringwald                     hci_send_cmd(&hci_accept_synchronous_connection, connection->address, 8000, 8000, max_latency, hci_stack->sco_voice_setting, retransmission_effort, packet_types);
2554e35edcc1S[email protected]                 }
2555dbe1a790S[email protected]                 return;
25560bf6344aS[email protected] 
2557a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
25580bf6344aS[email protected]             case SEND_CANCEL_CONNECTION:
25590bf6344aS[email protected]                 connection->state = SENT_CANCEL_CONNECTION;
25600bf6344aS[email protected]                 hci_send_cmd(&hci_le_create_connection_cancel);
25610bf6344aS[email protected]                 return;
2562a6725849S[email protected] #endif
25630bf6344aS[email protected]             case SEND_DISCONNECT:
25640bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
25657851196eSmatthias.ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
25660bf6344aS[email protected]                 return;
25670bf6344aS[email protected] 
25680bf6344aS[email protected]             default:
25690bf6344aS[email protected]                 break;
2570c7e0c5f6Smatthias.ringwald         }
2571c7e0c5f6Smatthias.ringwald 
257232ab9390Smatthias.ringwald         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
25739da54300S[email protected]             log_info("responding to link key request");
257434d2123cS[email protected]             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
257532ab9390Smatthias.ringwald             link_key_t link_key;
2576c77e8838S[email protected]             link_key_type_t link_key_type;
2577a98592bcSMatthias Ringwald             if ( hci_stack->link_key_db
2578a98592bcSMatthias Ringwald               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
257934d2123cS[email protected]               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
25809ab95c90S[email protected]                connection->link_key_type = link_key_type;
258132ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
258232ab9390Smatthias.ringwald             } else {
258332ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
258432ab9390Smatthias.ringwald             }
2585dbe1a790S[email protected]             return;
258632ab9390Smatthias.ringwald         }
25871d6b20aeS[email protected] 
2588899283eaS[email protected]         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
25899da54300S[email protected]             log_info("denying to pin request");
2590899283eaS[email protected]             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
259134d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
25924c57c146S[email protected]             return;
25934c57c146S[email protected]         }
25944c57c146S[email protected] 
2595dbe1a790S[email protected]         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
259634d2123cS[email protected]             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
259782d8f825S[email protected]             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
259882d8f825S[email protected]             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
2599106d6d11S[email protected]                 // tweak authentication requirements
26003a9fb326S[email protected]                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
2601106d6d11S[email protected]                 if (connection->bonding_flags & BONDING_DEDICATED){
26029faad3abS[email protected]                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
26039faad3abS[email protected]                 }
26049faad3abS[email protected]                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
26059faad3abS[email protected]                     authreq |= 1;
2606106d6d11S[email protected]                 }
26073a9fb326S[email protected]                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
2608f8fb5f6eS[email protected]             } else {
2609f8fb5f6eS[email protected]                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
2610f8fb5f6eS[email protected]             }
2611dbe1a790S[email protected]             return;
261232ab9390Smatthias.ringwald         }
261332ab9390Smatthias.ringwald 
2614dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
2615dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
261634d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
2617dbe1a790S[email protected]             return;
2618dbe1a790S[email protected]         }
2619dbe1a790S[email protected] 
2620dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
2621dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
262234d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
2623dbe1a790S[email protected]             return;
2624dbe1a790S[email protected]         }
2625afd4e962S[email protected] 
2626afd4e962S[email protected]         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
2627afd4e962S[email protected]             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
262834d2123cS[email protected]             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
26292bd8b7e7S[email protected]             return;
26302bd8b7e7S[email protected]         }
26312bd8b7e7S[email protected] 
26322bd8b7e7S[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
26332bd8b7e7S[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
263434d2123cS[email protected]             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
263534d2123cS[email protected]             return;
263634d2123cS[email protected]         }
2637ad83dc6aS[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
2638ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
26391bd5283dS[email protected]             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
264052d34f98S[email protected]             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
2641ad83dc6aS[email protected]             return;
2642ad83dc6aS[email protected]         }
264334d2123cS[email protected]         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
264434d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
264534d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
26462bd8b7e7S[email protected]             return;
2647afd4e962S[email protected]         }
2648dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
2649dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
2650dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
2651dce78009S[email protected]             return;
2652dce78009S[email protected]         }
2653da886c03S[email protected] 
2654a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
2655da886c03S[email protected]         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2656da886c03S[email protected]             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2657da886c03S[email protected] 
2658c37a3166S[email protected]             uint16_t connection_interval_min = connection->le_conn_interval_min;
2659c37a3166S[email protected]             connection->le_conn_interval_min = 0;
2660c37a3166S[email protected]             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2661c37a3166S[email protected]                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2662c37a3166S[email protected]                 0x0000, 0xffff);
2663c37a3166S[email protected]         }
2664c37a3166S[email protected] #endif
2665dbe1a790S[email protected]     }
2666c7e0c5f6Smatthias.ringwald 
266705ae8de3SMatthias Ringwald     hci_connection_t * connection;
26683a9fb326S[email protected]     switch (hci_stack->state){
26693429f56bSmatthias.ringwald         case HCI_STATE_INITIALIZING:
267074b323a9SMatthias Ringwald             hci_initializing_run();
26713429f56bSmatthias.ringwald             break;
2672c7e0c5f6Smatthias.ringwald 
2673c7e0c5f6Smatthias.ringwald         case HCI_STATE_HALTING:
2674c7e0c5f6Smatthias.ringwald 
26759da54300S[email protected]             log_info("HCI_STATE_HALTING");
26769956955bSMatthias Ringwald 
26779956955bSMatthias Ringwald             // free whitelist entries
2678a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
26799956955bSMatthias Ringwald             {
2680665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_t lit;
2681665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2682665d90f2SMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&lit)){
2683665d90f2SMatthias Ringwald                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2684665d90f2SMatthias Ringwald                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
26859956955bSMatthias Ringwald                     btstack_memory_whitelist_entry_free(entry);
26869956955bSMatthias Ringwald                 }
26879956955bSMatthias Ringwald             }
26889956955bSMatthias Ringwald #endif
2689c7e0c5f6Smatthias.ringwald             // close all open connections
26903a9fb326S[email protected]             connection =  (hci_connection_t *) hci_stack->connections;
2691c7e0c5f6Smatthias.ringwald             if (connection){
2692711e6c80SMatthias Ringwald                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
2693d94d3cafS[email protected]                 if (!hci_can_send_command_packet_now()) return;
269432ab9390Smatthias.ringwald 
26958837e9efSMatthias Ringwald                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
2696c7e0c5f6Smatthias.ringwald 
26978837e9efSMatthias Ringwald                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
26988837e9efSMatthias Ringwald                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
26998837e9efSMatthias Ringwald 
27008837e9efSMatthias Ringwald                 // ... which would be ignored anyway as we shutdown (free) the connection now
2701c7e0c5f6Smatthias.ringwald                 hci_shutdown_connection(connection);
27028837e9efSMatthias Ringwald 
27038837e9efSMatthias Ringwald                 // finally, send the disconnect command
27048837e9efSMatthias Ringwald                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
2705c7e0c5f6Smatthias.ringwald                 return;
2706c7e0c5f6Smatthias.ringwald             }
27079da54300S[email protected]             log_info("HCI_STATE_HALTING, calling off");
2708c7e0c5f6Smatthias.ringwald 
270972ea5239Smatthias.ringwald             // switch mode
2710c7e0c5f6Smatthias.ringwald             hci_power_control_off();
27119418f9c9Smatthias.ringwald 
27129da54300S[email protected]             log_info("HCI_STATE_HALTING, emitting state");
271372ea5239Smatthias.ringwald             hci_emit_state();
27149da54300S[email protected]             log_info("HCI_STATE_HALTING, done");
271572ea5239Smatthias.ringwald             break;
2716c7e0c5f6Smatthias.ringwald 
271772ea5239Smatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
27183a9fb326S[email protected]             switch(hci_stack->substate) {
271974b323a9SMatthias Ringwald                 case HCI_FALLING_ASLEEP_DISCONNECT:
27209da54300S[email protected]                     log_info("HCI_STATE_FALLING_ASLEEP");
272172ea5239Smatthias.ringwald                     // close all open connections
27223a9fb326S[email protected]                     connection =  (hci_connection_t *) hci_stack->connections;
272366da7044Smatthias.ringwald 
2724423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
272566da7044Smatthias.ringwald                     // don't close connections, if H4 supports power management
2726d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
272766da7044Smatthias.ringwald                         connection = NULL;
272866da7044Smatthias.ringwald                     }
272966da7044Smatthias.ringwald #endif
273072ea5239Smatthias.ringwald                     if (connection){
273132ab9390Smatthias.ringwald 
273272ea5239Smatthias.ringwald                         // send disconnect
2733d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
273432ab9390Smatthias.ringwald 
27359da54300S[email protected]                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
27366ad890d3Smatthias.ringwald                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
273772ea5239Smatthias.ringwald 
273872ea5239Smatthias.ringwald                         // send disconnected event right away - causes higher layer connections to get closed, too.
273972ea5239Smatthias.ringwald                         hci_shutdown_connection(connection);
274072ea5239Smatthias.ringwald                         return;
274172ea5239Smatthias.ringwald                     }
274272ea5239Smatthias.ringwald 
274392368cd3S[email protected]                     if (hci_classic_supported()){
274489db417bSmatthias.ringwald                         // disable page and inquiry scan
2745d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
274632ab9390Smatthias.ringwald 
27479da54300S[email protected]                         log_info("HCI_STATE_HALTING, disabling inq scans");
27483a9fb326S[email protected]                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
274989db417bSmatthias.ringwald 
275089db417bSmatthias.ringwald                         // continue in next sub state
275174b323a9SMatthias Ringwald                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
275289db417bSmatthias.ringwald                         break;
275392368cd3S[email protected]                     }
275492368cd3S[email protected]                     // fall through for ble-only chips
275592368cd3S[email protected] 
275674b323a9SMatthias Ringwald                 case HCI_FALLING_ASLEEP_COMPLETE:
27579da54300S[email protected]                     log_info("HCI_STATE_HALTING, calling sleep");
2758423a3e49SMatthias Ringwald #ifdef HAVE_PLATFORM_IPHONE_OS
275928171530Smatthias.ringwald                     // don't actually go to sleep, if H4 supports power management
2760d0b87befSMatthias Ringwald                     if (btstack_control_iphone_power_management_enabled()){
276128171530Smatthias.ringwald                         // SLEEP MODE reached
27623a9fb326S[email protected]                         hci_stack->state = HCI_STATE_SLEEPING;
276328171530Smatthias.ringwald                         hci_emit_state();
276428171530Smatthias.ringwald                         break;
276528171530Smatthias.ringwald                     }
276628171530Smatthias.ringwald #endif
276772ea5239Smatthias.ringwald                     // switch mode
27683a9fb326S[email protected]                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
2769c7e0c5f6Smatthias.ringwald                     hci_emit_state();
277028171530Smatthias.ringwald                     break;
277128171530Smatthias.ringwald 
277289db417bSmatthias.ringwald                 default:
277389db417bSmatthias.ringwald                     break;
277489db417bSmatthias.ringwald             }
2775c7e0c5f6Smatthias.ringwald             break;
2776c7e0c5f6Smatthias.ringwald 
27773429f56bSmatthias.ringwald         default:
27783429f56bSmatthias.ringwald             break;
27791f504dbdSmatthias.ringwald     }
27803429f56bSmatthias.ringwald }
278116833f0aSmatthias.ringwald 
278231452debSmatthias.ringwald int hci_send_cmd_packet(uint8_t *packet, int size){
2783c8e4258aSmatthias.ringwald     bd_addr_t addr;
2784c8e4258aSmatthias.ringwald     hci_connection_t * conn;
2785c8e4258aSmatthias.ringwald     // house-keeping
2786c8e4258aSmatthias.ringwald 
2787c8e4258aSmatthias.ringwald     // create_connection?
2788c8e4258aSmatthias.ringwald     if (IS_COMMAND(packet, hci_create_connection)){
2789724d70a2SMatthias Ringwald         reverse_bd_addr(&packet[3], addr);
27909da54300S[email protected]         log_info("Create_connection to %s", bd_addr_to_str(addr));
2791c8e4258aSmatthias.ringwald 
27922e77e513S[email protected]         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2793ad83dc6aS[email protected]         if (!conn){
279496a45072S[email protected]             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
279517f1ba2aSmatthias.ringwald             if (!conn){
279617f1ba2aSmatthias.ringwald                 // notify client that alloc failed
279717f1ba2aSmatthias.ringwald                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
279817f1ba2aSmatthias.ringwald                 return 0; // don't sent packet to controller
279917f1ba2aSmatthias.ringwald             }
2800ad83dc6aS[email protected]             conn->state = SEND_CREATE_CONNECTION;
2801ad83dc6aS[email protected]         }
2802ad83dc6aS[email protected]         log_info("conn state %u", conn->state);
2803ad83dc6aS[email protected]         switch (conn->state){
2804ad83dc6aS[email protected]             // if connection active exists
2805ad83dc6aS[email protected]             case OPEN:
280662bda3fbS[email protected]                 // and OPEN, emit connection complete command, don't send to controller
2807ad83dc6aS[email protected]                 hci_emit_connection_complete(conn, 0);
280862bda3fbS[email protected]                 return 0;
2809ad83dc6aS[email protected]             case SEND_CREATE_CONNECTION:
2810ad83dc6aS[email protected]                 // connection created by hci, e.g. dedicated bonding
2811ad83dc6aS[email protected]                 break;
2812ad83dc6aS[email protected]             default:
2813ad83dc6aS[email protected]                 // otherwise, just ignore as it is already in the open process
2814ad83dc6aS[email protected]                 return 0;
2815ad83dc6aS[email protected]         }
2816c8e4258aSmatthias.ringwald         conn->state = SENT_CREATE_CONNECTION;
2817c8e4258aSmatthias.ringwald     }
28187fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_reply)){
28197fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
28207fde4af9Smatthias.ringwald     }
28217fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
28227fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
28237fde4af9Smatthias.ringwald     }
28247fde4af9Smatthias.ringwald 
28258ef73945Smatthias.ringwald     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
2826a98592bcSMatthias Ringwald         if (hci_stack->link_key_db){
2827724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[3], addr);
2828a98592bcSMatthias Ringwald             hci_stack->link_key_db->delete_link_key(addr);
28298ef73945Smatthias.ringwald         }
28308ef73945Smatthias.ringwald     }
2831c8e4258aSmatthias.ringwald 
28326724cd9eS[email protected]     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
28336724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
2834724d70a2SMatthias Ringwald         reverse_bd_addr(&packet[3], addr);
28352e77e513S[email protected]         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
28366724cd9eS[email protected]         if (conn){
28376724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
28386724cd9eS[email protected]         }
28396724cd9eS[email protected]     }
28406724cd9eS[email protected] 
28416724cd9eS[email protected]     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
28426724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
28436724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
28446724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
2845724d70a2SMatthias Ringwald         reverse_bd_addr(&packet[3], addr);
28462e77e513S[email protected]         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
28476724cd9eS[email protected]         if (conn){
28486724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
28496724cd9eS[email protected]         }
28506724cd9eS[email protected]     }
28516724cd9eS[email protected] 
28524b3e1e19SMatthias Ringwald     if (IS_COMMAND(packet, hci_write_loopback_mode)){
28534b3e1e19SMatthias Ringwald         hci_stack->loopback_mode = packet[3];
28544b3e1e19SMatthias Ringwald     }
28554b3e1e19SMatthias Ringwald 
2856a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
285769a97523S[email protected]     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
28583a9fb326S[email protected]         hci_stack->adv_addr_type = packet[8];
285969a97523S[email protected]     }
286069a97523S[email protected]     if (IS_COMMAND(packet, hci_le_set_random_address)){
2861724d70a2SMatthias Ringwald         reverse_bd_addr(&packet[3], hci_stack->adv_address);
286269a97523S[email protected]     }
2863171293d3SMatthias Ringwald     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
2864171293d3SMatthias Ringwald         hci_stack->le_advertisements_active = packet[3];
2865171293d3SMatthias Ringwald     }
2866b04dfa37SMatthias Ringwald     if (IS_COMMAND(packet, hci_le_create_connection)){
2867b04dfa37SMatthias Ringwald         // white list used?
2868b04dfa37SMatthias Ringwald         uint8_t initiator_filter_policy = packet[7];
2869b04dfa37SMatthias Ringwald         switch (initiator_filter_policy){
2870b04dfa37SMatthias Ringwald             case 0:
2871b04dfa37SMatthias Ringwald                 // whitelist not used
2872b04dfa37SMatthias Ringwald                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
2873b04dfa37SMatthias Ringwald                 break;
2874b04dfa37SMatthias Ringwald             case 1:
2875b04dfa37SMatthias Ringwald                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
2876b04dfa37SMatthias Ringwald                 break;
2877b04dfa37SMatthias Ringwald             default:
2878b04dfa37SMatthias Ringwald                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
2879b04dfa37SMatthias Ringwald                 break;
2880b04dfa37SMatthias Ringwald         }
2881b04dfa37SMatthias Ringwald     }
2882b04dfa37SMatthias Ringwald     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
2883b04dfa37SMatthias Ringwald         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2884b04dfa37SMatthias Ringwald     }
288569a97523S[email protected] #endif
288669a97523S[email protected] 
28873a9fb326S[email protected]     hci_stack->num_cmd_packets--;
28885bb5bc3eS[email protected] 
28895bb5bc3eS[email protected]     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
28906b4af23dS[email protected]     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
28916b4af23dS[email protected] 
2892d051460cS[email protected]     // release packet buffer for synchronous transport implementations
2893c8b9416aS[email protected]     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
28946b4af23dS[email protected]         hci_stack->hci_packet_buffer_reserved = 0;
28956b4af23dS[email protected]     }
28966b4af23dS[email protected] 
28976b4af23dS[email protected]     return err;
289831452debSmatthias.ringwald }
28998adf0ddaSmatthias.ringwald 
29002bd8b7e7S[email protected] // disconnect because of security block
29012bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
29022bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
29032bd8b7e7S[email protected]     if (!connection) return;
29042bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
29052bd8b7e7S[email protected] }
29062bd8b7e7S[email protected] 
29072bd8b7e7S[email protected] 
2908dbe1a790S[email protected] // Configure Secure Simple Pairing
2909dbe1a790S[email protected] 
2910dbe1a790S[email protected] // enable will enable SSP during init
291115a95bd5SMatthias Ringwald void gap_ssp_set_enable(int enable){
29123a9fb326S[email protected]     hci_stack->ssp_enable = enable;
2913dbe1a790S[email protected] }
2914dbe1a790S[email protected] 
291595d71764SMatthias Ringwald static int hci_local_ssp_activated(void){
291615a95bd5SMatthias Ringwald     return gap_ssp_supported() && hci_stack->ssp_enable;
29172bd8b7e7S[email protected] }
29182bd8b7e7S[email protected] 
2919dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
292015a95bd5SMatthias Ringwald void gap_ssp_set_io_capability(int io_capability){
29213a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
2922dbe1a790S[email protected] }
292315a95bd5SMatthias Ringwald void gap_ssp_set_authentication_requirement(int authentication_requirement){
29243a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
2925dbe1a790S[email protected] }
2926dbe1a790S[email protected] 
2927dbe1a790S[email protected] // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
292815a95bd5SMatthias Ringwald void gap_ssp_set_auto_accept(int auto_accept){
29293a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
2930dbe1a790S[email protected] }
2931dbe1a790S[email protected] 
29321cd208adSmatthias.ringwald /**
29331cd208adSmatthias.ringwald  * pre: numcmds >= 0 - it's allowed to send a command to the controller
29341cd208adSmatthias.ringwald  */
2935fe35119dSmatthias.ringwald int hci_send_cmd(const hci_cmd_t *cmd, ...){
29365127cc62S[email protected] 
2937d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()){
29389d14b626S[email protected]         log_error("hci_send_cmd called but cannot send packet now");
29399d14b626S[email protected]         return 0;
29409d14b626S[email protected]     }
29419d14b626S[email protected] 
29425127cc62S[email protected]     // for HCI INITIALIZATION
29439da54300S[email protected]     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
29445127cc62S[email protected]     hci_stack->last_cmd_opcode = cmd->opcode;
29455127cc62S[email protected] 
29469d14b626S[email protected]     hci_reserve_packet_buffer();
29479d14b626S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
29489d14b626S[email protected] 
29491cd208adSmatthias.ringwald     va_list argptr;
29501cd208adSmatthias.ringwald     va_start(argptr, cmd);
2951bcc59d6cSMatthias Ringwald     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
29521cd208adSmatthias.ringwald     va_end(argptr);
29539d14b626S[email protected] 
29549d14b626S[email protected]     return hci_send_cmd_packet(packet, size);
295593b8dc03Smatthias.ringwald }
2956c8e4258aSmatthias.ringwald 
2957ee091cf1Smatthias.ringwald // Create various non-HCI events.
2958ee091cf1Smatthias.ringwald // TODO: generalize, use table similar to hci_create_command
2959ee091cf1Smatthias.ringwald 
2960d6b06661SMatthias Ringwald static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
2961fb37a842SMatthias Ringwald     // dump packet
2962d6b06661SMatthias Ringwald     if (dump) {
2963300c1ba4SMatthias Ringwald         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
2964d6b06661SMatthias Ringwald     }
29651ef6bb52SMatthias Ringwald 
2966fb37a842SMatthias Ringwald     // dispatch to all event handlers
29671ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_t it;
29681ef6bb52SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
29691ef6bb52SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
29701ef6bb52SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
2971d9a7306aSMatthias Ringwald         entry->callback(HCI_EVENT_PACKET, 0, event, size);
29721ef6bb52SMatthias Ringwald     }
2973d6b06661SMatthias Ringwald }
2974d6b06661SMatthias Ringwald 
2975d6b06661SMatthias Ringwald static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
2976fb37a842SMatthias Ringwald     if (!hci_stack->acl_packet_handler) return;
2977fb37a842SMatthias Ringwald     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, packet, size);
2978d6b06661SMatthias Ringwald }
2979d6b06661SMatthias Ringwald 
2980701e3307SMatthias Ringwald static void hci_notify_if_sco_can_send_now(void){
29813bc639ceSMatthias Ringwald     // notify SCO sender if waiting
2982701e3307SMatthias Ringwald     if (!hci_stack->sco_waiting_for_can_send_now) return;
2983701e3307SMatthias Ringwald     if (hci_can_send_sco_packet_now()){
29843bc639ceSMatthias Ringwald         hci_stack->sco_waiting_for_can_send_now = 0;
2985701e3307SMatthias Ringwald         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
2986701e3307SMatthias Ringwald         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
2987701e3307SMatthias Ringwald         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
29883bc639ceSMatthias Ringwald     }
29893bc639ceSMatthias Ringwald }
29903bc639ceSMatthias Ringwald 
299171de195eSMatthias Ringwald void hci_emit_state(void){
29923a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2993425d1371Smatthias.ringwald     uint8_t event[3];
299480d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
2995425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
29963a9fb326S[email protected]     event[2] = hci_stack->state;
2997d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
2998c8e4258aSmatthias.ringwald }
2999c8e4258aSmatthias.ringwald 
3000b83d5eabSMatthias Ringwald static void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
3001425d1371Smatthias.ringwald     uint8_t event[13];
3002c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3003425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
300417f1ba2aSmatthias.ringwald     event[2] = status;
3005f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 3, conn->con_handle);
3006724d70a2SMatthias Ringwald     reverse_bd_addr(conn->address, &event[5]);
3007c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
3008c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
3009d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
3010c8e4258aSmatthias.ringwald }
3011c8e4258aSmatthias.ringwald 
3012fc64f94aSMatthias 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){
30134f3229d8S[email protected]     uint8_t event[21];
30144f3229d8S[email protected]     event[0] = HCI_EVENT_LE_META;
30154f3229d8S[email protected]     event[1] = sizeof(event) - 2;
30164f3229d8S[email protected]     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
30174f3229d8S[email protected]     event[3] = status;
3018fc64f94aSMatthias Ringwald     little_endian_store_16(event, 4, con_handle);
30194f3229d8S[email protected]     event[6] = 0; // TODO: role
30206e2e9a6bS[email protected]     event[7] = address_type;
3021724d70a2SMatthias Ringwald     reverse_bd_addr(address, &event[8]);
3022f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, 0); // interval
3023f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 16, 0); // latency
3024f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 18, 0); // supervision timeout
30254f3229d8S[email protected]     event[20] = 0; // master clock accuracy
3026d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
30274f3229d8S[email protected] }
30284f3229d8S[email protected] 
3029fc64f94aSMatthias Ringwald static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
3030425d1371Smatthias.ringwald     uint8_t event[6];
30313c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
3032e518c4b8Smatthias.ringwald     event[1] = sizeof(event) - 2;
30333c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
3034fc64f94aSMatthias Ringwald     little_endian_store_16(event, 3, con_handle);
30353c4d4b90Smatthias.ringwald     event[5] = reason;
3036d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
30373c4d4b90Smatthias.ringwald }
30383c4d4b90Smatthias.ringwald 
3039b83d5eabSMatthias Ringwald static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
304066fb9560S[email protected]     if (disable_l2cap_timeouts) return;
3041e0abb8e7S[email protected]     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3042425d1371Smatthias.ringwald     uint8_t event[4];
304380d52d6bSmatthias.ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3044425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
3045f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 2, conn->con_handle);
3046d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
3047ee091cf1Smatthias.ringwald }
304843bfb1bdSmatthias.ringwald 
3049b83d5eabSMatthias Ringwald static void hci_emit_nr_connections_changed(void){
3050e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
3051425d1371Smatthias.ringwald     uint8_t event[3];
305280d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3053425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
305443bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
3055d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
305643bfb1bdSmatthias.ringwald }
3057038bc64cSmatthias.ringwald 
3058b83d5eabSMatthias Ringwald static void hci_emit_hci_open_failed(void){
3059e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
3060425d1371Smatthias.ringwald     uint8_t event[2];
306180d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
3062425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
3063d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
3064038bc64cSmatthias.ringwald }
30651b0e3922Smatthias.ringwald 
3066b83d5eabSMatthias Ringwald static void hci_emit_discoverable_enabled(uint8_t enabled){
3067e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
3068425d1371Smatthias.ringwald     uint8_t event[3];
3069381fbed8Smatthias.ringwald     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
3070425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
3071381fbed8Smatthias.ringwald     event[2] = enabled;
3072d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
3073381fbed8Smatthias.ringwald }
3074458bf4e8S[email protected] 
3075b83d5eabSMatthias Ringwald static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3076df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3077a00031e2S[email protected]     uint8_t event[5];
3078e00caf9cS[email protected]     int pos = 0;
30795611a760SMatthias Ringwald     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3080e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
3081f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
3082e00caf9cS[email protected]     pos += 2;
3083e00caf9cS[email protected]     event[pos++] = level;
3084d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
3085e00caf9cS[email protected] }
3086e00caf9cS[email protected] 
3087b83d5eabSMatthias Ringwald static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
3088ad83dc6aS[email protected]     log_info("hci_emit_dedicated_bonding_result %u ", status);
3089ad83dc6aS[email protected]     uint8_t event[9];
3090ad83dc6aS[email protected]     int pos = 0;
30915611a760SMatthias Ringwald     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
3092ad83dc6aS[email protected]     event[pos++] = sizeof(event) - 2;
3093ad83dc6aS[email protected]     event[pos++] = status;
3094724d70a2SMatthias Ringwald     reverse_bd_addr(address, &event[pos]);
3095ad83dc6aS[email protected]     pos += 6;
3096d6b06661SMatthias Ringwald     hci_emit_event(event, sizeof(event), 1);
3097ad83dc6aS[email protected] }
3098ad83dc6aS[email protected] 
309998a2fd1cSMatthias Ringwald // query if remote side supports eSCO
3100073bd0faSMatthias Ringwald int hci_remote_esco_supported(hci_con_handle_t con_handle){
310198a2fd1cSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
310298a2fd1cSMatthias Ringwald     if (!connection) return 0;
310398a2fd1cSMatthias Ringwald     return connection->remote_supported_feature_eSCO;
310498a2fd1cSMatthias Ringwald }
310598a2fd1cSMatthias Ringwald 
31062bd8b7e7S[email protected] // query if remote side supports SSP
31072bd8b7e7S[email protected] int hci_remote_ssp_supported(hci_con_handle_t con_handle){
31082bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
31092bd8b7e7S[email protected]     if (!connection) return 0;
31102bd8b7e7S[email protected]     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
31112bd8b7e7S[email protected] }
31122bd8b7e7S[email protected] 
311315a95bd5SMatthias Ringwald int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
3114df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3115df3354fcS[email protected] }
3116df3354fcS[email protected] 
3117458bf4e8S[email protected] // GAP API
3118458bf4e8S[email protected] /**
3119458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
3120458bf4e8S[email protected]  * @praram enabled
3121458bf4e8S[email protected]  */
31224c57c146S[email protected] void gap_set_bondable_mode(int enable){
31233a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
3124458bf4e8S[email protected] }
31254ef6443cSMatthias Ringwald /**
31264ef6443cSMatthias Ringwald  * @brief Get bondable mode.
31274ef6443cSMatthias Ringwald  * @return 1 if bondable
31284ef6443cSMatthias Ringwald  */
31294ef6443cSMatthias Ringwald int gap_get_bondable_mode(void){
31304ef6443cSMatthias Ringwald     return hci_stack->bondable;
31314ef6443cSMatthias Ringwald }
3132cb230b9dS[email protected] 
3133cb230b9dS[email protected] /**
313434d2123cS[email protected]  * @brief map link keys to security levels
3135cb230b9dS[email protected]  */
313634d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
313734d2123cS[email protected]     switch (link_key_type){
31383c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
31393c68dfa9S[email protected]             return LEVEL_4;
31403c68dfa9S[email protected]         case COMBINATION_KEY:
31413c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
31423c68dfa9S[email protected]             return LEVEL_3;
31433c68dfa9S[email protected]         default:
31443c68dfa9S[email protected]             return LEVEL_2;
31453c68dfa9S[email protected]     }
3146cb230b9dS[email protected] }
3147cb230b9dS[email protected] 
3148a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
314934d2123cS[email protected]     if (!connection) return LEVEL_0;
315034d2123cS[email protected]     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
315134d2123cS[email protected]     return gap_security_level_for_link_key_type(connection->link_key_type);
315234d2123cS[email protected] }
315334d2123cS[email protected] 
315434d2123cS[email protected] 
3155106d6d11S[email protected] int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
31565127cc62S[email protected]     log_info("gap_mitm_protection_required_for_security_level %u", level);
3157106d6d11S[email protected]     return level > LEVEL_2;
3158106d6d11S[email protected] }
3159106d6d11S[email protected] 
316034d2123cS[email protected] /**
316134d2123cS[email protected]  * @brief get current security level
316234d2123cS[email protected]  */
316334d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
316434d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
316534d2123cS[email protected]     if (!connection) return LEVEL_0;
316634d2123cS[email protected]     return gap_security_level_for_connection(connection);
316734d2123cS[email protected] }
316834d2123cS[email protected] 
3169cb230b9dS[email protected] /**
3170cb230b9dS[email protected]  * @brief request connection to device to
3171cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
3172cb230b9dS[email protected]  */
317334d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
317434d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
317534d2123cS[email protected]     if (!connection){
3176a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
317734d2123cS[email protected]         return;
317834d2123cS[email protected]     }
317934d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
318034d2123cS[email protected]     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
318134d2123cS[email protected]     if (current_level >= requested_level){
3182a00031e2S[email protected]         hci_emit_security_level(con_handle, current_level);
318334d2123cS[email protected]         return;
318434d2123cS[email protected]     }
3185a00031e2S[email protected] 
318634d2123cS[email protected]     connection->requested_security_level = requested_level;
3187a00031e2S[email protected] 
318825bf5872S[email protected] #if 0
318925bf5872S[email protected]     // sending encryption request without a link key results in an error.
319025bf5872S[email protected]     // TODO: figure out how to use it properly
319125bf5872S[email protected] 
3192fb8ba0dbS[email protected]     // would enabling ecnryption suffice (>= LEVEL_2)?
3193a98592bcSMatthias Ringwald     if (hci_stack->link_key_db){
3194a00031e2S[email protected]         link_key_type_t link_key_type;
3195a00031e2S[email protected]         link_key_t      link_key;
3196a98592bcSMatthias Ringwald         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3197a00031e2S[email protected]             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3198a00031e2S[email protected]                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3199a00031e2S[email protected]                 return;
3200a00031e2S[email protected]             }
3201a00031e2S[email protected]         }
3202a00031e2S[email protected]     }
320325bf5872S[email protected] #endif
3204a00031e2S[email protected] 
32051eb2563eS[email protected]     // try to authenticate connection
32061eb2563eS[email protected]     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3207e80b2cf9S[email protected]     hci_run();
3208e00caf9cS[email protected] }
3209ad83dc6aS[email protected] 
3210ad83dc6aS[email protected] /**
3211ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
3212ad83dc6aS[email protected]  * @param device
3213ad83dc6aS[email protected]  * @param request MITM protection
3214ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
3215ad83dc6aS[email protected]  */
3216ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3217ad83dc6aS[email protected] 
3218ad83dc6aS[email protected]     // create connection state machine
321996a45072S[email protected]     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3220ad83dc6aS[email protected] 
3221ad83dc6aS[email protected]     if (!connection){
3222ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
3223ad83dc6aS[email protected]     }
3224ad83dc6aS[email protected] 
3225ad83dc6aS[email protected]     // delete linkn key
322615a95bd5SMatthias Ringwald     gap_drop_link_key_for_bd_addr(device);
3227ad83dc6aS[email protected] 
3228ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
3229ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
3230ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
32315127cc62S[email protected]     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
3232ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
3233ad83dc6aS[email protected] 
3234ad83dc6aS[email protected]     // wait for GAP Security Result and send GAP Dedicated Bonding complete
3235ad83dc6aS[email protected] 
3236ad83dc6aS[email protected]     // handle: connnection failure (connection complete != ok)
3237ad83dc6aS[email protected]     // handle: authentication failure
3238ad83dc6aS[email protected]     // handle: disconnect on done
3239ad83dc6aS[email protected] 
3240ad83dc6aS[email protected]     hci_run();
3241ad83dc6aS[email protected] 
3242ad83dc6aS[email protected]     return 0;
3243ad83dc6aS[email protected] }
32448e618f72S[email protected] 
32458e618f72S[email protected] void gap_set_local_name(const char * local_name){
32468e618f72S[email protected]     hci_stack->local_name = local_name;
32478e618f72S[email protected] }
32488e618f72S[email protected] 
3249d8e8f12aSMatthias Ringwald void gap_start_scan(void){
3250d8e8f12aSMatthias Ringwald     if (hci_stack->le_scanning_state == LE_SCANNING) return;
32517bdc6798S[email protected]     hci_stack->le_scanning_state = LE_START_SCAN;
32527bdc6798S[email protected]     hci_run();
32537bdc6798S[email protected] }
32548e618f72S[email protected] 
3255d8e8f12aSMatthias Ringwald void gap_stop_scan(void){
3256d8e8f12aSMatthias Ringwald     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return;
32577bdc6798S[email protected]     hci_stack->le_scanning_state = LE_STOP_SCAN;
32587bdc6798S[email protected]     hci_run();
32597bdc6798S[email protected] }
32604f3229d8S[email protected] 
3261d8e8f12aSMatthias Ringwald void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
3262ef11999fSmatthias.ringwald     hci_stack->le_scan_type     = scan_type;
3263ef11999fSmatthias.ringwald     hci_stack->le_scan_interval = scan_interval;
3264ef11999fSmatthias.ringwald     hci_stack->le_scan_window   = scan_window;
3265ef11999fSmatthias.ringwald     hci_run();
3266ef11999fSmatthias.ringwald }
32674f3229d8S[email protected] 
3268d8e8f12aSMatthias Ringwald uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
32694f3229d8S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
32704f3229d8S[email protected]     if (!conn){
3271d8e8f12aSMatthias Ringwald         log_info("gap_connect: no connection exists yet, creating context");
32722e77e513S[email protected]         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
32734f3229d8S[email protected]         if (!conn){
32744f3229d8S[email protected]             // notify client that alloc failed
32756e2e9a6bS[email protected]             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3276d8e8f12aSMatthias Ringwald             log_info("gap_connect: failed to alloc hci_connection_t");
3277472a5742SMatthias Ringwald             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
32784f3229d8S[email protected]         }
32794f3229d8S[email protected]         conn->state = SEND_CREATE_CONNECTION;
3280d8e8f12aSMatthias Ringwald         log_info("gap_connect: send create connection next");
3281564fca32S[email protected]         hci_run();
3282616edd56SMatthias Ringwald         return 0;
32834f3229d8S[email protected]     }
32840bf6344aS[email protected] 
32850bf6344aS[email protected]     if (!hci_is_le_connection(conn) ||
32860bf6344aS[email protected]         conn->state == SEND_CREATE_CONNECTION ||
32870bf6344aS[email protected]         conn->state == SENT_CREATE_CONNECTION) {
32882e77e513S[email protected]         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
3289d8e8f12aSMatthias Ringwald         log_error("gap_connect: classic connection or connect is already being created");
3290616edd56SMatthias Ringwald         return GATT_CLIENT_IN_WRONG_STATE;
32910bf6344aS[email protected]     }
32920bf6344aS[email protected] 
3293d8e8f12aSMatthias Ringwald     log_info("gap_connect: context exists with state %u", conn->state);
32942e77e513S[email protected]     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
32954f3229d8S[email protected]     hci_run();
3296616edd56SMatthias Ringwald     return 0;
32974f3229d8S[email protected] }
32984f3229d8S[email protected] 
32997851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
3300d8e8f12aSMatthias Ringwald static hci_connection_t * gap_get_outgoing_connection(void){
3301665d90f2SMatthias Ringwald     btstack_linked_item_t *it;
3302665d90f2SMatthias Ringwald     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
33030bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
33040bf6344aS[email protected]         if (!hci_is_le_connection(conn)) continue;
33050bf6344aS[email protected]         switch (conn->state){
3306a6725849S[email protected]             case SEND_CREATE_CONNECTION:
33077851196eSmatthias.ringwald             case SENT_CREATE_CONNECTION:
33087851196eSmatthias.ringwald                 return conn;
33097851196eSmatthias.ringwald             default:
33107851196eSmatthias.ringwald                 break;
33117851196eSmatthias.ringwald         };
33127851196eSmatthias.ringwald     }
33137851196eSmatthias.ringwald     return NULL;
33147851196eSmatthias.ringwald }
33157851196eSmatthias.ringwald 
3316d8e8f12aSMatthias Ringwald uint8_t gap_connect_cancel(void){
3317d8e8f12aSMatthias Ringwald     hci_connection_t * conn = gap_get_outgoing_connection();
3318616edd56SMatthias Ringwald     if (!conn) return 0;
33197851196eSmatthias.ringwald     switch (conn->state){
33207851196eSmatthias.ringwald         case SEND_CREATE_CONNECTION:
33217851196eSmatthias.ringwald             // skip sending create connection and emit event instead
33222e77e513S[email protected]             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
3323665d90f2SMatthias Ringwald             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
33247851196eSmatthias.ringwald             btstack_memory_hci_connection_free( conn );
33250bf6344aS[email protected]             break;
3326a6725849S[email protected]         case SENT_CREATE_CONNECTION:
33277851196eSmatthias.ringwald             // request to send cancel connection
33280bf6344aS[email protected]             conn->state = SEND_CANCEL_CONNECTION;
33290bf6344aS[email protected]             hci_run();
33300bf6344aS[email protected]             break;
33310bf6344aS[email protected]         default:
33320bf6344aS[email protected]             break;
33330bf6344aS[email protected]     }
3334616edd56SMatthias Ringwald     return 0;
3335e31f89a7S[email protected] }
33364f3229d8S[email protected] 
3337c37a3166S[email protected] /**
3338c37a3166S[email protected]  * @brief Updates the connection parameters for a given LE connection
3339c37a3166S[email protected]  * @param handle
3340c37a3166S[email protected]  * @param conn_interval_min (unit: 1.25ms)
3341c37a3166S[email protected]  * @param conn_interval_max (unit: 1.25ms)
3342c37a3166S[email protected]  * @param conn_latency
3343c37a3166S[email protected]  * @param supervision_timeout (unit: 10ms)
3344c37a3166S[email protected]  * @returns 0 if ok
3345c37a3166S[email protected]  */
3346c37a3166S[email protected] int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3347c37a3166S[email protected]     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3348c37a3166S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3349c37a3166S[email protected]     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3350c37a3166S[email protected]     connection->le_conn_interval_min = conn_interval_min;
3351c37a3166S[email protected]     connection->le_conn_interval_max = conn_interval_max;
3352c37a3166S[email protected]     connection->le_conn_latency = conn_latency;
3353c37a3166S[email protected]     connection->le_supervision_timeout = supervision_timeout;
335484cf6d83SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
3355cfc59f1bSMatthias Ringwald     hci_run();
3356c37a3166S[email protected]     return 0;
3357c37a3166S[email protected] }
3358c37a3166S[email protected] 
335945c102fdSMatthias Ringwald /**
3360b68d7bc3SMatthias Ringwald  * @brief Request an update of the connection parameter for a given LE connection
3361b68d7bc3SMatthias Ringwald  * @param handle
3362b68d7bc3SMatthias Ringwald  * @param conn_interval_min (unit: 1.25ms)
3363b68d7bc3SMatthias Ringwald  * @param conn_interval_max (unit: 1.25ms)
3364b68d7bc3SMatthias Ringwald  * @param conn_latency
3365b68d7bc3SMatthias Ringwald  * @param supervision_timeout (unit: 10ms)
3366b68d7bc3SMatthias Ringwald  * @returns 0 if ok
3367b68d7bc3SMatthias Ringwald  */
3368b68d7bc3SMatthias Ringwald int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3369b68d7bc3SMatthias Ringwald     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3370b68d7bc3SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3371b68d7bc3SMatthias Ringwald     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3372b68d7bc3SMatthias Ringwald     connection->le_conn_interval_min = conn_interval_min;
3373b68d7bc3SMatthias Ringwald     connection->le_conn_interval_max = conn_interval_max;
3374b68d7bc3SMatthias Ringwald     connection->le_conn_latency = conn_latency;
3375b68d7bc3SMatthias Ringwald     connection->le_supervision_timeout = supervision_timeout;
3376b68d7bc3SMatthias Ringwald     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
3377b68d7bc3SMatthias Ringwald     hci_run();
3378b68d7bc3SMatthias Ringwald     return 0;
3379b68d7bc3SMatthias Ringwald }
3380b68d7bc3SMatthias Ringwald 
3381501f56b3SMatthias Ringwald static void gap_advertisments_changed(void){
3382501f56b3SMatthias Ringwald     // disable advertisements before updating adv, scan data, or adv params
3383501f56b3SMatthias Ringwald     if (hci_stack->le_advertisements_active){
3384501f56b3SMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
3385501f56b3SMatthias Ringwald     }
3386501f56b3SMatthias Ringwald     hci_run();
3387501f56b3SMatthias Ringwald }
3388501f56b3SMatthias Ringwald 
3389b68d7bc3SMatthias Ringwald /**
339045c102fdSMatthias Ringwald  * @brief Set Advertisement Data
339145c102fdSMatthias Ringwald  * @param advertising_data_length
339245c102fdSMatthias Ringwald  * @param advertising_data (max 31 octets)
339345c102fdSMatthias Ringwald  * @note data is not copied, pointer has to stay valid
339445c102fdSMatthias Ringwald  */
339545c102fdSMatthias Ringwald void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
339645c102fdSMatthias Ringwald     hci_stack->le_advertisements_data_len = advertising_data_length;
339745c102fdSMatthias Ringwald     hci_stack->le_advertisements_data = advertising_data;
3398501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3399501f56b3SMatthias Ringwald     gap_advertisments_changed();
340045c102fdSMatthias Ringwald }
3401501f56b3SMatthias Ringwald 
3402501f56b3SMatthias Ringwald /**
3403501f56b3SMatthias Ringwald  * @brief Set Scan Response Data
3404501f56b3SMatthias Ringwald  * @param advertising_data_length
3405501f56b3SMatthias Ringwald  * @param advertising_data (max 31 octets)
3406501f56b3SMatthias Ringwald  * @note data is not copied, pointer has to stay valid
3407501f56b3SMatthias Ringwald  */
3408501f56b3SMatthias Ringwald void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
3409501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data_len = scan_response_data_length;
3410501f56b3SMatthias Ringwald     hci_stack->le_scan_response_data = scan_response_data;
3411501f56b3SMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3412501f56b3SMatthias Ringwald     gap_advertisments_changed();
341345c102fdSMatthias Ringwald }
341445c102fdSMatthias Ringwald 
341545c102fdSMatthias Ringwald /**
341645c102fdSMatthias Ringwald  * @brief Set Advertisement Parameters
341745c102fdSMatthias Ringwald  * @param adv_int_min
341845c102fdSMatthias Ringwald  * @param adv_int_max
341945c102fdSMatthias Ringwald  * @param adv_type
342045c102fdSMatthias Ringwald  * @param own_address_type
342145c102fdSMatthias Ringwald  * @param direct_address_type
342245c102fdSMatthias Ringwald  * @param direct_address
342345c102fdSMatthias Ringwald  * @param channel_map
342445c102fdSMatthias Ringwald  * @param filter_policy
342545c102fdSMatthias Ringwald  *
342645c102fdSMatthias Ringwald  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
342745c102fdSMatthias Ringwald  */
342845c102fdSMatthias Ringwald  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
342945c102fdSMatthias Ringwald     uint8_t own_address_type, uint8_t direct_address_typ, bd_addr_t direct_address,
343045c102fdSMatthias Ringwald     uint8_t channel_map, uint8_t filter_policy) {
343145c102fdSMatthias Ringwald 
343245c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_min = adv_int_min;
343345c102fdSMatthias Ringwald     hci_stack->le_advertisements_interval_max = adv_int_max;
343445c102fdSMatthias Ringwald     hci_stack->le_advertisements_type = adv_type;
343545c102fdSMatthias Ringwald     hci_stack->le_advertisements_own_address_type = own_address_type;
343645c102fdSMatthias Ringwald     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
343745c102fdSMatthias Ringwald     hci_stack->le_advertisements_channel_map = channel_map;
343845c102fdSMatthias Ringwald     hci_stack->le_advertisements_filter_policy = filter_policy;
343945c102fdSMatthias Ringwald     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
344045c102fdSMatthias Ringwald 
344145c102fdSMatthias Ringwald     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3442501f56b3SMatthias Ringwald     gap_advertisments_changed();
344345c102fdSMatthias Ringwald  }
344445c102fdSMatthias Ringwald 
344545c102fdSMatthias Ringwald /**
344645c102fdSMatthias Ringwald  * @brief Enable/Disable Advertisements
344745c102fdSMatthias Ringwald  * @param enabled
344845c102fdSMatthias Ringwald  */
344945c102fdSMatthias Ringwald void gap_advertisements_enable(int enabled){
345045c102fdSMatthias Ringwald     hci_stack->le_advertisements_enabled = enabled;
345145c102fdSMatthias Ringwald     if (enabled && !hci_stack->le_advertisements_active){
345245c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
345345c102fdSMatthias Ringwald     }
345445c102fdSMatthias Ringwald     if (!enabled && hci_stack->le_advertisements_active){
345545c102fdSMatthias Ringwald         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
345645c102fdSMatthias Ringwald     }
3457cfc59f1bSMatthias Ringwald     hci_run();
345845c102fdSMatthias Ringwald }
345945c102fdSMatthias Ringwald 
346045c102fdSMatthias Ringwald 
3461616edd56SMatthias Ringwald uint8_t gap_disconnect(hci_con_handle_t handle){
34625917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
34635917a5c5S[email protected]     if (!conn){
34647851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
3465616edd56SMatthias Ringwald         return 0;
34665917a5c5S[email protected]     }
34675917a5c5S[email protected]     conn->state = SEND_DISCONNECT;
34685917a5c5S[email protected]     hci_run();
3469616edd56SMatthias Ringwald     return 0;
34704f3229d8S[email protected] }
347104a6ef8cSmatthias.ringwald 
3472a1bf5ae7SMatthias Ringwald /**
3473a1bf5ae7SMatthias Ringwald  * @brief Get connection type
3474a1bf5ae7SMatthias Ringwald  * @param con_handle
3475a1bf5ae7SMatthias Ringwald  * @result connection_type
3476a1bf5ae7SMatthias Ringwald  */
3477a1bf5ae7SMatthias Ringwald gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
3478a1bf5ae7SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
3479a1bf5ae7SMatthias Ringwald     if (!conn) return GAP_CONNECTION_INVALID;
3480a1bf5ae7SMatthias Ringwald     switch (conn->address_type){
3481a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_PUBLIC:
3482a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_LE_RANDOM:
3483a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_LE;
3484a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_SCO:
3485a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_SCO;
3486a1bf5ae7SMatthias Ringwald         case BD_ADDR_TYPE_CLASSIC:
3487a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_ACL;
3488a1bf5ae7SMatthias Ringwald         default:
3489a1bf5ae7SMatthias Ringwald             return GAP_CONNECTION_INVALID;
3490a1bf5ae7SMatthias Ringwald     }
3491a1bf5ae7SMatthias Ringwald }
3492a1bf5ae7SMatthias Ringwald 
3493a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
34944f551432SMatthias Ringwald 
3495d23838ecSMatthias Ringwald /**
3496ac9c45e0SMatthias Ringwald  * @brief Auto Connection Establishment - Start Connecting to device
3497ac9c45e0SMatthias Ringwald  * @param address_typ
3498ac9c45e0SMatthias Ringwald  * @param address
3499ac9c45e0SMatthias Ringwald  * @returns 0 if ok
3500ac9c45e0SMatthias Ringwald  */
35014f551432SMatthias Ringwald int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
3502e83201bcSMatthias Ringwald     // check capacity
3503665d90f2SMatthias Ringwald     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
350491915b0bSMatthias Ringwald     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3505e83201bcSMatthias Ringwald     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
3506e83201bcSMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
3507e83201bcSMatthias Ringwald     entry->address_type = address_type;
3508e83201bcSMatthias Ringwald     memcpy(entry->address, address, 6);
3509e83201bcSMatthias Ringwald     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
3510665d90f2SMatthias Ringwald     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
3511e83201bcSMatthias Ringwald     hci_run();
3512e83201bcSMatthias Ringwald     return 0;
3513ac9c45e0SMatthias Ringwald }
3514ac9c45e0SMatthias Ringwald 
351542ff5ba1SMatthias Ringwald static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
3516665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3517665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3518665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3519665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3520e83201bcSMatthias Ringwald         if (entry->address_type != address_type) continue;
3521e83201bcSMatthias Ringwald         if (memcmp(entry->address, address, 6) != 0) continue;
3522e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3523e83201bcSMatthias Ringwald             // remove from controller if already present
3524e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3525e83201bcSMatthias Ringwald             continue;
3526e83201bcSMatthias Ringwald         }
3527e83201bcSMatthias Ringwald         // direclty remove entry from whitelist
3528665d90f2SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
3529e83201bcSMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
3530e83201bcSMatthias Ringwald     }
353142ff5ba1SMatthias Ringwald }
353242ff5ba1SMatthias Ringwald 
353342ff5ba1SMatthias Ringwald /**
353442ff5ba1SMatthias Ringwald  * @brief Auto Connection Establishment - Stop Connecting to device
353542ff5ba1SMatthias Ringwald  * @param address_typ
353642ff5ba1SMatthias Ringwald  * @param address
353742ff5ba1SMatthias Ringwald  * @returns 0 if ok
353842ff5ba1SMatthias Ringwald  */
353942ff5ba1SMatthias Ringwald int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
354042ff5ba1SMatthias Ringwald     hci_remove_from_whitelist(address_type, address);
3541e83201bcSMatthias Ringwald     hci_run();
3542e83201bcSMatthias Ringwald     return 0;
3543ac9c45e0SMatthias Ringwald }
3544ac9c45e0SMatthias Ringwald 
3545ac9c45e0SMatthias Ringwald /**
3546ac9c45e0SMatthias Ringwald  * @brief Auto Connection Establishment - Stop everything
3547ac9c45e0SMatthias Ringwald  * @note  Convenience function to stop all active auto connection attempts
3548ac9c45e0SMatthias Ringwald  */
3549ac9c45e0SMatthias Ringwald void gap_auto_connection_stop_all(void){
3550665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3551665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3552665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3553665d90f2SMatthias Ringwald         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3554e83201bcSMatthias Ringwald         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3555e83201bcSMatthias Ringwald             // remove from controller if already present
3556e83201bcSMatthias Ringwald             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3557e83201bcSMatthias Ringwald             continue;
3558e83201bcSMatthias Ringwald         }
355991915b0bSMatthias Ringwald         // directly remove entry from whitelist
3560665d90f2SMatthias Ringwald         btstack_linked_list_iterator_remove(&it);
3561e83201bcSMatthias Ringwald         btstack_memory_whitelist_entry_free(entry);
3562e83201bcSMatthias Ringwald     }
3563e83201bcSMatthias Ringwald     hci_run();
3564ac9c45e0SMatthias Ringwald }
3565ac9c45e0SMatthias Ringwald 
35664f551432SMatthias Ringwald #endif
35674f551432SMatthias Ringwald 
3568ac9c45e0SMatthias Ringwald /**
3569d950d659SMatthias Ringwald  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
3570d950d659SMatthias Ringwald  */
3571d950d659SMatthias Ringwald void hci_set_sco_voice_setting(uint16_t voice_setting){
3572d950d659SMatthias Ringwald     hci_stack->sco_voice_setting = voice_setting;
3573d950d659SMatthias Ringwald }
3574d950d659SMatthias Ringwald 
3575d950d659SMatthias Ringwald /**
3576d950d659SMatthias Ringwald  * @brief Get SCO Voice Setting
3577d950d659SMatthias Ringwald  * @return current voice setting
3578d950d659SMatthias Ringwald  */
35790cb5b971SMatthias Ringwald uint16_t hci_get_sco_voice_setting(void){
3580d950d659SMatthias Ringwald     return hci_stack->sco_voice_setting;
3581d950d659SMatthias Ringwald }
3582d950d659SMatthias Ringwald 
3583b3aad8daSMatthias Ringwald /** @brief Get SCO packet length for current SCO Voice setting
3584b3aad8daSMatthias Ringwald  *  @note  Using SCO packets of the exact length is required for USB transfer
3585b3aad8daSMatthias Ringwald  *  @return Length of SCO packets in bytes (not audio frames)
3586b3aad8daSMatthias Ringwald  */
3587b3aad8daSMatthias Ringwald int hci_get_sco_packet_length(void){
3588b3aad8daSMatthias Ringwald     // see Core Spec for H2 USB Transfer.
3589b3aad8daSMatthias Ringwald     if (hci_stack->sco_voice_setting & 0x0020) return 51;
3590b3aad8daSMatthias Ringwald     return 27;
3591b3aad8daSMatthias Ringwald }
3592b3aad8daSMatthias Ringwald 
3593d950d659SMatthias Ringwald /**
3594d23838ecSMatthias Ringwald  * @brief Set callback for Bluetooth Hardware Error
3595d23838ecSMatthias Ringwald  */
3596d23838ecSMatthias Ringwald void hci_set_hardware_error_callback(void (*fn)(void)){
3597d23838ecSMatthias Ringwald     hci_stack->hardware_error_callback = fn;
3598d23838ecSMatthias Ringwald }
3599d23838ecSMatthias Ringwald 
3600a6ddbcb9SMatthias Ringwald /**
3601a6ddbcb9SMatthias Ringwald  * @brief Set callback for local information from Bluetooth controller right after HCI Reset
3602a6ddbcb9SMatthias Ringwald  * @note Can be used to select chipset driver dynamically during startup
3603a6ddbcb9SMatthias Ringwald  */
3604a6ddbcb9SMatthias Ringwald void hci_set_local_version_information_callback(void (*fn)(uint8_t * local_version_information)){
3605a6ddbcb9SMatthias Ringwald     hci_stack->local_version_information_callback = fn;
3606a6ddbcb9SMatthias Ringwald }
3607a6ddbcb9SMatthias Ringwald 
360871de195eSMatthias Ringwald void hci_disconnect_all(void){
3609665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3610665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
3611665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3612665d90f2SMatthias Ringwald         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
361304a6ef8cSmatthias.ringwald         if (con->state == SENT_DISCONNECT) continue;
361404a6ef8cSmatthias.ringwald         con->state = SEND_DISCONNECT;
361504a6ef8cSmatthias.ringwald     }
3616d31fba26S[email protected]     hci_run();
361704a6ef8cSmatthias.ringwald }
3618