xref: /btstack/src/hci.c (revision 33e6948b1254ceb02d68d53c2d586e29fb8c8b03)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "hci.c"
39 
40 /*
41  *  hci.c
42  *
43  *  Created by Matthias Ringwald on 4/29/09.
44  *
45  */
46 
47 #include "btstack_config.h"
48 
49 
50 #ifdef ENABLE_CLASSIC
51 #ifdef HAVE_EMBEDDED_TICK
52 #include "btstack_run_loop_embedded.h"
53 #endif
54 #endif
55 
56 #ifdef HAVE_PLATFORM_IPHONE_OS
57 #include "../port/ios/src/btstack_control_iphone.h"
58 #endif
59 
60 #ifdef ENABLE_BLE
61 #include "gap.h"
62 #endif
63 
64 #include <stdarg.h>
65 #include <string.h>
66 #include <stdio.h>
67 #include <inttypes.h>
68 
69 #include "btstack_debug.h"
70 #include "btstack_event.h"
71 #include "btstack_linked_list.h"
72 #include "btstack_memory.h"
73 #include "bluetooth_company_id.h"
74 #include "bluetooth_data_types.h"
75 #include "gap.h"
76 #include "hci.h"
77 #include "hci_cmd.h"
78 #include "hci_dump.h"
79 #include "ad_parser.h"
80 
81 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
82 #ifndef HCI_HOST_ACL_PACKET_NUM
83 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM"
84 #endif
85 #ifndef HCI_HOST_ACL_PACKET_LEN
86 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN"
87 #endif
88 #ifndef HCI_HOST_SCO_PACKET_NUM
89 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM"
90 #endif
91 #ifndef HCI_HOST_SCO_PACKET_LEN
92 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN"
93 #endif
94 #endif
95 
96 #define HCI_CONNECTION_TIMEOUT_MS 10000
97 #define HCI_RESET_RESEND_TIMEOUT_MS 200
98 
99 // Names are arbitrarily shortened to 32 bytes if not requested otherwise
100 #ifndef GAP_INQUIRY_MAX_NAME_LEN
101 #define GAP_INQUIRY_MAX_NAME_LEN 32
102 #endif
103 
104 // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
105 #define GAP_INQUIRY_DURATION_MIN 0x01
106 #define GAP_INQUIRY_DURATION_MAX 0x30
107 #define GAP_INQUIRY_STATE_ACTIVE 0x80
108 #define GAP_INQUIRY_STATE_IDLE 0
109 #define GAP_INQUIRY_STATE_W2_CANCEL 0x81
110 #define GAP_INQUIRY_STATE_W4_CANCELLED 0x82
111 
112 // GAP Remote Name Request
113 #define GAP_REMOTE_NAME_STATE_IDLE 0
114 #define GAP_REMOTE_NAME_STATE_W2_SEND 1
115 #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
116 
117 // GAP Pairing
118 #define GAP_PAIRING_STATE_IDLE                       0
119 #define GAP_PAIRING_STATE_SEND_PIN                   1
120 #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
121 #define GAP_PAIRING_STATE_SEND_PASSKEY               3
122 #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
123 #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
124 #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
125 
126 
127 // prototypes
128 #ifdef ENABLE_CLASSIC
129 static void hci_update_scan_enable(void);
130 static void hci_emit_discoverable_enabled(uint8_t enabled);
131 static int  hci_local_ssp_activated(void);
132 static int  hci_remote_ssp_supported(hci_con_handle_t con_handle);
133 static void hci_notify_if_sco_can_send_now(void);
134 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
135 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
136 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
137 static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
138 static void hci_connection_timestamp(hci_connection_t *connection);
139 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
140 static void gap_inquiry_explode(uint8_t * packet);
141 #endif
142 
143 static int  hci_power_control_on(void);
144 static void hci_power_control_off(void);
145 static void hci_state_reset(void);
146 static void hci_emit_transport_packet_sent(void);
147 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
148 static void hci_emit_nr_connections_changed(void);
149 static void hci_emit_hci_open_failed(void);
150 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
151 static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
152 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
153 static void hci_run(void);
154 static int  hci_is_le_connection(hci_connection_t * connection);
155 static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
156 
157 #ifdef ENABLE_BLE
158 #ifdef ENABLE_LE_CENTRAL
159 // called from test/ble_client/advertising_data_parser.c
160 void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
161 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address);
162 static hci_connection_t * gap_get_outgoing_connection(void);
163 #endif
164 #endif
165 
166 // the STACK is here
167 #ifndef HAVE_MALLOC
168 static hci_stack_t   hci_stack_static;
169 #endif
170 static hci_stack_t * hci_stack = NULL;
171 
172 #ifdef ENABLE_CLASSIC
173 // default name
174 static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
175 
176 // test helper
177 static uint8_t disable_l2cap_timeouts = 0;
178 #endif
179 
180 /**
181  * create connection for given address
182  *
183  * @return connection OR NULL, if no memory left
184  */
185 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
186     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
187     hci_connection_t * conn = btstack_memory_hci_connection_get();
188     if (!conn) return NULL;
189     bd_addr_copy(conn->address, addr);
190     conn->address_type = addr_type;
191     conn->con_handle = 0xffff;
192     conn->authentication_flags = AUTH_FLAGS_NONE;
193     conn->bonding_flags = 0;
194     conn->requested_security_level = LEVEL_0;
195 #ifdef ENABLE_CLASSIC
196     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
197     btstack_run_loop_set_timer_context(&conn->timeout, conn);
198     hci_connection_timestamp(conn);
199 #endif
200     conn->acl_recombination_length = 0;
201     conn->acl_recombination_pos = 0;
202     conn->num_acl_packets_sent = 0;
203     conn->num_sco_packets_sent = 0;
204     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
205 #ifdef ENABLE_BLE
206     conn->le_phy_update_all_phys = 0xff;
207 #endif
208     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
209     return conn;
210 }
211 
212 
213 /**
214  * get le connection parameter range
215 *
216  * @return le connection parameter range struct
217  */
218 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
219     *range = hci_stack->le_connection_parameter_range;
220 }
221 
222 /**
223  * set le connection parameter range
224  *
225  */
226 
227 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
228     hci_stack->le_connection_parameter_range = *range;
229 }
230 
231 /**
232  * @brief Test if connection parameters are inside in existing rage
233  * @param conn_interval_min (unit: 1.25ms)
234  * @param conn_interval_max (unit: 1.25ms)
235  * @param conn_latency
236  * @param supervision_timeout (unit: 10ms)
237  * @returns 1 if included
238  */
239 int gap_connection_parameter_range_included(le_connection_parameter_range_t * existing_range, uint16_t le_conn_interval_min, uint16_t le_conn_interval_max, uint16_t le_conn_latency, uint16_t le_supervision_timeout){
240     if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
241     if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
242 
243     if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
244     if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
245 
246     if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
247     if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
248 
249     return 1;
250 }
251 
252 /**
253  * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
254  * @note: default: 1
255  * @param max_peripheral_connections
256  */
257 #ifdef ENABLE_LE_PERIPHERAL
258 void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
259     hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
260 }
261 #endif
262 
263 /**
264  * get hci connections iterator
265  *
266  * @return hci connections iterator
267  */
268 
269 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
270     btstack_linked_list_iterator_init(it, &hci_stack->connections);
271 }
272 
273 /**
274  * get connection for a given handle
275  *
276  * @return connection OR NULL, if not found
277  */
278 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
279     btstack_linked_list_iterator_t it;
280     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
281     while (btstack_linked_list_iterator_has_next(&it)){
282         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
283         if ( item->con_handle == con_handle ) {
284             return item;
285         }
286     }
287     return NULL;
288 }
289 
290 /**
291  * get connection for given address
292  *
293  * @return connection OR NULL, if not found
294  */
295 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t  addr, bd_addr_type_t addr_type){
296     btstack_linked_list_iterator_t it;
297     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
298     while (btstack_linked_list_iterator_has_next(&it)){
299         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
300         if (connection->address_type != addr_type)  continue;
301         if (memcmp(addr, connection->address, 6) != 0) continue;
302         return connection;
303     }
304     return NULL;
305 }
306 
307 
308 #ifdef ENABLE_CLASSIC
309 
310 #ifdef ENABLE_SCO_OVER_HCI
311 static int hci_number_sco_connections(void){
312     int connections = 0;
313     btstack_linked_list_iterator_t it;
314     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
315     while (btstack_linked_list_iterator_has_next(&it)){
316         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
317         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
318         connections++;
319     }
320     return connections;
321 }
322 #endif
323 
324 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
325     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
326 #ifdef HAVE_EMBEDDED_TICK
327     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
328         // connections might be timed out
329         hci_emit_l2cap_check_timeout(connection);
330     }
331 #else
332     if (btstack_run_loop_get_time_ms() > connection->timestamp + HCI_CONNECTION_TIMEOUT_MS){
333         // connections might be timed out
334         hci_emit_l2cap_check_timeout(connection);
335     }
336 #endif
337 }
338 
339 static void hci_connection_timestamp(hci_connection_t *connection){
340 #ifdef HAVE_EMBEDDED_TICK
341     connection->timestamp = btstack_run_loop_embedded_get_ticks();
342 #else
343     connection->timestamp = btstack_run_loop_get_time_ms();
344 #endif
345 }
346 
347 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
348     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
349 }
350 
351 
352 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
353     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
354 }
355 
356 /**
357  * add authentication flags and reset timer
358  * @note: assumes classic connection
359  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
360  */
361 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
362     bd_addr_t addr;
363     reverse_bd_addr(bd_addr, addr);
364     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
365     if (conn) {
366         connectionSetAuthenticationFlags(conn, flags);
367         hci_connection_timestamp(conn);
368     }
369 }
370 
371 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
372     hci_connection_t * conn = hci_connection_for_handle(handle);
373     if (!conn) return 0;
374     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
375     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
376     return 0;
377 }
378 
379 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
380     if (!hci_stack->link_key_db) return;
381     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
382     hci_stack->link_key_db->delete_link_key(addr);
383 }
384 
385 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
386     if (!hci_stack->link_key_db) return;
387     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
388     hci_stack->link_key_db->put_link_key(addr, link_key, type);
389 }
390 
391 void gap_delete_all_link_keys(void){
392     bd_addr_t  addr;
393     link_key_t link_key;
394     link_key_type_t type;
395     btstack_link_key_iterator_t it;
396     int ok = gap_link_key_iterator_init(&it);
397     if (!ok) {
398         log_error("could not initialize iterator");
399         return;
400     }
401     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
402         gap_drop_link_key_for_bd_addr(addr);
403     }
404     gap_link_key_iterator_done(&it);
405 }
406 
407 int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
408     if (!hci_stack->link_key_db) return 0;
409     if (!hci_stack->link_key_db->iterator_init) return 0;
410     return hci_stack->link_key_db->iterator_init(it);
411 }
412 int gap_link_key_iterator_get_next(btstack_link_key_iterator_t * it, bd_addr_t bd_addr, link_key_t link_key, link_key_type_t * type){
413     if (!hci_stack->link_key_db) return 0;
414     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
415 }
416 void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
417     if (!hci_stack->link_key_db) return;
418     hci_stack->link_key_db->iterator_done(it);
419 }
420 #endif
421 
422 static int hci_is_le_connection(hci_connection_t * connection){
423     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
424     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
425 }
426 
427 /**
428  * count connections
429  */
430 static int nr_hci_connections(void){
431     int count = 0;
432     btstack_linked_item_t *it;
433     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
434     return count;
435 }
436 
437 static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
438 
439     unsigned int num_packets_sent_classic = 0;
440     unsigned int num_packets_sent_le = 0;
441 
442     btstack_linked_item_t *it;
443     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
444         hci_connection_t * connection = (hci_connection_t *) it;
445         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
446             num_packets_sent_classic += connection->num_acl_packets_sent;
447         } else {
448             num_packets_sent_le += connection->num_acl_packets_sent;
449         }
450     }
451     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
452     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
453     int free_slots_le = 0;
454 
455     if (free_slots_classic < 0){
456         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);
457         return 0;
458     }
459 
460     if (hci_stack->le_acl_packets_total_num){
461         // if we have LE slots, they are used
462         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
463         if (free_slots_le < 0){
464             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);
465             return 0;
466         }
467     } else {
468         // otherwise, classic slots are used for LE, too
469         free_slots_classic -= num_packets_sent_le;
470         if (free_slots_classic < 0){
471             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);
472             return 0;
473         }
474     }
475 
476     switch (address_type){
477         case BD_ADDR_TYPE_UNKNOWN:
478             log_error("hci_number_free_acl_slots: unknown address type");
479             return 0;
480 
481         case BD_ADDR_TYPE_CLASSIC:
482             return free_slots_classic;
483 
484         default:
485            if (hci_stack->le_acl_packets_total_num){
486                return free_slots_le;
487            }
488            return free_slots_classic;
489     }
490 }
491 
492 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
493     // get connection type
494     hci_connection_t * connection = hci_connection_for_handle(con_handle);
495     if (!connection){
496         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
497         return 0;
498     }
499     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
500 }
501 
502 #ifdef ENABLE_CLASSIC
503 static int hci_number_free_sco_slots(void){
504     unsigned int num_sco_packets_sent  = 0;
505     btstack_linked_item_t *it;
506     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
507         hci_connection_t * connection = (hci_connection_t *) it;
508         num_sco_packets_sent += connection->num_sco_packets_sent;
509     }
510     if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
511         log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
512         return 0;
513     }
514     // log_info("hci_number_free_sco_slots u", handle, num_sco_packets_sent);
515     return hci_stack->sco_packets_total_num - num_sco_packets_sent;
516 }
517 #endif
518 
519 // only used to send HCI Host Number Completed Packets
520 static int hci_can_send_comand_packet_transport(void){
521     if (hci_stack->hci_packet_buffer_reserved) return 0;
522 
523     // check for async hci transport implementations
524     if (hci_stack->hci_transport->can_send_packet_now){
525         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
526             return 0;
527         }
528     }
529     return 1;
530 }
531 
532 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
533 int hci_can_send_command_packet_now(void){
534     if (hci_can_send_comand_packet_transport() == 0) return 0;
535     return hci_stack->num_cmd_packets > 0;
536 }
537 
538 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
539     // check for async hci transport implementations
540     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
541     return hci_stack->hci_transport->can_send_packet_now(packet_type);
542 }
543 
544 static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
545     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
546     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
547 }
548 
549 int hci_can_send_acl_le_packet_now(void){
550     if (hci_stack->hci_packet_buffer_reserved) return 0;
551     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
552 }
553 
554 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
555     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
556     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
557 }
558 
559 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
560     if (hci_stack->hci_packet_buffer_reserved) return 0;
561     return hci_can_send_prepared_acl_packet_now(con_handle);
562 }
563 
564 #ifdef ENABLE_CLASSIC
565 int hci_can_send_acl_classic_packet_now(void){
566     if (hci_stack->hci_packet_buffer_reserved) return 0;
567     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_CLASSIC);
568 }
569 
570 int hci_can_send_prepared_sco_packet_now(void){
571     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
572     if (!hci_stack->synchronous_flow_control_enabled) return 1;
573     return hci_number_free_sco_slots() > 0;
574 }
575 
576 int hci_can_send_sco_packet_now(void){
577     if (hci_stack->hci_packet_buffer_reserved) return 0;
578     return hci_can_send_prepared_sco_packet_now();
579 }
580 
581 void hci_request_sco_can_send_now_event(void){
582     hci_stack->sco_waiting_for_can_send_now = 1;
583     hci_notify_if_sco_can_send_now();
584 }
585 #endif
586 
587 // used for internal checks in l2cap.c
588 int hci_is_packet_buffer_reserved(void){
589     return hci_stack->hci_packet_buffer_reserved;
590 }
591 
592 // reserves outgoing packet buffer. @returns 1 if successful
593 int hci_reserve_packet_buffer(void){
594     if (hci_stack->hci_packet_buffer_reserved) {
595         log_error("hci_reserve_packet_buffer called but buffer already reserved");
596         return 0;
597     }
598     hci_stack->hci_packet_buffer_reserved = 1;
599     return 1;
600 }
601 
602 void hci_release_packet_buffer(void){
603     hci_stack->hci_packet_buffer_reserved = 0;
604 }
605 
606 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
607 static int hci_transport_synchronous(void){
608     return hci_stack->hci_transport->can_send_packet_now == NULL;
609 }
610 
611 static int hci_send_acl_packet_fragments(hci_connection_t *connection){
612 
613     // 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);
614 
615     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
616     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
617     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
618         max_acl_data_packet_length = hci_stack->le_data_packets_length;
619     }
620 
621     // testing: reduce buffer to minimum
622     // max_acl_data_packet_length = 52;
623 
624     log_debug("hci_send_acl_packet_fragments entered");
625 
626     int err;
627     // multiple packets could be send on a synchronous HCI transport
628     while (1){
629 
630         log_debug("hci_send_acl_packet_fragments loop entered");
631 
632         // get current data
633         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
634         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
635         int more_fragments = 0;
636 
637         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
638         if (current_acl_data_packet_length > max_acl_data_packet_length){
639             more_fragments = 1;
640             current_acl_data_packet_length = max_acl_data_packet_length;
641         }
642 
643         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
644         if (acl_header_pos > 0){
645             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
646             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
647             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
648         }
649 
650         // update header len
651         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
652 
653         // count packet
654         connection->num_acl_packets_sent++;
655         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", more_fragments);
656 
657         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
658         if (more_fragments){
659             // update start of next fragment to send
660             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
661         } else {
662             // done
663             hci_stack->acl_fragmentation_pos = 0;
664             hci_stack->acl_fragmentation_total_size = 0;
665         }
666 
667         // send packet
668         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
669         const int size = current_acl_data_packet_length + 4;
670         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
671         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
672 
673         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", more_fragments);
674 
675         // done yet?
676         if (!more_fragments) break;
677 
678         // can send more?
679         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
680     }
681 
682     log_debug("hci_send_acl_packet_fragments loop over");
683 
684     // release buffer now for synchronous transport
685     if (hci_transport_synchronous()){
686         hci_release_packet_buffer();
687         hci_emit_transport_packet_sent();
688     }
689 
690     return err;
691 }
692 
693 // pre: caller has reserved the packet buffer
694 int hci_send_acl_packet_buffer(int size){
695 
696     // log_info("hci_send_acl_packet_buffer size %u", size);
697 
698     if (!hci_stack->hci_packet_buffer_reserved) {
699         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
700         return 0;
701     }
702 
703     uint8_t * packet = hci_stack->hci_packet_buffer;
704     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
705 
706     // check for free places on Bluetooth module
707     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
708         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
709         hci_release_packet_buffer();
710         hci_emit_transport_packet_sent();
711         return BTSTACK_ACL_BUFFERS_FULL;
712     }
713 
714     hci_connection_t *connection = hci_connection_for_handle( con_handle);
715     if (!connection) {
716         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
717         hci_release_packet_buffer();
718         hci_emit_transport_packet_sent();
719         return 0;
720     }
721 
722 #ifdef ENABLE_CLASSIC
723     hci_connection_timestamp(connection);
724 #endif
725 
726     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
727 
728     // setup data
729     hci_stack->acl_fragmentation_total_size = size;
730     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
731 
732     return hci_send_acl_packet_fragments(connection);
733 }
734 
735 #ifdef ENABLE_CLASSIC
736 // pre: caller has reserved the packet buffer
737 int hci_send_sco_packet_buffer(int size){
738 
739     // log_info("hci_send_acl_packet_buffer size %u", size);
740 
741     if (!hci_stack->hci_packet_buffer_reserved) {
742         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
743         return 0;
744     }
745 
746     uint8_t * packet = hci_stack->hci_packet_buffer;
747 
748     // skip checks in loopback mode
749     if (!hci_stack->loopback_mode){
750         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
751 
752         // check for free places on Bluetooth module
753         if (!hci_can_send_prepared_sco_packet_now()) {
754             log_error("hci_send_sco_packet_buffer called but no free ACL buffers on controller");
755             hci_release_packet_buffer();
756             hci_emit_transport_packet_sent();
757             return BTSTACK_ACL_BUFFERS_FULL;
758         }
759 
760         // track send packet in connection struct
761         hci_connection_t *connection = hci_connection_for_handle( con_handle);
762         if (!connection) {
763             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
764             hci_release_packet_buffer();
765             hci_emit_transport_packet_sent();
766             return 0;
767         }
768         connection->num_sco_packets_sent++;
769     }
770 
771     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
772     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
773 
774     if (hci_transport_synchronous()){
775         hci_release_packet_buffer();
776         hci_emit_transport_packet_sent();
777     }
778 
779     return err;
780 }
781 #endif
782 
783 static void acl_handler(uint8_t *packet, int size){
784 
785     // log_info("acl_handler: size %u", size);
786 
787     // get info
788     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
789     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
790     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
791     uint16_t acl_length         = READ_ACL_LENGTH(packet);
792 
793     // ignore non-registered handle
794     if (!conn){
795         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
796         return;
797     }
798 
799     // assert packet is complete
800     if (acl_length + 4 != size){
801         log_error("hci.c: acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
802         return;
803     }
804 
805 #ifdef ENABLE_CLASSIC
806     // update idle timestamp
807     hci_connection_timestamp(conn);
808 #endif
809 
810 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
811     hci_stack->host_completed_packets = 1;
812     conn->num_packets_completed++;
813 #endif
814 
815     // handle different packet types
816     switch (acl_flags & 0x03) {
817 
818         case 0x01: // continuation fragment
819 
820             // sanity checks
821             if (conn->acl_recombination_pos == 0) {
822                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
823                 return;
824             }
825             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
826                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
827                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
828                 conn->acl_recombination_pos = 0;
829                 return;
830             }
831 
832             // append fragment payload (header already stored)
833             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
834             conn->acl_recombination_pos += acl_length;
835 
836             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
837             //        conn->acl_recombination_pos, conn->acl_recombination_length);
838 
839             // forward complete L2CAP packet if complete.
840             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
841                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
842                 // reset recombination buffer
843                 conn->acl_recombination_length = 0;
844                 conn->acl_recombination_pos = 0;
845             }
846             break;
847 
848         case 0x02: { // first fragment
849 
850             // sanity check
851             if (conn->acl_recombination_pos) {
852                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
853                 conn->acl_recombination_pos = 0;
854             }
855 
856             // peek into L2CAP packet!
857             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
858 
859             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
860 
861             // compare fragment size to L2CAP packet size
862             if (acl_length >= l2cap_length + 4){
863                 // forward fragment as L2CAP packet
864                 hci_emit_acl_packet(packet, acl_length + 4);
865             } else {
866 
867                 if (acl_length > HCI_ACL_BUFFER_SIZE){
868                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
869                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
870                     return;
871                 }
872 
873                 // store first fragment and tweak acl length for complete package
874                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
875                 conn->acl_recombination_pos    = acl_length + 4;
876                 conn->acl_recombination_length = l2cap_length;
877                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
878             }
879             break;
880 
881         }
882         default:
883             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
884             return;
885     }
886 
887     // execute main loop
888     hci_run();
889 }
890 
891 static void hci_shutdown_connection(hci_connection_t *conn){
892     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
893 
894 #ifdef ENABLE_CLASSIC
895 #ifdef ENABLE_SCO_OVER_HCI
896     int addr_type = conn->address_type;
897 #endif
898 #endif
899 
900     btstack_run_loop_remove_timer(&conn->timeout);
901 
902     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
903     btstack_memory_hci_connection_free( conn );
904 
905     // now it's gone
906     hci_emit_nr_connections_changed();
907 
908 #ifdef ENABLE_CLASSIC
909 #ifdef ENABLE_SCO_OVER_HCI
910     // update SCO
911     if (addr_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
912         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
913     }
914 #endif
915 #endif
916 }
917 
918 #ifdef ENABLE_CLASSIC
919 
920 static const uint16_t packet_type_sizes[] = {
921     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
922     HCI_ACL_DH1_SIZE, 0, 0, 0,
923     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
924     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
925 };
926 static const uint8_t  packet_type_feature_requirement_bit[] = {
927      0, // 3 slot packets
928      1, // 5 slot packets
929     25, // EDR 2 mpbs
930     26, // EDR 3 mbps
931     39, // 3 slot EDR packts
932     40, // 5 slot EDR packet
933 };
934 static const uint16_t packet_type_feature_packet_mask[] = {
935     0x0f00, // 3 slot packets
936     0xf000, // 5 slot packets
937     0x1102, // EDR 2 mpbs
938     0x2204, // EDR 3 mbps
939     0x0300, // 3 slot EDR packts
940     0x3000, // 5 slot EDR packet
941 };
942 
943 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
944     // enable packet types based on size
945     uint16_t packet_types = 0;
946     unsigned int i;
947     for (i=0;i<16;i++){
948         if (packet_type_sizes[i] == 0) continue;
949         if (packet_type_sizes[i] <= buffer_size){
950             packet_types |= 1 << i;
951         }
952     }
953     // disable packet types due to missing local supported features
954     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
955         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
956         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
957         if (feature_set) continue;
958         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
959         packet_types &= ~packet_type_feature_packet_mask[i];
960     }
961     // flip bits for "may not be used"
962     packet_types ^= 0x3306;
963     return packet_types;
964 }
965 
966 uint16_t hci_usable_acl_packet_types(void){
967     return hci_stack->packet_types;
968 }
969 #endif
970 
971 uint8_t* hci_get_outgoing_packet_buffer(void){
972     // hci packet buffer is >= acl data packet length
973     return hci_stack->hci_packet_buffer;
974 }
975 
976 uint16_t hci_max_acl_data_packet_length(void){
977     return hci_stack->acl_data_packet_length;
978 }
979 
980 #ifdef ENABLE_CLASSIC
981 int hci_extended_sco_link_supported(void){
982     // No. 31, byte 3, bit 7
983     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
984 }
985 #endif
986 
987 int hci_non_flushable_packet_boundary_flag_supported(void){
988     // No. 54, byte 6, bit 6
989     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
990 }
991 
992 static int gap_ssp_supported(void){
993     // No. 51, byte 6, bit 3
994     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
995 }
996 
997 static int hci_classic_supported(void){
998 #ifdef ENABLE_CLASSIC
999     // No. 37, byte 4, bit 5, = No BR/EDR Support
1000     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
1001 #else
1002     return 0;
1003 #endif
1004 }
1005 
1006 static int hci_le_supported(void){
1007 #ifdef ENABLE_BLE
1008     // No. 37, byte 4, bit 6 = LE Supported (Controller)
1009     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
1010 #else
1011     return 0;
1012 #endif
1013 }
1014 
1015 #ifdef ENABLE_BLE
1016 
1017 /**
1018  * @brief Get addr type and address used for LE in Advertisements, Scan Responses,
1019  */
1020 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
1021     *addr_type = hci_stack->le_own_addr_type;
1022     if (hci_stack->le_own_addr_type){
1023         memcpy(addr, hci_stack->le_random_address, 6);
1024     } else {
1025         memcpy(addr, hci_stack->local_bd_addr, 6);
1026     }
1027 }
1028 
1029 #ifdef ENABLE_LE_CENTRAL
1030 void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
1031 
1032     int offset = 3;
1033     int num_reports = packet[offset];
1034     offset += 1;
1035 
1036     int i;
1037     // log_info("HCI: handle adv report with num reports: %d", num_reports);
1038     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1039     for (i=0; i<num_reports && offset < size;i++){
1040         // sanity checks on data_length:
1041         uint8_t data_length = packet[offset + 8];
1042         if (data_length > LE_ADVERTISING_DATA_SIZE) return;
1043         if (offset + 9 + data_length + 1 > size)    return;
1044         // setup event
1045         uint8_t event_size = 10 + data_length;
1046         int pos = 0;
1047         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1048         event[pos++] = event_size;
1049         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
1050         offset += 8;
1051         pos += 8;
1052         event[pos++] = packet[offset + 1 + data_length]; // rssi
1053         event[pos++] = data_length;
1054         offset++;
1055         memcpy(&event[pos], &packet[offset], data_length);
1056         pos +=    data_length;
1057         offset += data_length + 1; // rssi
1058         hci_emit_event(event, pos, 1);
1059     }
1060 }
1061 #endif
1062 #endif
1063 
1064 #ifdef ENABLE_BLE
1065 #ifdef ENABLE_LE_PERIPHERAL
1066 static void hci_reenable_advertisements_if_needed(void){
1067     if (!hci_stack->le_advertisements_active && hci_stack->le_advertisements_enabled){
1068         // get number of active le slave connections
1069         int num_slave_connections = 0;
1070         btstack_linked_list_iterator_t it;
1071         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
1072         while (btstack_linked_list_iterator_has_next(&it)){
1073             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
1074             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
1075             if (con->state != OPEN) continue;
1076             if (con->role  != HCI_ROLE_SLAVE) continue;
1077             if (!hci_is_le_connection(con)) continue;
1078             num_slave_connections++;
1079         }
1080         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
1081         if (num_slave_connections < hci_stack->le_max_number_peripheral_connections){
1082             hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
1083         }
1084     }
1085 }
1086 #endif
1087 #endif
1088 
1089 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1090 
1091 static uint32_t hci_transport_uart_get_main_baud_rate(void){
1092     if (!hci_stack->config) return 0;
1093     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1094     // Limit baud rate for Broadcom chipsets to 3 mbps
1095     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION && baud_rate > 3000000){
1096         baud_rate = 3000000;
1097     }
1098     return baud_rate;
1099 }
1100 
1101 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
1102     UNUSED(ds);
1103 
1104     switch (hci_stack->substate){
1105         case HCI_INIT_W4_SEND_RESET:
1106             log_info("Resend HCI Reset");
1107             hci_stack->substate = HCI_INIT_SEND_RESET;
1108             hci_stack->num_cmd_packets = 1;
1109             hci_run();
1110             break;
1111         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
1112             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
1113             if (hci_stack->hci_transport->reset_link){
1114                 hci_stack->hci_transport->reset_link();
1115             }
1116             // no break - explicit fallthrough to HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT
1117         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1118             log_info("Resend HCI Reset - CSR Warm Boot");
1119             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1120             hci_stack->num_cmd_packets = 1;
1121             hci_run();
1122             break;
1123         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1124             if (hci_stack->hci_transport->set_baudrate){
1125                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1126                 log_info("Local baud rate change to %"PRIu32"(timeout handler)", baud_rate);
1127                 hci_stack->hci_transport->set_baudrate(baud_rate);
1128             }
1129             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
1130             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1131                 if (hci_stack->hci_transport->reset_link){
1132                     log_info("Link Reset");
1133                     hci_stack->hci_transport->reset_link();
1134                 }
1135                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1136                 hci_run();
1137             }
1138             break;
1139         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1140             // otherwise continue
1141             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1142             hci_send_cmd(&hci_read_local_supported_commands);
1143             break;
1144         default:
1145             break;
1146     }
1147 }
1148 #endif
1149 
1150 static void hci_initializing_next_state(void){
1151     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
1152 }
1153 
1154 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_PERIPHERAL)
1155 static void hci_replace_bd_addr_placeholder(uint8_t * data, uint16_t size){
1156     const int bd_addr_string_len = 17;
1157     int i = 0;
1158     while (i < size - bd_addr_string_len){
1159         if (memcmp(&data[i], "00:00:00:00:00:00", bd_addr_string_len)) {
1160             i++;
1161             continue;
1162         }
1163         // set real address
1164         memcpy(&data[i], bd_addr_to_str(hci_stack->local_bd_addr), bd_addr_string_len);
1165         i += bd_addr_string_len;
1166     }
1167 }
1168 #endif
1169 
1170 // assumption: hci_can_send_command_packet_now() == true
1171 static void hci_initializing_run(void){
1172     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
1173     switch (hci_stack->substate){
1174         case HCI_INIT_SEND_RESET:
1175             hci_state_reset();
1176 
1177 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1178             // prepare reset if command complete not received in 100ms
1179             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1180             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1181             btstack_run_loop_add_timer(&hci_stack->timeout);
1182 #endif
1183             // send command
1184             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1185             hci_send_cmd(&hci_reset);
1186             break;
1187         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
1188             hci_send_cmd(&hci_read_local_version_information);
1189             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
1190             break;
1191         case HCI_INIT_SEND_READ_LOCAL_NAME:
1192             hci_send_cmd(&hci_read_local_name);
1193             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1194             break;
1195 
1196 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1197         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1198             hci_state_reset();
1199             // prepare reset if command complete not received in 100ms
1200             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1201             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1202             btstack_run_loop_add_timer(&hci_stack->timeout);
1203             // send command
1204             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1205             hci_send_cmd(&hci_reset);
1206             break;
1207         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
1208             hci_state_reset();
1209             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
1210             hci_send_cmd(&hci_reset);
1211             break;
1212         case HCI_INIT_SEND_BAUD_CHANGE: {
1213             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1214             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1215             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1216             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1217             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1218             // STLC25000D: baudrate change happens within 0.5 s after command was send,
1219             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
1220             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1221                 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1222                 btstack_run_loop_add_timer(&hci_stack->timeout);
1223             }
1224             break;
1225         }
1226         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1227             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1228             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1229             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1230             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1231             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1232             break;
1233         }
1234         case HCI_INIT_CUSTOM_INIT:
1235             // Custom initialization
1236             if (hci_stack->chipset && hci_stack->chipset->next_command){
1237                 int valid_cmd = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
1238                 if (valid_cmd){
1239                     int size = 3 + hci_stack->hci_packet_buffer[2];
1240                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1241                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
1242                     switch (valid_cmd) {
1243                         case BTSTACK_CHIPSET_VALID_COMMAND:
1244                             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1245                             break;
1246                         case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
1247                             // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1248                             log_info("CSR Warm Boot");
1249                             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1250                             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1251                             btstack_run_loop_add_timer(&hci_stack->timeout);
1252                             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO
1253                                 && hci_stack->config
1254                                 && hci_stack->chipset
1255                                 // && hci_stack->chipset->set_baudrate_command -- there's no such command
1256                                 && hci_stack->hci_transport->set_baudrate
1257                                 && hci_transport_uart_get_main_baud_rate()){
1258                                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1259                             } else {
1260                                hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1261                             }
1262                             break;
1263                         default:
1264                             // should not get here
1265                             break;
1266                     }
1267                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1268                     break;
1269                 }
1270                 log_info("Init script done");
1271 
1272                 // Init script download on Broadcom chipsets causes:
1273                 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION
1274                 ||  hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA){
1275 
1276                     // - baud rate to reset, restore UART baud rate if needed
1277                     int need_baud_change = hci_stack->config
1278                         && hci_stack->chipset
1279                         && hci_stack->chipset->set_baudrate_command
1280                         && hci_stack->hci_transport->set_baudrate
1281                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1282                     if (need_baud_change) {
1283                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1284                         log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate);
1285                         hci_stack->hci_transport->set_baudrate(baud_rate);
1286                     }
1287 
1288                     // - RTS will raise during update, but manual RTS/CTS in WICED port on RedBear Duo cannot handle this
1289                     //   -> Work around: wait a few milliseconds here.
1290                     log_info("BCM delay after init script");
1291                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1292                     btstack_run_loop_set_timer(&hci_stack->timeout, 10);
1293                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1294                     btstack_run_loop_add_timer(&hci_stack->timeout);
1295                     break;
1296                 }
1297             }
1298             // otherwise continue
1299             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1300             hci_send_cmd(&hci_read_local_supported_commands);
1301             break;
1302         case HCI_INIT_SET_BD_ADDR:
1303             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1304             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1305             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1306             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1307             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1308             break;
1309 #endif
1310 
1311         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
1312             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
1313             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1314             hci_send_cmd(&hci_read_local_supported_commands);
1315             break;
1316         case HCI_INIT_READ_BD_ADDR:
1317             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
1318             hci_send_cmd(&hci_read_bd_addr);
1319             break;
1320         case HCI_INIT_READ_BUFFER_SIZE:
1321             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
1322             hci_send_cmd(&hci_read_buffer_size);
1323             break;
1324         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
1325             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
1326             hci_send_cmd(&hci_read_local_supported_features);
1327             break;
1328 
1329 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
1330         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
1331             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
1332             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
1333             break;
1334         case HCI_INIT_HOST_BUFFER_SIZE:
1335             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
1336             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
1337                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
1338             break;
1339 #endif
1340 
1341         case HCI_INIT_SET_EVENT_MASK:
1342             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
1343             if (hci_le_supported()){
1344                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1345             } else {
1346                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1347                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1348             }
1349             break;
1350 
1351 #ifdef ENABLE_CLASSIC
1352         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1353             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
1354             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1355             break;
1356         case HCI_INIT_WRITE_PAGE_TIMEOUT:
1357             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
1358             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
1359             break;
1360         case HCI_INIT_WRITE_DEFAULT_LINK_POLICY_SETTING:
1361             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_LINK_POLICY_SETTING;
1362             hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1363             break;
1364         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
1365             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
1366             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1367             break;
1368         case HCI_INIT_WRITE_LOCAL_NAME: {
1369             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
1370             hci_reserve_packet_buffer();
1371             uint8_t * packet = hci_stack->hci_packet_buffer;
1372             // construct HCI Command and send
1373             uint16_t opcode = hci_write_local_name.opcode;
1374             hci_stack->last_cmd_opcode = opcode;
1375             packet[0] = opcode & 0xff;
1376             packet[1] = opcode >> 8;
1377             packet[2] = DEVICE_NAME_LEN;
1378             memset(&packet[3], 0, DEVICE_NAME_LEN);
1379             memcpy(&packet[3], hci_stack->local_name, strlen(hci_stack->local_name));
1380             // expand '00:00:00:00:00:00' in name with bd_addr
1381             hci_replace_bd_addr_placeholder(&packet[3], DEVICE_NAME_LEN);
1382             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
1383             break;
1384         }
1385         case HCI_INIT_WRITE_EIR_DATA: {
1386             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
1387             hci_reserve_packet_buffer();
1388             uint8_t * packet = hci_stack->hci_packet_buffer;
1389             // construct HCI Command and send
1390             uint16_t opcode = hci_write_extended_inquiry_response.opcode;
1391             hci_stack->last_cmd_opcode = opcode;
1392             packet[0] = opcode & 0xff;
1393             packet[1] = opcode >> 8;
1394             packet[2] = 1 + 240;
1395             packet[3] = 0;  // FEC not required
1396             if (hci_stack->eir_data){
1397                 memcpy(&packet[4], hci_stack->eir_data, 240);
1398             } else {
1399                 memset(&packet[4], 0, 240);
1400                 int name_len = strlen(hci_stack->local_name);
1401                 packet[4] = name_len + 1;
1402                 packet[5] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
1403                 memcpy(&packet[6], hci_stack->local_name, name_len);
1404             }
1405             // expand '00:00:00:00:00:00' in name with bd_addr
1406             hci_replace_bd_addr_placeholder(&packet[4], 240);
1407             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + 240);
1408             break;
1409         }
1410         case HCI_INIT_WRITE_INQUIRY_MODE:
1411             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
1412             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1413             break;
1414         case HCI_INIT_WRITE_SCAN_ENABLE:
1415             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1416             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
1417             break;
1418         // only sent if ENABLE_SCO_OVER_HCI is defined
1419         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1420             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1421             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1422             break;
1423         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1424             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1425             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1426             break;
1427         // only sent if ENABLE_SCO_OVER_HCI and manufacturer is Broadcom
1428         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1429             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1430             log_info("BCM: Route SCO data via HCI transport");
1431             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
1432             break;
1433 
1434 #endif
1435 #ifdef ENABLE_BLE
1436         // LE INIT
1437         case HCI_INIT_LE_READ_BUFFER_SIZE:
1438             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
1439             hci_send_cmd(&hci_le_read_buffer_size);
1440             break;
1441         case HCI_INIT_LE_SET_EVENT_MASK:
1442             hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
1443             hci_send_cmd(&hci_le_set_event_mask, 0x809FF, 0x0); // bits 0-8, 11, 19
1444             break;
1445         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
1446             // LE Supported Host = 1, Simultaneous Host = 0
1447             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
1448             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1449             break;
1450 #endif
1451 
1452 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1453         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
1454             hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
1455             hci_send_cmd(&hci_le_read_maximum_data_length);
1456             break;
1457         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
1458             hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
1459             hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1460             break;
1461 #endif
1462 
1463 #ifdef ENABLE_LE_CENTRAL
1464         case HCI_INIT_READ_WHITE_LIST_SIZE:
1465             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
1466             hci_send_cmd(&hci_le_read_white_list_size);
1467             break;
1468         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1469             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, own address type, accept all advs
1470             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1471             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, hci_stack->le_own_addr_type, 0);
1472             break;
1473 #endif
1474         default:
1475             return;
1476     }
1477 }
1478 
1479 static void hci_init_done(void){
1480     // done. tell the app
1481     log_info("hci_init_done -> HCI_STATE_WORKING");
1482     hci_stack->state = HCI_STATE_WORKING;
1483     hci_emit_state();
1484     hci_run();
1485 }
1486 
1487 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
1488 
1489     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
1490 
1491     uint8_t command_completed = 0;
1492 
1493     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1494         uint16_t opcode = little_endian_read_16(packet,3);
1495         if (opcode == hci_stack->last_cmd_opcode){
1496             command_completed = 1;
1497             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
1498         } else {
1499             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
1500         }
1501     }
1502 
1503     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
1504         uint8_t  status = packet[2];
1505         uint16_t opcode = little_endian_read_16(packet,4);
1506         if (opcode == hci_stack->last_cmd_opcode){
1507             if (status){
1508                 command_completed = 1;
1509                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
1510             } else {
1511                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
1512             }
1513         } else {
1514             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1515         }
1516     }
1517 
1518 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1519 
1520     // Vendor == CSR
1521     if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1522         // TODO: track actual command
1523         command_completed = 1;
1524     }
1525 
1526     // Vendor == Toshiba
1527     if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1528         // TODO: track actual command
1529         command_completed = 1;
1530         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
1531         hci_stack->num_cmd_packets = 1;
1532     }
1533 
1534     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1535     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1536     //
1537     // HCI Reset
1538     // Timeout 100 ms
1539     // HCI Reset
1540     // Command Complete Reset
1541     // HCI Read Local Version Information
1542     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1543     // hang...
1544     //
1545     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1546     if (!command_completed
1547             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1548             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
1549 
1550         uint16_t opcode = little_endian_read_16(packet,3);
1551         if (opcode == hci_reset.opcode){
1552             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1553             return;
1554         }
1555     }
1556 
1557     // CSR & H5
1558     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1559     if (!command_completed
1560             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1561             && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){
1562 
1563         uint16_t opcode = little_endian_read_16(packet,3);
1564         if (opcode == hci_reset.opcode){
1565             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1566             return;
1567         }
1568     }
1569 
1570     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
1571     // fix: Correct substate and behave as command below
1572     if (command_completed){
1573         switch (hci_stack->substate){
1574             case HCI_INIT_SEND_RESET:
1575                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1576                 break;
1577             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1578                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1579                 break;
1580             default:
1581                 break;
1582         }
1583     }
1584 
1585 #endif
1586 
1587     if (!command_completed) return;
1588 
1589     int need_baud_change = 0;
1590     int need_addr_change = 0;
1591 
1592 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1593     need_baud_change = hci_stack->config
1594                         && hci_stack->chipset
1595                         && hci_stack->chipset->set_baudrate_command
1596                         && hci_stack->hci_transport->set_baudrate
1597                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1598 
1599     need_addr_change = hci_stack->custom_bd_addr_set
1600                         && hci_stack->chipset
1601                         && hci_stack->chipset->set_bd_addr_command;
1602 #endif
1603 
1604     switch(hci_stack->substate){
1605 
1606 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1607         case HCI_INIT_SEND_RESET:
1608             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
1609             // fix: just correct substate and behave as command below
1610             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1611             btstack_run_loop_remove_timer(&hci_stack->timeout);
1612             break;
1613         case HCI_INIT_W4_SEND_RESET:
1614             btstack_run_loop_remove_timer(&hci_stack->timeout);
1615             break;
1616         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
1617             log_info("Received local name, need baud change %d", need_baud_change);
1618             if (need_baud_change){
1619                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
1620                 return;
1621             }
1622             // skip baud change
1623             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1624             return;
1625         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1626             // for STLC2500D, baud rate change already happened.
1627             // for others, baud rate gets changed now
1628             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
1629                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1630                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1631                 hci_stack->hci_transport->set_baudrate(baud_rate);
1632             }
1633             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1634             return;
1635         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1636             btstack_run_loop_remove_timer(&hci_stack->timeout);
1637             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1638             return;
1639         case HCI_INIT_W4_CUSTOM_INIT:
1640             // repeat custom init
1641             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1642             return;
1643 #else
1644         case HCI_INIT_W4_SEND_RESET:
1645             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1646             return ;
1647 #endif
1648 
1649         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1650             if (need_baud_change &&
1651               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
1652                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
1653                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1654                 return;
1655             }
1656             if (need_addr_change){
1657                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1658                 return;
1659             }
1660             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1661             return;
1662 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1663         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
1664             if (need_baud_change){
1665                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1666                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1667                 hci_stack->hci_transport->set_baudrate(baud_rate);
1668             }
1669             if (need_addr_change){
1670                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1671                 return;
1672             }
1673             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1674             return;
1675         case HCI_INIT_W4_SET_BD_ADDR:
1676             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
1677             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
1678             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
1679                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
1680                 return;
1681             }
1682             // skipping st warm boot
1683             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1684             return;
1685         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
1686             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1687             return;
1688 #endif
1689         case HCI_INIT_W4_READ_BD_ADDR:
1690             // only read buffer size if supported
1691             if (hci_stack->local_supported_commands[0] & 0x01) {
1692                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
1693                 return;
1694             }
1695             // skipping read buffer size
1696             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1697             return;
1698         case HCI_INIT_W4_SET_EVENT_MASK:
1699             // skip Classic init commands for LE only chipsets
1700             if (!hci_classic_supported()){
1701 #ifdef ENABLE_BLE
1702                 if (hci_le_supported()){
1703                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
1704                     return;
1705                 }
1706 #endif
1707                 log_error("Neither BR/EDR nor LE supported");
1708                 hci_init_done();
1709                 return;
1710             }
1711             if (!gap_ssp_supported()){
1712                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
1713                 return;
1714             }
1715             break;
1716 #ifdef ENABLE_BLE
1717         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1718             // skip write le host if not supported (e.g. on LE only EM9301)
1719             if (hci_stack->local_supported_commands[0] & 0x02) break;
1720             hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1721             return;
1722 
1723 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1724         case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED:
1725             log_info("Supported commands %x", hci_stack->local_supported_commands[0] & 0x30);
1726             if ((hci_stack->local_supported_commands[0] & 0x30) == 0x30){
1727                 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1728                 return;
1729             }
1730             // explicit fall through to reduce repetitions
1731 
1732 #ifdef ENABLE_LE_CENTRAL
1733             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1734 #else
1735             hci_init_done();
1736 #endif
1737             return;
1738 #endif  /* ENABLE_LE_DATA_LENGTH_EXTENSION */
1739 
1740 #endif  /* ENABLE_BLE */
1741 
1742 #ifdef ENABLE_SCO_OVER_HCI
1743         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1744             // skip write synchronous flow control if not supported
1745             if (hci_stack->local_supported_commands[0] & 0x04) break;
1746             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1747             // explicit fall through to reduce repetitions
1748 
1749         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1750             // skip write default erroneous data reporting if not supported
1751             if (hci_stack->local_supported_commands[0] & 0x08) break;
1752             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1753             // explicit fall through to reduce repetitions
1754 
1755         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1756             // skip bcm set sco pcm config on non-Broadcom chipsets
1757             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break;
1758             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1759             // explicit fall through to reduce repetitions
1760 
1761         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1762             if (!hci_le_supported()){
1763                 // SKIP LE init for Classic only configuration
1764                 hci_init_done();
1765                 return;
1766             }
1767             break;
1768 
1769 #else /* !ENABLE_SCO_OVER_HCI */
1770 
1771         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1772 #ifdef ENABLE_BLE
1773             if (hci_le_supported()){
1774                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
1775                 return;
1776             }
1777 #endif
1778             // SKIP LE init for Classic only configuration
1779             hci_init_done();
1780             return;
1781 #endif /* ENABLE_SCO_OVER_HCI */
1782 
1783 // avoid compile error due to duplicate cases: HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT == HCI_INIT_DONE-1
1784 #if defined(ENABLE_BLE) || defined(ENABLE_LE_DATA_LENGTH_EXTENSION) || defined(ENABLE_LE_CENTRAL)
1785         // Response to command before init done state -> init done
1786         case (HCI_INIT_DONE-1):
1787             hci_init_done();
1788             return;
1789 #endif
1790 
1791         default:
1792             break;
1793     }
1794     hci_initializing_next_state();
1795 }
1796 
1797 static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
1798     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
1799     bd_addr_t bd_address;
1800     memcpy(&bd_address, conn->address, 6);
1801 
1802 #ifdef ENABLE_CLASSIC
1803     // cache needed data
1804     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1805 #endif
1806 
1807     // connection failed, remove entry
1808     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1809     btstack_memory_hci_connection_free( conn );
1810 
1811 #ifdef ENABLE_CLASSIC
1812     // notify client if dedicated bonding
1813     if (notify_dedicated_bonding_failed){
1814         log_info("hci notify_dedicated_bonding_failed");
1815         hci_emit_dedicated_bonding_result(bd_address, status);
1816     }
1817 
1818     // if authentication error, also delete link key
1819     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
1820         gap_drop_link_key_for_bd_addr(bd_address);
1821     }
1822 #endif
1823 }
1824 
1825 static void event_handler(uint8_t *packet, int size){
1826 
1827     uint16_t event_length = packet[1];
1828 
1829     // assert packet is complete
1830     if (size != event_length + 2){
1831         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
1832         return;
1833     }
1834 
1835     bd_addr_t addr;
1836     bd_addr_type_t addr_type;
1837     hci_con_handle_t handle;
1838     hci_connection_t * conn;
1839     int i;
1840     int create_connection_cmd;
1841 
1842 #ifdef ENABLE_CLASSIC
1843     uint8_t link_type;
1844 #endif
1845 
1846     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
1847 
1848     switch (hci_event_packet_get_type(packet)) {
1849 
1850         case HCI_EVENT_COMMAND_COMPLETE:
1851             // get num cmd packets - limit to 1 to reduce complexity
1852             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
1853 
1854             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
1855                 if (packet[5]) break;
1856                 // terminate, name 248 chars
1857                 packet[6+248] = 0;
1858                 log_info("local name: %s", &packet[6]);
1859             }
1860             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1861                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1862                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1863                     uint16_t acl_len = little_endian_read_16(packet, 6);
1864                     uint16_t sco_len = packet[8];
1865 
1866                     // determine usable ACL/SCO payload size
1867                     hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
1868                     hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
1869 
1870                     hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1871                     hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1872 
1873                     log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
1874                              acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1875                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1876                 }
1877             }
1878 #ifdef ENABLE_BLE
1879             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1880                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1881                 hci_stack->le_acl_packets_total_num  = packet[8];
1882                 // determine usable ACL payload size
1883                 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1884                     hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1885                 }
1886                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1887             }
1888 #endif
1889 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1890             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_maximum_data_length)){
1891                 hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
1892                 hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
1893                 log_info("hci_le_read_maximum_data_length: tx octets %u, tx time %u us", hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1894             }
1895 #endif
1896 #ifdef ENABLE_LE_CENTRAL
1897             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1898                 hci_stack->le_whitelist_capacity = packet[6];
1899                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1900             }
1901 #endif
1902             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1903                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1904 				hci_stack->local_bd_addr);
1905                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1906                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1907 #ifdef ENABLE_CLASSIC
1908                 if (hci_stack->link_key_db){
1909                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1910                 }
1911 #endif
1912             }
1913 #ifdef ENABLE_CLASSIC
1914             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1915                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1916             }
1917             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_inquiry_cancel)){
1918                 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
1919                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1920                     uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1921                     hci_emit_event(event, sizeof(event), 1);
1922                 }
1923             }
1924 #endif
1925 
1926             // Note: HCI init checks
1927             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1928                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1929 
1930 #ifdef ENABLE_CLASSIC
1931                 // determine usable ACL packet types based on host buffer size and supported features
1932                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1933                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
1934 #endif
1935                 // Classic/LE
1936                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1937             }
1938             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1939                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1940                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1941                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1942                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1943                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1944                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1945             }
1946             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1947                 hci_stack->local_supported_commands[0] =
1948                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7 / Read Buffer Size
1949                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6 / Write Le Host Supported
1950                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4 / Write Synchronous Flow Control Enable
1951                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08)      |  // bit 3 = Octet 18, bit 3 / Write Default Erroneous Data Reporting
1952                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x01) << 4 |  // bit 4 = Octet 34, bit 0 / LE Write Suggested Default Data Length
1953                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x08) << 2 |  // bit 5 = Octet 35, bit 3 / LE Read Maximum Data Length
1954                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x20) << 1;   // bit 6 = Octet 35, bit 5 / LE Set Default PHY
1955                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1956             }
1957 #ifdef ENABLE_CLASSIC
1958             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1959                 if (packet[5] == 0){
1960                     hci_stack->synchronous_flow_control_enabled = 1;
1961                 }
1962             }
1963 #endif
1964             break;
1965 
1966         case HCI_EVENT_COMMAND_STATUS:
1967             // get num cmd packets - limit to 1 to reduce complexity
1968             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
1969 
1970             // check command status to detected failed outgoing connections
1971             create_connection_cmd = 0;
1972 #ifdef ENABLE_CLASSIC
1973             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
1974                 create_connection_cmd = 1;
1975             }
1976 #endif
1977 #ifdef ENABLE_LE_CENTRAL
1978             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_le_create_connection)){
1979                 create_connection_cmd = 1;
1980             }
1981 #endif
1982             if (create_connection_cmd) {
1983                 uint8_t status = hci_event_command_status_get_status(packet);
1984                 conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, hci_stack->outgoing_addr_type);
1985                 log_info("command status (create connection), status %x, connection %p, addr %s, type %x", status, conn, bd_addr_to_str(hci_stack->outgoing_addr), hci_stack->outgoing_addr_type);
1986 
1987                 // reset outgoing address info
1988                 memset(hci_stack->outgoing_addr, 0, 6);
1989                 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
1990 
1991                 // error => outgoing connection failed
1992                 if ((conn != NULL) && (status != 0)){
1993                     hci_handle_connection_failed(conn, status);
1994                 }
1995             }
1996             break;
1997 
1998         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1999             int offset = 3;
2000             for (i=0; i<packet[2];i++){
2001                 handle = little_endian_read_16(packet, offset) & 0x0fff;
2002                 offset += 2;
2003                 uint16_t num_packets = little_endian_read_16(packet, offset);
2004                 offset += 2;
2005 
2006                 conn = hci_connection_for_handle(handle);
2007                 if (!conn){
2008                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
2009                     continue;
2010                 }
2011 
2012                 if (conn->address_type == BD_ADDR_TYPE_SCO){
2013 #ifdef ENABLE_CLASSIC
2014                     if (conn->num_sco_packets_sent >= num_packets){
2015                         conn->num_sco_packets_sent -= num_packets;
2016                     } else {
2017                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
2018                         conn->num_sco_packets_sent = 0;
2019                     }
2020                     hci_notify_if_sco_can_send_now();
2021 #endif
2022                 } else {
2023                     if (conn->num_acl_packets_sent >= num_packets){
2024                         conn->num_acl_packets_sent -= num_packets;
2025                     } else {
2026                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
2027                         conn->num_acl_packets_sent = 0;
2028                     }
2029                 }
2030                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
2031             }
2032             break;
2033         }
2034 
2035 #ifdef ENABLE_CLASSIC
2036         case HCI_EVENT_INQUIRY_COMPLETE:
2037             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
2038                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2039                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2040                 hci_emit_event(event, sizeof(event), 1);
2041             }
2042             break;
2043         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
2044             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
2045                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
2046             }
2047             break;
2048         case HCI_EVENT_CONNECTION_REQUEST:
2049             reverse_bd_addr(&packet[2], addr);
2050             // TODO: eval COD 8-10
2051             link_type = packet[11];
2052             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
2053             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
2054             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2055             if (!conn) {
2056                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2057             }
2058             if (!conn) {
2059                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
2060                 hci_stack->decline_reason = 0x0d;
2061                 bd_addr_copy(hci_stack->decline_addr, addr);
2062                 break;
2063             }
2064             conn->role  = HCI_ROLE_SLAVE;
2065             conn->state = RECEIVED_CONNECTION_REQUEST;
2066             // store info about eSCO
2067             if (link_type == 0x02){
2068                 conn->remote_supported_feature_eSCO = 1;
2069             }
2070             hci_run();
2071             break;
2072 
2073         case HCI_EVENT_CONNECTION_COMPLETE:
2074             // Connection management
2075             reverse_bd_addr(&packet[5], addr);
2076             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2077             addr_type = BD_ADDR_TYPE_CLASSIC;
2078             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2079             if (conn) {
2080                 if (!packet[2]){
2081                     conn->state = OPEN;
2082                     conn->con_handle = little_endian_read_16(packet, 3);
2083                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
2084 
2085                     // restart timer
2086                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2087                     btstack_run_loop_add_timer(&conn->timeout);
2088 
2089                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2090 
2091                     hci_emit_nr_connections_changed();
2092                 } else {
2093                     // connection failed
2094                     hci_handle_connection_failed(conn, packet[2]);
2095                 }
2096             }
2097             break;
2098 
2099         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
2100             reverse_bd_addr(&packet[5], addr);
2101             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2102             if (packet[2]){
2103                 // connection failed
2104                 break;
2105             }
2106             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2107             if (!conn) {
2108                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2109             }
2110             if (!conn) {
2111                 break;
2112             }
2113             conn->state = OPEN;
2114             conn->con_handle = little_endian_read_16(packet, 3);
2115 
2116 #ifdef ENABLE_SCO_OVER_HCI
2117             // update SCO
2118             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
2119                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
2120             }
2121 #endif
2122             break;
2123 
2124         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2125             handle = little_endian_read_16(packet, 3);
2126             conn = hci_connection_for_handle(handle);
2127             if (!conn) break;
2128             if (!packet[2]){
2129                 uint8_t * features = &packet[5];
2130                 if (features[6] & (1 << 3)){
2131                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
2132                 }
2133                 if (features[3] & (1<<7)){
2134                     conn->remote_supported_feature_eSCO = 1;
2135                 }
2136             }
2137             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2138             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
2139             if (conn->bonding_flags & BONDING_DEDICATED){
2140                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2141             }
2142             break;
2143 
2144         case HCI_EVENT_LINK_KEY_REQUEST:
2145             log_info("HCI_EVENT_LINK_KEY_REQUEST");
2146             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
2147             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
2148             if (hci_stack->bondable && !hci_stack->link_key_db) break;
2149             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
2150             hci_run();
2151             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
2152             return;
2153 
2154         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2155             reverse_bd_addr(&packet[2], addr);
2156             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2157             if (!conn) break;
2158             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
2159             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2160             // Change Connection Encryption keeps link key type
2161             if (link_key_type != CHANGED_COMBINATION_KEY){
2162                 conn->link_key_type = link_key_type;
2163             }
2164             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2165             // still forward event to allow dismiss of pairing dialog
2166             break;
2167         }
2168 
2169         case HCI_EVENT_PIN_CODE_REQUEST:
2170             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
2171             // non-bondable mode: pin code negative reply will be sent
2172             if (!hci_stack->bondable){
2173                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
2174                 hci_run();
2175                 return;
2176             }
2177             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
2178             if (!hci_stack->link_key_db) break;
2179             hci_event_pin_code_request_get_bd_addr(packet, addr);
2180             hci_stack->link_key_db->delete_link_key(addr);
2181             break;
2182 
2183         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2184             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
2185             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
2186             break;
2187 
2188         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2189             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2190             if (!hci_stack->ssp_auto_accept) break;
2191             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
2192             break;
2193 
2194         case HCI_EVENT_USER_PASSKEY_REQUEST:
2195             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2196             if (!hci_stack->ssp_auto_accept) break;
2197             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
2198             break;
2199         case HCI_EVENT_MODE_CHANGE:
2200             handle = hci_event_mode_change_get_handle(packet);
2201             conn = hci_connection_for_handle(handle);
2202             if (!conn) break;
2203             conn->connection_mode = hci_event_mode_change_get_mode(packet);
2204             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
2205             break;
2206 #endif
2207 
2208         case HCI_EVENT_ENCRYPTION_CHANGE:
2209             handle = little_endian_read_16(packet, 3);
2210             conn = hci_connection_for_handle(handle);
2211             if (!conn) break;
2212             if (packet[2] == 0) {
2213                 if (packet[5]){
2214                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
2215                 } else {
2216                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
2217                 }
2218             }
2219 #ifdef ENABLE_CLASSIC
2220             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2221 #endif
2222             break;
2223 
2224 #ifdef ENABLE_CLASSIC
2225         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2226             handle = little_endian_read_16(packet, 3);
2227             conn = hci_connection_for_handle(handle);
2228             if (!conn) break;
2229 
2230             // dedicated bonding: send result and disconnect
2231             if (conn->bonding_flags & BONDING_DEDICATED){
2232                 conn->bonding_flags &= ~BONDING_DEDICATED;
2233                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2234                 conn->bonding_status = packet[2];
2235                 break;
2236             }
2237 
2238             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
2239                 // link key sufficient for requested security
2240                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2241                 break;
2242             }
2243             // not enough
2244             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2245             break;
2246 #endif
2247 
2248         // HCI_EVENT_DISCONNECTION_COMPLETE
2249         // has been split, to first notify stack before shutting connection down
2250         // see end of function, too.
2251         case HCI_EVENT_DISCONNECTION_COMPLETE:
2252             if (packet[2]) break;   // status != 0
2253             handle = little_endian_read_16(packet, 3);
2254             // drop outgoing ACL fragments if it is for closed connection
2255             if (hci_stack->acl_fragmentation_total_size > 0) {
2256                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
2257                     log_info("hci: drop fragmented ACL data for closed connection");
2258                      hci_stack->acl_fragmentation_total_size = 0;
2259                      hci_stack->acl_fragmentation_pos = 0;
2260                 }
2261             }
2262 
2263             // re-enable advertisements for le connections if active
2264             conn = hci_connection_for_handle(handle);
2265             if (!conn) break;
2266             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2267 #ifdef ENABLE_BLE
2268 #ifdef ENABLE_LE_PERIPHERAL
2269             if (hci_is_le_connection(conn)){
2270                 hci_reenable_advertisements_if_needed();
2271             }
2272 #endif
2273 #endif
2274             break;
2275 
2276         case HCI_EVENT_HARDWARE_ERROR:
2277             log_error("Hardware Error: 0x%02x", packet[2]);
2278             if (hci_stack->hardware_error_callback){
2279                 (*hci_stack->hardware_error_callback)(packet[2]);
2280             } else {
2281                 // if no special requests, just reboot stack
2282                 hci_power_control_off();
2283                 hci_power_control_on();
2284             }
2285             break;
2286 
2287 #ifdef ENABLE_CLASSIC
2288         case HCI_EVENT_ROLE_CHANGE:
2289             if (packet[2]) break;   // status != 0
2290             reverse_bd_addr(&packet[3], addr);
2291             addr_type = BD_ADDR_TYPE_CLASSIC;
2292             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2293             if (!conn) break;
2294             conn->role = packet[9];
2295             break;
2296 #endif
2297 
2298         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2299             // release packet buffer only for asynchronous transport and if there are not further fragements
2300             if (hci_transport_synchronous()) {
2301                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2302                 return; // instead of break: to avoid re-entering hci_run()
2303             }
2304             if (hci_stack->acl_fragmentation_total_size) break;
2305             hci_release_packet_buffer();
2306 
2307             // L2CAP receives this event via the hci_emit_event below
2308 
2309 #ifdef ENABLE_CLASSIC
2310             // For SCO, we do the can_send_now_check here
2311             hci_notify_if_sco_can_send_now();
2312 #endif
2313             break;
2314 
2315 #ifdef ENABLE_CLASSIC
2316         case HCI_EVENT_SCO_CAN_SEND_NOW:
2317             // For SCO, we do the can_send_now_check here
2318             hci_notify_if_sco_can_send_now();
2319             return;
2320 
2321         // explode inquriy results for easier consumption
2322         case HCI_EVENT_INQUIRY_RESULT:
2323         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
2324         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
2325             gap_inquiry_explode(packet);
2326             break;
2327 #endif
2328 
2329 #ifdef ENABLE_BLE
2330         case HCI_EVENT_LE_META:
2331             switch (packet[2]){
2332 #ifdef ENABLE_LE_CENTRAL
2333                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
2334                     // log_info("advertising report received");
2335                     if (!hci_stack->le_scanning_enabled) break;
2336                     le_handle_advertisement_report(packet, size);
2337                     break;
2338 #endif
2339                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
2340                     // Connection management
2341                     reverse_bd_addr(&packet[8], addr);
2342                     addr_type = (bd_addr_type_t)packet[7];
2343                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2344                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2345 
2346 #ifdef ENABLE_LE_CENTRAL
2347                     // if auto-connect, remove from whitelist in both roles
2348                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
2349                         hci_remove_from_whitelist(addr_type, addr);
2350                     }
2351                     // handle error: error is reported only to the initiator -> outgoing connection
2352                     if (packet[3]){
2353 
2354                         // handle cancelled outgoing connection
2355                         // "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2356                         //  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2357                         //  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2358                         if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2359                             conn = gap_get_outgoing_connection();
2360                         }
2361 
2362                         // outgoing connection establishment is done
2363                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2364                         // remove entry
2365                         if (conn){
2366                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2367                             btstack_memory_hci_connection_free( conn );
2368                         }
2369                         break;
2370                     }
2371 #endif
2372                     // on success, both hosts receive connection complete event
2373                     if (packet[6] == HCI_ROLE_MASTER){
2374 #ifdef ENABLE_LE_CENTRAL
2375                         // if we're master, it was an outgoing connection and we're done with it
2376                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2377 #endif
2378                     } else {
2379 #ifdef ENABLE_LE_PERIPHERAL
2380                         // if we're slave, it was an incoming connection, advertisements have stopped
2381                         hci_stack->le_advertisements_active = 0;
2382 #endif
2383                     }
2384                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2385                     if (!conn){
2386                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2387                     }
2388                     // no memory, sorry.
2389                     if (!conn){
2390                         break;
2391                     }
2392 
2393                     conn->state = OPEN;
2394                     conn->role  = packet[6];
2395                     conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
2396                     conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
2397 
2398 #ifdef ENABLE_LE_PERIPHERAL
2399                     if (packet[6] == HCI_ROLE_SLAVE){
2400                         hci_reenable_advertisements_if_needed();
2401                     }
2402 #endif
2403 
2404                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2405 
2406                     // restart timer
2407                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2408                     // btstack_run_loop_add_timer(&conn->timeout);
2409 
2410                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2411 
2412                     hci_emit_nr_connections_changed();
2413                     break;
2414 
2415                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2416                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
2417                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
2418                     conn = hci_connection_for_handle(handle);
2419                     if (!conn) break;
2420                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
2421                     break;
2422 
2423                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
2424                     // connection
2425                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
2426                     conn = hci_connection_for_handle(handle);
2427                     if (conn) {
2428                         // read arguments
2429                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
2430                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
2431                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
2432                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
2433 
2434                         // validate against current connection parameter range
2435                         le_connection_parameter_range_t existing_range;
2436                         gap_get_connection_parameter_range(&existing_range);
2437                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
2438                         if (update_parameter){
2439                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
2440                             conn->le_conn_interval_min = le_conn_interval_min;
2441                             conn->le_conn_interval_max = le_conn_interval_max;
2442                             conn->le_conn_latency = le_conn_latency;
2443                             conn->le_supervision_timeout = le_supervision_timeout;
2444                         } else {
2445                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2446                         }
2447                     }
2448                     break;
2449                 default:
2450                     break;
2451             }
2452             break;
2453 #endif
2454         case HCI_EVENT_VENDOR_SPECIFIC:
2455             // Vendor specific commands often create vendor specific event instead of num completed packets
2456             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
2457             switch (hci_stack->manufacturer){
2458                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
2459                     hci_stack->num_cmd_packets = 1;
2460                     break;
2461                 default:
2462                     break;
2463             }
2464             break;
2465         default:
2466             break;
2467     }
2468 
2469     // handle BT initialization
2470     if (hci_stack->state == HCI_STATE_INITIALIZING){
2471         hci_initializing_event_handler(packet, size);
2472     }
2473 
2474     // help with BT sleep
2475     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2476         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2477         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2478         hci_initializing_next_state();
2479     }
2480 
2481     // notify upper stack
2482 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2483 
2484     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2485     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2486         if (!packet[2]){
2487             handle = little_endian_read_16(packet, 3);
2488             hci_connection_t * aConn = hci_connection_for_handle(handle);
2489             if (aConn) {
2490                 uint8_t status = aConn->bonding_status;
2491                 uint16_t flags = aConn->bonding_flags;
2492                 bd_addr_t bd_address;
2493                 memcpy(&bd_address, aConn->address, 6);
2494                 hci_shutdown_connection(aConn);
2495                 // connection struct is gone, don't access anymore
2496                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2497                     hci_emit_dedicated_bonding_result(bd_address, status);
2498                 }
2499             }
2500         }
2501     }
2502 
2503 	// execute main loop
2504 	hci_run();
2505 }
2506 
2507 #ifdef ENABLE_CLASSIC
2508 static void sco_handler(uint8_t * packet, uint16_t size){
2509     if (!hci_stack->sco_packet_handler) return;
2510     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2511 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2512     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2513     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
2514     if (conn){
2515         conn->num_packets_completed++;
2516         hci_stack->host_completed_packets = 1;
2517         hci_run();
2518     }
2519 #endif
2520 }
2521 #endif
2522 
2523 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2524     hci_dump_packet(packet_type, 1, packet, size);
2525     switch (packet_type) {
2526         case HCI_EVENT_PACKET:
2527             event_handler(packet, size);
2528             break;
2529         case HCI_ACL_DATA_PACKET:
2530             acl_handler(packet, size);
2531             break;
2532 #ifdef ENABLE_CLASSIC
2533         case HCI_SCO_DATA_PACKET:
2534             sco_handler(packet, size);
2535             break;
2536 #endif
2537         default:
2538             break;
2539     }
2540 }
2541 
2542 /**
2543  * @brief Add event packet handler.
2544  */
2545 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2546     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2547 }
2548 
2549 
2550 /** Register HCI packet handlers */
2551 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2552     hci_stack->acl_packet_handler = handler;
2553 }
2554 
2555 #ifdef ENABLE_CLASSIC
2556 /**
2557  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2558  */
2559 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2560     hci_stack->sco_packet_handler = handler;
2561 }
2562 #endif
2563 
2564 static void hci_state_reset(void){
2565     // no connections yet
2566     hci_stack->connections = NULL;
2567 
2568     // keep discoverable/connectable as this has been requested by the client(s)
2569     // hci_stack->discoverable = 0;
2570     // hci_stack->connectable = 0;
2571     // hci_stack->bondable = 1;
2572     // hci_stack->own_addr_type = 0;
2573 
2574     // buffer is free
2575     hci_stack->hci_packet_buffer_reserved = 0;
2576 
2577     // no pending cmds
2578     hci_stack->decline_reason = 0;
2579     hci_stack->new_scan_enable_value = 0xff;
2580 
2581     // LE
2582 #ifdef ENABLE_BLE
2583     memset(hci_stack->le_random_address, 0, 6);
2584     hci_stack->le_random_address_set = 0;
2585 #endif
2586 #ifdef ENABLE_LE_CENTRAL
2587     hci_stack->le_scanning_active  = 0;
2588     hci_stack->le_scan_type = 0xff;
2589     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2590     hci_stack->le_whitelist = 0;
2591     hci_stack->le_whitelist_capacity = 0;
2592 #endif
2593 }
2594 
2595 #ifdef ENABLE_CLASSIC
2596 /**
2597  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2598  */
2599 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2600     // store and open remote device db
2601     hci_stack->link_key_db = link_key_db;
2602     if (hci_stack->link_key_db) {
2603         hci_stack->link_key_db->open();
2604     }
2605 }
2606 #endif
2607 
2608 void hci_init(const hci_transport_t *transport, const void *config){
2609 
2610 #ifdef HAVE_MALLOC
2611     if (!hci_stack) {
2612         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2613     }
2614 #else
2615     hci_stack = &hci_stack_static;
2616 #endif
2617     memset(hci_stack, 0, sizeof(hci_stack_t));
2618 
2619     // reference to use transport layer implementation
2620     hci_stack->hci_transport = transport;
2621 
2622     // reference to used config
2623     hci_stack->config = config;
2624 
2625     // setup pointer for outgoing packet buffer
2626     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2627 
2628     // max acl payload size defined in config.h
2629     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2630 
2631     // register packet handlers with transport
2632     transport->register_packet_handler(&packet_handler);
2633 
2634     hci_stack->state = HCI_STATE_OFF;
2635 
2636     // class of device
2637     hci_stack->class_of_device = 0x007a020c; // Smartphone
2638 
2639     // bondable by default
2640     hci_stack->bondable = 1;
2641 
2642 #ifdef ENABLE_CLASSIC
2643     // classic name
2644     hci_stack->local_name = default_classic_name;
2645 
2646     // Master slave policy
2647     hci_stack->master_slave_policy = 1;
2648 #endif
2649 
2650     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2651     hci_stack->ssp_enable = 1;
2652     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2653     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2654     hci_stack->ssp_auto_accept = 1;
2655 
2656     // voice setting - signed 16 bit pcm data with CVSD over the air
2657     hci_stack->sco_voice_setting = 0x60;
2658 
2659 #ifdef ENABLE_LE_CENTRAL
2660     // connection parameter to use for outgoing connections
2661     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
2662     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
2663     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
2664     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
2665     hci_stack->le_connection_latency      = 4;         // 4
2666     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
2667     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
2668     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
2669 #endif
2670 
2671 #ifdef ENABLE_LE_PERIPHERAL
2672     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
2673 #endif
2674 
2675     // connection parameter range used to answer connection parameter update requests in l2cap
2676     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2677     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2678     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2679     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2680     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2681     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2682 
2683     hci_state_reset();
2684 }
2685 
2686 /**
2687  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2688  */
2689 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2690     hci_stack->chipset = chipset_driver;
2691 
2692     // reset chipset driver - init is also called on power_up
2693     if (hci_stack->chipset && hci_stack->chipset->init){
2694         hci_stack->chipset->init(hci_stack->config);
2695     }
2696 }
2697 
2698 /**
2699  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2700  */
2701 void hci_set_control(const btstack_control_t *hardware_control){
2702     // references to used control implementation
2703     hci_stack->control = hardware_control;
2704     // init with transport config
2705     hardware_control->init(hci_stack->config);
2706 }
2707 
2708 void hci_close(void){
2709     // close remote device db
2710     if (hci_stack->link_key_db) {
2711         hci_stack->link_key_db->close();
2712     }
2713 
2714     btstack_linked_list_iterator_t lit;
2715     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2716     while (btstack_linked_list_iterator_has_next(&lit)){
2717         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2718         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2719         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2720         hci_shutdown_connection(connection);
2721     }
2722 
2723     hci_power_control(HCI_POWER_OFF);
2724 
2725 #ifdef HAVE_MALLOC
2726     free(hci_stack);
2727 #endif
2728     hci_stack = NULL;
2729 }
2730 
2731 #ifdef ENABLE_CLASSIC
2732 void gap_set_class_of_device(uint32_t class_of_device){
2733     hci_stack->class_of_device = class_of_device;
2734 }
2735 
2736 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
2737     hci_stack->default_link_policy_settings = default_link_policy_settings;
2738 }
2739 
2740 void hci_disable_l2cap_timeout_check(void){
2741     disable_l2cap_timeouts = 1;
2742 }
2743 #endif
2744 
2745 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2746 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2747 void hci_set_bd_addr(bd_addr_t addr){
2748     memcpy(hci_stack->custom_bd_addr, addr, 6);
2749     hci_stack->custom_bd_addr_set = 1;
2750 }
2751 #endif
2752 
2753 // State-Module-Driver overview
2754 // state                    module  low-level
2755 // HCI_STATE_OFF             off      close
2756 // HCI_STATE_INITIALIZING,   on       open
2757 // HCI_STATE_WORKING,        on       open
2758 // HCI_STATE_HALTING,        on       open
2759 // HCI_STATE_SLEEPING,    off/sleep   close
2760 // HCI_STATE_FALLING_ASLEEP  on       open
2761 
2762 static int hci_power_control_on(void){
2763 
2764     // power on
2765     int err = 0;
2766     if (hci_stack->control && hci_stack->control->on){
2767         err = (*hci_stack->control->on)();
2768     }
2769     if (err){
2770         log_error( "POWER_ON failed");
2771         hci_emit_hci_open_failed();
2772         return err;
2773     }
2774 
2775     // int chipset driver
2776     if (hci_stack->chipset && hci_stack->chipset->init){
2777         hci_stack->chipset->init(hci_stack->config);
2778     }
2779 
2780     // init transport
2781     if (hci_stack->hci_transport->init){
2782         hci_stack->hci_transport->init(hci_stack->config);
2783     }
2784 
2785     // open transport
2786     err = hci_stack->hci_transport->open();
2787     if (err){
2788         log_error( "HCI_INIT failed, turning Bluetooth off again");
2789         if (hci_stack->control && hci_stack->control->off){
2790             (*hci_stack->control->off)();
2791         }
2792         hci_emit_hci_open_failed();
2793         return err;
2794     }
2795     return 0;
2796 }
2797 
2798 static void hci_power_control_off(void){
2799 
2800     log_info("hci_power_control_off");
2801 
2802     // close low-level device
2803     hci_stack->hci_transport->close();
2804 
2805     log_info("hci_power_control_off - hci_transport closed");
2806 
2807     // power off
2808     if (hci_stack->control && hci_stack->control->off){
2809         (*hci_stack->control->off)();
2810     }
2811 
2812     log_info("hci_power_control_off - control closed");
2813 
2814     hci_stack->state = HCI_STATE_OFF;
2815 }
2816 
2817 static void hci_power_control_sleep(void){
2818 
2819     log_info("hci_power_control_sleep");
2820 
2821 #if 0
2822     // don't close serial port during sleep
2823 
2824     // close low-level device
2825     hci_stack->hci_transport->close(hci_stack->config);
2826 #endif
2827 
2828     // sleep mode
2829     if (hci_stack->control && hci_stack->control->sleep){
2830         (*hci_stack->control->sleep)();
2831     }
2832 
2833     hci_stack->state = HCI_STATE_SLEEPING;
2834 }
2835 
2836 static int hci_power_control_wake(void){
2837 
2838     log_info("hci_power_control_wake");
2839 
2840     // wake on
2841     if (hci_stack->control && hci_stack->control->wake){
2842         (*hci_stack->control->wake)();
2843     }
2844 
2845 #if 0
2846     // open low-level device
2847     int err = hci_stack->hci_transport->open(hci_stack->config);
2848     if (err){
2849         log_error( "HCI_INIT failed, turning Bluetooth off again");
2850         if (hci_stack->control && hci_stack->control->off){
2851             (*hci_stack->control->off)();
2852         }
2853         hci_emit_hci_open_failed();
2854         return err;
2855     }
2856 #endif
2857 
2858     return 0;
2859 }
2860 
2861 static void hci_power_transition_to_initializing(void){
2862     // set up state machine
2863     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2864     hci_stack->hci_packet_buffer_reserved = 0;
2865     hci_stack->state = HCI_STATE_INITIALIZING;
2866     hci_stack->substate = HCI_INIT_SEND_RESET;
2867 }
2868 
2869 int hci_power_control(HCI_POWER_MODE power_mode){
2870 
2871     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2872 
2873     int err = 0;
2874     switch (hci_stack->state){
2875 
2876         case HCI_STATE_OFF:
2877             switch (power_mode){
2878                 case HCI_POWER_ON:
2879                     err = hci_power_control_on();
2880                     if (err) {
2881                         log_error("hci_power_control_on() error %d", err);
2882                         return err;
2883                     }
2884                     hci_power_transition_to_initializing();
2885                     break;
2886                 case HCI_POWER_OFF:
2887                     // do nothing
2888                     break;
2889                 case HCI_POWER_SLEEP:
2890                     // do nothing (with SLEEP == OFF)
2891                     break;
2892             }
2893             break;
2894 
2895         case HCI_STATE_INITIALIZING:
2896             switch (power_mode){
2897                 case HCI_POWER_ON:
2898                     // do nothing
2899                     break;
2900                 case HCI_POWER_OFF:
2901                     // no connections yet, just turn it off
2902                     hci_power_control_off();
2903                     break;
2904                 case HCI_POWER_SLEEP:
2905                     // no connections yet, just turn it off
2906                     hci_power_control_sleep();
2907                     break;
2908             }
2909             break;
2910 
2911         case HCI_STATE_WORKING:
2912             switch (power_mode){
2913                 case HCI_POWER_ON:
2914                     // do nothing
2915                     break;
2916                 case HCI_POWER_OFF:
2917                     // see hci_run
2918                     hci_stack->state = HCI_STATE_HALTING;
2919                     break;
2920                 case HCI_POWER_SLEEP:
2921                     // see hci_run
2922                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2923                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2924                     break;
2925             }
2926             break;
2927 
2928         case HCI_STATE_HALTING:
2929             switch (power_mode){
2930                 case HCI_POWER_ON:
2931                     hci_power_transition_to_initializing();
2932                     break;
2933                 case HCI_POWER_OFF:
2934                     // do nothing
2935                     break;
2936                 case HCI_POWER_SLEEP:
2937                     // see hci_run
2938                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2939                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2940                     break;
2941             }
2942             break;
2943 
2944         case HCI_STATE_FALLING_ASLEEP:
2945             switch (power_mode){
2946                 case HCI_POWER_ON:
2947 
2948 #ifdef HAVE_PLATFORM_IPHONE_OS
2949                     // nothing to do, if H4 supports power management
2950                     if (btstack_control_iphone_power_management_enabled()){
2951                         hci_stack->state = HCI_STATE_INITIALIZING;
2952                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2953                         break;
2954                     }
2955 #endif
2956                     hci_power_transition_to_initializing();
2957                     break;
2958                 case HCI_POWER_OFF:
2959                     // see hci_run
2960                     hci_stack->state = HCI_STATE_HALTING;
2961                     break;
2962                 case HCI_POWER_SLEEP:
2963                     // do nothing
2964                     break;
2965             }
2966             break;
2967 
2968         case HCI_STATE_SLEEPING:
2969             switch (power_mode){
2970                 case HCI_POWER_ON:
2971 
2972 #ifdef HAVE_PLATFORM_IPHONE_OS
2973                     // nothing to do, if H4 supports power management
2974                     if (btstack_control_iphone_power_management_enabled()){
2975                         hci_stack->state = HCI_STATE_INITIALIZING;
2976                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2977                         hci_update_scan_enable();
2978                         break;
2979                     }
2980 #endif
2981                     err = hci_power_control_wake();
2982                     if (err) return err;
2983                     hci_power_transition_to_initializing();
2984                     break;
2985                 case HCI_POWER_OFF:
2986                     hci_stack->state = HCI_STATE_HALTING;
2987                     break;
2988                 case HCI_POWER_SLEEP:
2989                     // do nothing
2990                     break;
2991             }
2992             break;
2993     }
2994 
2995     // create internal event
2996 	hci_emit_state();
2997 
2998 	// trigger next/first action
2999 	hci_run();
3000 
3001     return 0;
3002 }
3003 
3004 
3005 #ifdef ENABLE_CLASSIC
3006 
3007 static void hci_update_scan_enable(void){
3008     // 2 = page scan, 1 = inq scan
3009     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
3010     hci_run();
3011 }
3012 
3013 void gap_discoverable_control(uint8_t enable){
3014     if (enable) enable = 1; // normalize argument
3015 
3016     if (hci_stack->discoverable == enable){
3017         hci_emit_discoverable_enabled(hci_stack->discoverable);
3018         return;
3019     }
3020 
3021     hci_stack->discoverable = enable;
3022     hci_update_scan_enable();
3023 }
3024 
3025 void gap_connectable_control(uint8_t enable){
3026     if (enable) enable = 1; // normalize argument
3027 
3028     // don't emit event
3029     if (hci_stack->connectable == enable) return;
3030 
3031     hci_stack->connectable = enable;
3032     hci_update_scan_enable();
3033 }
3034 #endif
3035 
3036 void gap_local_bd_addr(bd_addr_t address_buffer){
3037     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
3038 }
3039 
3040 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3041 static void hci_host_num_completed_packets(void){
3042 
3043     // create packet manually as arrays are not supported and num_commands should not get reduced
3044     hci_reserve_packet_buffer();
3045     uint8_t * packet = hci_get_outgoing_packet_buffer();
3046 
3047     uint16_t size = 0;
3048     uint16_t num_handles = 0;
3049     packet[size++] = 0x35;
3050     packet[size++] = 0x0c;
3051     size++;  // skip param len
3052     size++;  // skip num handles
3053 
3054     // add { handle, packets } entries
3055     btstack_linked_item_t * it;
3056     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3057         hci_connection_t * connection = (hci_connection_t *) it;
3058         if (connection->num_packets_completed){
3059             little_endian_store_16(packet, size, connection->con_handle);
3060             size += 2;
3061             little_endian_store_16(packet, size, connection->num_packets_completed);
3062             size += 2;
3063             //
3064             num_handles++;
3065             connection->num_packets_completed = 0;
3066         }
3067     }
3068 
3069     packet[2] = size - 3;
3070     packet[3] = num_handles;
3071 
3072     hci_stack->host_completed_packets = 0;
3073 
3074     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3075     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3076 
3077     // release packet buffer for synchronous transport implementations
3078     if (hci_transport_synchronous()){
3079         hci_release_packet_buffer();
3080         hci_emit_transport_packet_sent();
3081     }
3082 }
3083 #endif
3084 
3085 static void hci_run(void){
3086 
3087     // log_info("hci_run: entered");
3088     btstack_linked_item_t * it;
3089 
3090     // send continuation fragments first, as they block the prepared packet buffer
3091     if (hci_stack->acl_fragmentation_total_size > 0) {
3092         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
3093         hci_connection_t *connection = hci_connection_for_handle(con_handle);
3094         if (connection) {
3095             if (hci_can_send_prepared_acl_packet_now(con_handle)){
3096                 hci_send_acl_packet_fragments(connection);
3097                 return;
3098             }
3099         } else {
3100             // connection gone -> discard further fragments
3101             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
3102             hci_stack->acl_fragmentation_total_size = 0;
3103             hci_stack->acl_fragmentation_pos = 0;
3104         }
3105     }
3106 
3107 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3108     // send host num completed packets next as they don't require num_cmd_packets > 0
3109     if (!hci_can_send_comand_packet_transport()) return;
3110     if (hci_stack->host_completed_packets){
3111         hci_host_num_completed_packets();
3112         return;
3113     }
3114 #endif
3115 
3116     if (!hci_can_send_command_packet_now()) return;
3117 
3118     // global/non-connection oriented commands
3119 
3120 #ifdef ENABLE_CLASSIC
3121     // decline incoming connections
3122     if (hci_stack->decline_reason){
3123         uint8_t reason = hci_stack->decline_reason;
3124         hci_stack->decline_reason = 0;
3125         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
3126         return;
3127     }
3128     // send scan enable
3129     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
3130         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
3131         hci_stack->new_scan_enable_value = 0xff;
3132         return;
3133     }
3134     // start/stop inquiry
3135     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX){
3136         uint8_t duration = hci_stack->inquiry_state;
3137         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3138         hci_send_cmd(&hci_inquiry, GAP_IAC_GENERAL_INQUIRY, duration, 0);
3139         return;
3140     }
3141     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
3142         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
3143         hci_send_cmd(&hci_inquiry_cancel);
3144         return;
3145     }
3146     // remote name request
3147     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
3148         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
3149         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
3150             hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
3151         return;
3152     }
3153     // pairing
3154     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
3155         uint8_t state = hci_stack->gap_pairing_state;
3156         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
3157         switch (state){
3158             case GAP_PAIRING_STATE_SEND_PIN:
3159                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, strlen(hci_stack->gap_pairing_input.gap_pairing_pin), hci_stack->gap_pairing_input.gap_pairing_pin);
3160                 break;
3161             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
3162                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
3163                 break;
3164             case GAP_PAIRING_STATE_SEND_PASSKEY:
3165                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
3166                 break;
3167             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
3168                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
3169                 break;
3170             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
3171                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
3172                 break;
3173             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
3174                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
3175                 break;
3176             default:
3177                 break;
3178         }
3179         return;
3180     }
3181 #endif
3182 
3183 #ifdef ENABLE_BLE
3184     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
3185     if ((hci_stack->state == HCI_STATE_WORKING)
3186     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
3187 
3188 #ifdef ENABLE_LE_CENTRAL
3189         // handle le scan
3190         if ((hci_stack->le_scanning_enabled != hci_stack->le_scanning_active)){
3191             hci_stack->le_scanning_active = hci_stack->le_scanning_enabled;
3192             hci_send_cmd(&hci_le_set_scan_enable, hci_stack->le_scanning_enabled, 0);
3193             return;
3194         }
3195         if (hci_stack->le_scan_type != 0xff){
3196             // defaults: active scanning, accept all advertisement packets
3197             int scan_type = hci_stack->le_scan_type;
3198             hci_stack->le_scan_type = 0xff;
3199             hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->le_own_addr_type, 0);
3200             return;
3201         }
3202 #endif
3203 #ifdef ENABLE_LE_PERIPHERAL
3204         // le advertisement control
3205         if (hci_stack->le_advertisements_todo){
3206             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
3207         }
3208         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
3209             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
3210             hci_send_cmd(&hci_le_set_advertise_enable, 0);
3211             return;
3212         }
3213         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
3214             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3215             hci_send_cmd(&hci_le_set_advertising_parameters,
3216                  hci_stack->le_advertisements_interval_min,
3217                  hci_stack->le_advertisements_interval_max,
3218                  hci_stack->le_advertisements_type,
3219                  hci_stack->le_own_addr_type,
3220                  hci_stack->le_advertisements_direct_address_type,
3221                  hci_stack->le_advertisements_direct_address,
3222                  hci_stack->le_advertisements_channel_map,
3223                  hci_stack->le_advertisements_filter_policy);
3224             return;
3225         }
3226         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3227             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3228             uint8_t adv_data_clean[31];
3229             memset(adv_data_clean, 0, sizeof(adv_data_clean));
3230             memcpy(adv_data_clean, hci_stack->le_advertisements_data, hci_stack->le_advertisements_data_len);
3231             hci_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len);
3232             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3233             return;
3234         }
3235         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3236             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3237             uint8_t scan_data_clean[31];
3238             memset(scan_data_clean, 0, sizeof(scan_data_clean));
3239             memcpy(scan_data_clean, hci_stack->le_scan_response_data, hci_stack->le_scan_response_data_len);
3240             hci_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len);
3241             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, hci_stack->le_scan_response_data);
3242             return;
3243         }
3244         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
3245             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
3246             hci_send_cmd(&hci_le_set_advertise_enable, 1);
3247             return;
3248         }
3249 #endif
3250 
3251 #ifdef ENABLE_LE_CENTRAL
3252         //
3253         // LE Whitelist Management
3254         //
3255 
3256         // check if whitelist needs modification
3257         btstack_linked_list_iterator_t lit;
3258         int modification_pending = 0;
3259         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3260         while (btstack_linked_list_iterator_has_next(&lit)){
3261             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3262             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3263                 modification_pending = 1;
3264                 break;
3265             }
3266         }
3267 
3268         if (modification_pending){
3269             // stop connnecting if modification pending
3270             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
3271                 hci_send_cmd(&hci_le_create_connection_cancel);
3272                 return;
3273             }
3274 
3275             // add/remove entries
3276             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3277             while (btstack_linked_list_iterator_has_next(&lit)){
3278                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3279                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
3280                     entry->state = LE_WHITELIST_ON_CONTROLLER;
3281                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3282                     return;
3283 
3284                 }
3285                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
3286                     bd_addr_t address;
3287                     bd_addr_type_t address_type = entry->address_type;
3288                     memcpy(address, entry->address, 6);
3289                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3290                     btstack_memory_whitelist_entry_free(entry);
3291                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
3292                     return;
3293                 }
3294             }
3295         }
3296 
3297         // start connecting
3298         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
3299             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
3300             bd_addr_t null_addr;
3301             memset(null_addr, 0, 6);
3302             hci_send_cmd(&hci_le_create_connection,
3303                 hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
3304                 hci_stack->le_connection_scan_window,    // scan interval: 30 ms
3305                  1,         // use whitelist
3306                  0,         // peer address type
3307                  null_addr, // peer bd addr
3308                  hci_stack->le_own_addr_type, // our addr type:
3309                  hci_stack->le_connection_interval_min,    // conn interval min
3310                  hci_stack->le_connection_interval_max,    // conn interval max
3311                  hci_stack->le_connection_latency,         // conn latency
3312                  hci_stack->le_supervision_timeout,        // conn latency
3313                  hci_stack->le_minimum_ce_length,          // min ce length
3314                  hci_stack->le_maximum_ce_length           // max ce length
3315                 );
3316             return;
3317         }
3318 #endif
3319     }
3320 #endif
3321 
3322     // send pending HCI commands
3323     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3324         hci_connection_t * connection = (hci_connection_t *) it;
3325 
3326         switch(connection->state){
3327             case SEND_CREATE_CONNECTION:
3328                 switch(connection->address_type){
3329 #ifdef ENABLE_CLASSIC
3330                     case BD_ADDR_TYPE_CLASSIC:
3331                         log_info("sending hci_create_connection");
3332                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
3333                         break;
3334 #endif
3335                     default:
3336 #ifdef ENABLE_BLE
3337 #ifdef ENABLE_LE_CENTRAL
3338                         // track outgoing connection
3339                         hci_stack->outgoing_addr_type = connection->address_type;
3340                         memcpy(hci_stack->outgoing_addr, connection->address, 6);
3341                         log_info("sending hci_le_create_connection");
3342                         hci_send_cmd(&hci_le_create_connection,
3343                              hci_stack->le_connection_scan_interval,    // conn scan interval
3344                              hci_stack->le_connection_scan_window,      // conn scan windows
3345                              0,         // don't use whitelist
3346                              connection->address_type, // peer address type
3347                              connection->address,      // peer bd addr
3348                              hci_stack->le_own_addr_type, // our addr type:
3349                              hci_stack->le_connection_interval_min,    // conn interval min
3350                              hci_stack->le_connection_interval_max,    // conn interval max
3351                              hci_stack->le_connection_latency,         // conn latency
3352                              hci_stack->le_supervision_timeout,        // conn latency
3353                              hci_stack->le_minimum_ce_length,          // min ce length
3354                              hci_stack->le_maximum_ce_length          // max ce length
3355                              );
3356                         connection->state = SENT_CREATE_CONNECTION;
3357 #endif
3358 #endif
3359                         break;
3360                 }
3361                 return;
3362 
3363 #ifdef ENABLE_CLASSIC
3364             case RECEIVED_CONNECTION_REQUEST:
3365                 connection->role  = HCI_ROLE_SLAVE;
3366                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
3367                     log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
3368                     connection->state = ACCEPTED_CONNECTION_REQUEST;
3369                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
3370                 }
3371                 return;
3372 #endif
3373 
3374 #ifdef ENABLE_BLE
3375 #ifdef ENABLE_LE_CENTRAL
3376             case SEND_CANCEL_CONNECTION:
3377                 connection->state = SENT_CANCEL_CONNECTION;
3378                 hci_send_cmd(&hci_le_create_connection_cancel);
3379                 return;
3380 #endif
3381 #endif
3382             case SEND_DISCONNECT:
3383                 connection->state = SENT_DISCONNECT;
3384                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
3385                 return;
3386 
3387             default:
3388                 break;
3389         }
3390 
3391         // no further commands if connection is about to get shut down
3392         if (connection->state == SENT_DISCONNECT) continue;
3393 
3394 #ifdef ENABLE_CLASSIC
3395         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
3396             log_info("responding to link key request");
3397             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
3398             link_key_t link_key;
3399             link_key_type_t link_key_type;
3400             if ( hci_stack->link_key_db
3401               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
3402               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
3403                connection->link_key_type = link_key_type;
3404                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
3405             } else {
3406                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
3407             }
3408             return;
3409         }
3410 
3411         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
3412             log_info("denying to pin request");
3413             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
3414             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
3415             return;
3416         }
3417 
3418         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
3419             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
3420             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
3421             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3422                 // tweak authentication requirements
3423                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3424                 if (connection->bonding_flags & BONDING_DEDICATED){
3425                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3426                 }
3427                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
3428                     authreq |= 1;
3429                 }
3430                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3431             } else {
3432                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3433             }
3434             return;
3435         }
3436 
3437         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3438             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
3439             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3440             return;
3441         }
3442 
3443         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3444             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
3445             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3446             return;
3447         }
3448 
3449         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
3450             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
3451             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3452             return;
3453         }
3454 
3455         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3456             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
3457             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
3458             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
3459             return;
3460         }
3461 
3462         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
3463             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3464             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3465             return;
3466         }
3467 
3468         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3469             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3470             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3471             return;
3472         }
3473 #endif
3474 
3475         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
3476             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
3477             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
3478             return;
3479         }
3480 
3481 #ifdef ENABLE_CLASSIC
3482         uint16_t sniff_min_interval;
3483         switch (connection->sniff_min_interval){
3484             case 0:
3485                 break;
3486             case 0xffff:
3487                 connection->sniff_min_interval = 0;
3488                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
3489                 return;
3490             default:
3491                 sniff_min_interval = connection->sniff_min_interval;
3492                 connection->sniff_min_interval = 0;
3493                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
3494                 return;
3495         }
3496 #endif
3497 
3498 #ifdef ENABLE_BLE
3499         switch (connection->le_con_parameter_update_state){
3500             // response to L2CAP CON PARAMETER UPDATE REQUEST
3501             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
3502                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3503                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
3504                     connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3505                     0x0000, 0xffff);
3506                 return;
3507             case CON_PARAMETER_UPDATE_REPLY:
3508                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3509                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
3510                     connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3511                     0x0000, 0xffff);
3512                 return;
3513             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
3514                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3515                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
3516                 return;
3517             default:
3518                 break;
3519         }
3520         if (connection->le_phy_update_all_phys != 0xff){
3521             uint8_t all_phys = connection->le_phy_update_all_phys;
3522             connection->le_phy_update_all_phys = 0xff;
3523             hci_send_cmd(&hci_le_set_phy, connection->con_handle, all_phys, connection->le_phy_update_tx_phys, connection->le_phy_update_rx_phys, connection->le_phy_update_phy_options);
3524             return;
3525         }
3526 #endif
3527     }
3528 
3529     hci_connection_t * connection;
3530     switch (hci_stack->state){
3531         case HCI_STATE_INITIALIZING:
3532             hci_initializing_run();
3533             break;
3534 
3535         case HCI_STATE_HALTING:
3536 
3537             log_info("HCI_STATE_HALTING");
3538 
3539             // free whitelist entries
3540 #ifdef ENABLE_BLE
3541 #ifdef ENABLE_LE_CENTRAL
3542             {
3543                 btstack_linked_list_iterator_t lit;
3544                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3545                 while (btstack_linked_list_iterator_has_next(&lit)){
3546                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3547                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3548                     btstack_memory_whitelist_entry_free(entry);
3549                 }
3550             }
3551 #endif
3552 #endif
3553             // close all open connections
3554             connection =  (hci_connection_t *) hci_stack->connections;
3555             if (connection){
3556                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
3557                 if (!hci_can_send_command_packet_now()) return;
3558 
3559                 // check state
3560                 if (connection->state == SENT_DISCONNECT) return;
3561                 connection->state = SENT_DISCONNECT;
3562 
3563                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
3564 
3565                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
3566                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
3567 
3568                 // ... which would be ignored anyway as we shutdown (free) the connection now
3569                 hci_shutdown_connection(connection);
3570 
3571                 // finally, send the disconnect command
3572                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
3573                 return;
3574             }
3575             log_info("HCI_STATE_HALTING, calling off");
3576 
3577             // switch mode
3578             hci_power_control_off();
3579 
3580             log_info("HCI_STATE_HALTING, emitting state");
3581             hci_emit_state();
3582             log_info("HCI_STATE_HALTING, done");
3583             break;
3584 
3585         case HCI_STATE_FALLING_ASLEEP:
3586             switch(hci_stack->substate) {
3587                 case HCI_FALLING_ASLEEP_DISCONNECT:
3588                     log_info("HCI_STATE_FALLING_ASLEEP");
3589                     // close all open connections
3590                     connection =  (hci_connection_t *) hci_stack->connections;
3591 
3592 #ifdef HAVE_PLATFORM_IPHONE_OS
3593                     // don't close connections, if H4 supports power management
3594                     if (btstack_control_iphone_power_management_enabled()){
3595                         connection = NULL;
3596                     }
3597 #endif
3598                     if (connection){
3599 
3600                         // send disconnect
3601                         if (!hci_can_send_command_packet_now()) return;
3602 
3603                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3604                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3605 
3606                         // send disconnected event right away - causes higher layer connections to get closed, too.
3607                         hci_shutdown_connection(connection);
3608                         return;
3609                     }
3610 
3611                     if (hci_classic_supported()){
3612                         // disable page and inquiry scan
3613                         if (!hci_can_send_command_packet_now()) return;
3614 
3615                         log_info("HCI_STATE_HALTING, disabling inq scans");
3616                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3617 
3618                         // continue in next sub state
3619                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3620                         break;
3621                     }
3622                     // no break - fall through for ble-only chips
3623 
3624                 case HCI_FALLING_ASLEEP_COMPLETE:
3625                     log_info("HCI_STATE_HALTING, calling sleep");
3626 #ifdef HAVE_PLATFORM_IPHONE_OS
3627                     // don't actually go to sleep, if H4 supports power management
3628                     if (btstack_control_iphone_power_management_enabled()){
3629                         // SLEEP MODE reached
3630                         hci_stack->state = HCI_STATE_SLEEPING;
3631                         hci_emit_state();
3632                         break;
3633                     }
3634 #endif
3635                     // switch mode
3636                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3637                     hci_emit_state();
3638                     break;
3639 
3640                 default:
3641                     break;
3642             }
3643             break;
3644 
3645         default:
3646             break;
3647     }
3648 }
3649 
3650 int hci_send_cmd_packet(uint8_t *packet, int size){
3651     // house-keeping
3652 
3653     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3654         hci_stack->loopback_mode = packet[3];
3655     }
3656 
3657 #ifdef ENABLE_CLASSIC
3658     bd_addr_t addr;
3659     hci_connection_t * conn;
3660 
3661     // create_connection?
3662     if (IS_COMMAND(packet, hci_create_connection)){
3663         reverse_bd_addr(&packet[3], addr);
3664         log_info("Create_connection to %s", bd_addr_to_str(addr));
3665 
3666         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3667         if (!conn){
3668             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3669             if (!conn){
3670                 // notify client that alloc failed
3671                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3672                 return -1; // packet not sent to controller
3673             }
3674             conn->state = SEND_CREATE_CONNECTION;
3675         }
3676         log_info("conn state %u", conn->state);
3677         switch (conn->state){
3678             // if connection active exists
3679             case OPEN:
3680                 // and OPEN, emit connection complete command
3681                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3682                 return -1; // packet not sent to controller
3683             case SEND_CREATE_CONNECTION:
3684                 // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
3685                 break;
3686             default:
3687                 // otherwise, just ignore as it is already in the open process
3688                 return -1; // packet not sent to controller
3689         }
3690         conn->state = SENT_CREATE_CONNECTION;
3691 
3692         // track outgoing connection
3693         hci_stack->outgoing_addr_type = BD_ADDR_TYPE_CLASSIC;
3694         memcpy(hci_stack->outgoing_addr, addr, 6);
3695     }
3696 
3697     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3698         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3699     }
3700     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3701         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3702     }
3703 
3704     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3705         if (hci_stack->link_key_db){
3706             reverse_bd_addr(&packet[3], addr);
3707             hci_stack->link_key_db->delete_link_key(addr);
3708         }
3709     }
3710 
3711     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3712     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3713         reverse_bd_addr(&packet[3], addr);
3714         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3715         if (conn){
3716             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3717         }
3718     }
3719 
3720     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3721     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3722     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3723     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3724         reverse_bd_addr(&packet[3], addr);
3725         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3726         if (conn){
3727             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3728         }
3729     }
3730 
3731 #ifdef ENABLE_SCO_OVER_HCI
3732     // setup_synchronous_connection? Voice setting at offset 22
3733     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3734         // TODO: compare to current setting if sco connection already active
3735         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3736     }
3737     // accept_synchronus_connection? Voice setting at offset 18
3738     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3739         // TODO: compare to current setting if sco connection already active
3740         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3741     }
3742 #endif
3743 #endif
3744 
3745 #ifdef ENABLE_BLE
3746 #ifdef ENABLE_LE_PERIPHERAL
3747     if (IS_COMMAND(packet, hci_le_set_random_address)){
3748         hci_stack->le_random_address_set = 1;
3749         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3750     }
3751     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3752         hci_stack->le_advertisements_active = packet[3];
3753     }
3754 #endif
3755 #ifdef ENABLE_LE_CENTRAL
3756     if (IS_COMMAND(packet, hci_le_create_connection)){
3757         // white list used?
3758         uint8_t initiator_filter_policy = packet[7];
3759         switch (initiator_filter_policy){
3760             case 0:
3761                 // whitelist not used
3762                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3763                 break;
3764             case 1:
3765                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3766                 break;
3767             default:
3768                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3769                 break;
3770         }
3771     }
3772     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3773         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3774     }
3775 #endif
3776 #endif
3777 
3778     hci_stack->num_cmd_packets--;
3779 
3780     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3781     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3782 }
3783 
3784 // disconnect because of security block
3785 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3786     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3787     if (!connection) return;
3788     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3789 }
3790 
3791 
3792 // Configure Secure Simple Pairing
3793 
3794 #ifdef ENABLE_CLASSIC
3795 
3796 // enable will enable SSP during init
3797 void gap_ssp_set_enable(int enable){
3798     hci_stack->ssp_enable = enable;
3799 }
3800 
3801 static int hci_local_ssp_activated(void){
3802     return gap_ssp_supported() && hci_stack->ssp_enable;
3803 }
3804 
3805 // if set, BTstack will respond to io capability request using authentication requirement
3806 void gap_ssp_set_io_capability(int io_capability){
3807     hci_stack->ssp_io_capability = io_capability;
3808 }
3809 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3810     hci_stack->ssp_authentication_requirement = authentication_requirement;
3811 }
3812 
3813 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3814 void gap_ssp_set_auto_accept(int auto_accept){
3815     hci_stack->ssp_auto_accept = auto_accept;
3816 }
3817 #endif
3818 
3819 // va_list part of hci_send_cmd
3820 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3821     if (!hci_can_send_command_packet_now()){
3822         log_error("hci_send_cmd called but cannot send packet now");
3823         return 0;
3824     }
3825 
3826     // for HCI INITIALIZATION
3827     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3828     hci_stack->last_cmd_opcode = cmd->opcode;
3829 
3830     hci_reserve_packet_buffer();
3831     uint8_t * packet = hci_stack->hci_packet_buffer;
3832     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3833     int err = hci_send_cmd_packet(packet, size);
3834 
3835     // release packet buffer for synchronous transport implementations
3836     if (hci_transport_synchronous()){
3837         hci_release_packet_buffer();
3838         hci_emit_transport_packet_sent();
3839     }
3840 
3841     return err;
3842 }
3843 
3844 /**
3845  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3846  */
3847 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3848     va_list argptr;
3849     va_start(argptr, cmd);
3850     int res = hci_send_cmd_va_arg(cmd, argptr);
3851     va_end(argptr);
3852     return res;
3853 }
3854 
3855 // Create various non-HCI events.
3856 // TODO: generalize, use table similar to hci_create_command
3857 
3858 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3859     // dump packet
3860     if (dump) {
3861         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3862     }
3863 
3864     // dispatch to all event handlers
3865     btstack_linked_list_iterator_t it;
3866     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3867     while (btstack_linked_list_iterator_has_next(&it)){
3868         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3869         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3870     }
3871 }
3872 
3873 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3874     if (!hci_stack->acl_packet_handler) return;
3875     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3876 }
3877 
3878 #ifdef ENABLE_CLASSIC
3879 static void hci_notify_if_sco_can_send_now(void){
3880     // notify SCO sender if waiting
3881     if (!hci_stack->sco_waiting_for_can_send_now) return;
3882     if (hci_can_send_sco_packet_now()){
3883         hci_stack->sco_waiting_for_can_send_now = 0;
3884         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3885         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3886         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3887     }
3888 }
3889 
3890 // parsing end emitting has been merged to reduce code size
3891 static void gap_inquiry_explode(uint8_t * packet){
3892     uint8_t event[19+GAP_INQUIRY_MAX_NAME_LEN];
3893 
3894     uint8_t * eir_data;
3895     ad_context_t context;
3896     const uint8_t * name;
3897     uint8_t         name_len;
3898 
3899     int event_type = hci_event_packet_get_type(packet);
3900     int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1;    // 2 for old event, 1 otherwise
3901     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
3902 
3903     // event[1] is set at the end
3904     int i;
3905     for (i=0; i<num_responses;i++){
3906         memset(event, 0, sizeof(event));
3907         event[0] = GAP_EVENT_INQUIRY_RESULT;
3908         uint8_t event_size = 18;    // if name is not set by EIR
3909 
3910         memcpy(&event[2],  &packet[3 +                                             i*6], 6); // bd_addr
3911         event[8] =          packet[3 + num_responses*(6)                         + i*1];     // page_scan_repetition_mode
3912         memcpy(&event[9],  &packet[3 + num_responses*(6+1+num_reserved_fields)   + i*3], 3); // class of device
3913         memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset
3914 
3915         switch (event_type){
3916             case HCI_EVENT_INQUIRY_RESULT:
3917                 // 14,15,16,17 = 0, size 18
3918                 break;
3919             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3920                 event[14] = 1;
3921                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3922                 // 16,17 = 0, size 18
3923                 break;
3924             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3925                 event[14] = 1;
3926                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3927                 // for EIR packets, there is only one reponse in it
3928                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
3929                 name = NULL;
3930                 // EIR data is 240 bytes in EIR event
3931                 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
3932                     uint8_t data_type    = ad_iterator_get_data_type(&context);
3933                     uint8_t data_size    = ad_iterator_get_data_len(&context);
3934                     const uint8_t * data = ad_iterator_get_data(&context);
3935                     // Prefer Complete Local Name over Shortend Local Name
3936                     switch (data_type){
3937                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
3938                             if (name) continue;
3939                             /* explicit fall-through */
3940                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
3941                             name = data;
3942                             name_len = data_size;
3943                             break;
3944                         default:
3945                             break;
3946                     }
3947                 }
3948                 if (name){
3949                     event[16] = 1;
3950                     // truncate name if needed
3951                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
3952                     event[17] = len;
3953                     memcpy(&event[18], name, len);
3954                     event_size += len;
3955                 }
3956                 break;
3957         }
3958         event[1] = event_size - 2;
3959         hci_emit_event(event, event_size, 1);
3960     }
3961 }
3962 #endif
3963 
3964 void hci_emit_state(void){
3965     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3966     uint8_t event[3];
3967     event[0] = BTSTACK_EVENT_STATE;
3968     event[1] = sizeof(event) - 2;
3969     event[2] = hci_stack->state;
3970     hci_emit_event(event, sizeof(event), 1);
3971 }
3972 
3973 #ifdef ENABLE_CLASSIC
3974 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3975     uint8_t event[13];
3976     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3977     event[1] = sizeof(event) - 2;
3978     event[2] = status;
3979     little_endian_store_16(event, 3, con_handle);
3980     reverse_bd_addr(address, &event[5]);
3981     event[11] = 1; // ACL connection
3982     event[12] = 0; // encryption disabled
3983     hci_emit_event(event, sizeof(event), 1);
3984 }
3985 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3986     if (disable_l2cap_timeouts) return;
3987     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3988     uint8_t event[4];
3989     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3990     event[1] = sizeof(event) - 2;
3991     little_endian_store_16(event, 2, conn->con_handle);
3992     hci_emit_event(event, sizeof(event), 1);
3993 }
3994 #endif
3995 
3996 #ifdef ENABLE_BLE
3997 #ifdef ENABLE_LE_CENTRAL
3998 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3999     uint8_t event[21];
4000     event[0] = HCI_EVENT_LE_META;
4001     event[1] = sizeof(event) - 2;
4002     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
4003     event[3] = status;
4004     little_endian_store_16(event, 4, con_handle);
4005     event[6] = 0; // TODO: role
4006     event[7] = address_type;
4007     reverse_bd_addr(address, &event[8]);
4008     little_endian_store_16(event, 14, 0); // interval
4009     little_endian_store_16(event, 16, 0); // latency
4010     little_endian_store_16(event, 18, 0); // supervision timeout
4011     event[20] = 0; // master clock accuracy
4012     hci_emit_event(event, sizeof(event), 1);
4013 }
4014 #endif
4015 #endif
4016 
4017 static void hci_emit_transport_packet_sent(void){
4018     // notify upper stack that it might be possible to send again
4019     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
4020     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
4021 }
4022 
4023 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
4024     uint8_t event[6];
4025     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
4026     event[1] = sizeof(event) - 2;
4027     event[2] = 0; // status = OK
4028     little_endian_store_16(event, 3, con_handle);
4029     event[5] = reason;
4030     hci_emit_event(event, sizeof(event), 1);
4031 }
4032 
4033 static void hci_emit_nr_connections_changed(void){
4034     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
4035     uint8_t event[3];
4036     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
4037     event[1] = sizeof(event) - 2;
4038     event[2] = nr_hci_connections();
4039     hci_emit_event(event, sizeof(event), 1);
4040 }
4041 
4042 static void hci_emit_hci_open_failed(void){
4043     log_info("BTSTACK_EVENT_POWERON_FAILED");
4044     uint8_t event[2];
4045     event[0] = BTSTACK_EVENT_POWERON_FAILED;
4046     event[1] = sizeof(event) - 2;
4047     hci_emit_event(event, sizeof(event), 1);
4048 }
4049 
4050 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
4051     log_info("hci_emit_dedicated_bonding_result %u ", status);
4052     uint8_t event[9];
4053     int pos = 0;
4054     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
4055     event[pos++] = sizeof(event) - 2;
4056     event[pos++] = status;
4057     reverse_bd_addr(address, &event[pos]);
4058     hci_emit_event(event, sizeof(event), 1);
4059 }
4060 
4061 
4062 #ifdef ENABLE_CLASSIC
4063 
4064 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
4065     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
4066     uint8_t event[5];
4067     int pos = 0;
4068     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
4069     event[pos++] = sizeof(event) - 2;
4070     little_endian_store_16(event, 2, con_handle);
4071     pos += 2;
4072     event[pos++] = level;
4073     hci_emit_event(event, sizeof(event), 1);
4074 }
4075 
4076 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
4077     if (!connection) return LEVEL_0;
4078     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
4079     return gap_security_level_for_link_key_type(connection->link_key_type);
4080 }
4081 
4082 static void hci_emit_discoverable_enabled(uint8_t enabled){
4083     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
4084     uint8_t event[3];
4085     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
4086     event[1] = sizeof(event) - 2;
4087     event[2] = enabled;
4088     hci_emit_event(event, sizeof(event), 1);
4089 }
4090 
4091 #ifdef ENABLE_CLASSIC
4092 // query if remote side supports eSCO
4093 int hci_remote_esco_supported(hci_con_handle_t con_handle){
4094     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4095     if (!connection) return 0;
4096     return connection->remote_supported_feature_eSCO;
4097 }
4098 
4099 // query if remote side supports SSP
4100 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
4101     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4102     if (!connection) return 0;
4103     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
4104 }
4105 
4106 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
4107     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
4108 }
4109 #endif
4110 
4111 // GAP API
4112 /**
4113  * @bbrief enable/disable bonding. default is enabled
4114  * @praram enabled
4115  */
4116 void gap_set_bondable_mode(int enable){
4117     hci_stack->bondable = enable ? 1 : 0;
4118 }
4119 /**
4120  * @brief Get bondable mode.
4121  * @return 1 if bondable
4122  */
4123 int gap_get_bondable_mode(void){
4124     return hci_stack->bondable;
4125 }
4126 
4127 /**
4128  * @brief map link keys to security levels
4129  */
4130 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
4131     switch (link_key_type){
4132         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
4133             return LEVEL_4;
4134         case COMBINATION_KEY:
4135         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
4136             return LEVEL_3;
4137         default:
4138             return LEVEL_2;
4139     }
4140 }
4141 
4142 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
4143     log_info("gap_mitm_protection_required_for_security_level %u", level);
4144     return level > LEVEL_2;
4145 }
4146 
4147 /**
4148  * @brief get current security level
4149  */
4150 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
4151     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4152     if (!connection) return LEVEL_0;
4153     return gap_security_level_for_connection(connection);
4154 }
4155 
4156 /**
4157  * @brief request connection to device to
4158  * @result GAP_AUTHENTICATION_RESULT
4159  */
4160 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
4161     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4162     if (!connection){
4163         hci_emit_security_level(con_handle, LEVEL_0);
4164         return;
4165     }
4166     gap_security_level_t current_level = gap_security_level(con_handle);
4167     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
4168         requested_level, connection->requested_security_level, current_level);
4169 
4170     // assumption: earlier requested security higher than current level => security request is active
4171     if (current_level < connection->requested_security_level){
4172         if (connection->requested_security_level < requested_level){
4173             // increase requested level as new level is higher
4174 
4175             // TODO: handle re-authentication when done
4176 
4177             connection->requested_security_level = requested_level;
4178         }
4179         return;
4180     }
4181 
4182     // no request active, notify if security sufficient
4183     if (requested_level <= current_level){
4184         hci_emit_security_level(con_handle, current_level);
4185         return;
4186     }
4187 
4188     // start pairing to increase security level
4189     connection->requested_security_level = requested_level;
4190 
4191 #if 0
4192     // sending encryption request without a link key results in an error.
4193     // TODO: figure out how to use it properly
4194 
4195     // would enabling ecnryption suffice (>= LEVEL_2)?
4196     if (hci_stack->link_key_db){
4197         link_key_type_t link_key_type;
4198         link_key_t      link_key;
4199         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
4200             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
4201                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4202                 return;
4203             }
4204         }
4205     }
4206 #endif
4207 
4208     // start to authenticate connection
4209     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
4210     hci_run();
4211 }
4212 
4213 /**
4214  * @brief start dedicated bonding with device. disconnect after bonding
4215  * @param device
4216  * @param request MITM protection
4217  * @result GAP_DEDICATED_BONDING_COMPLETE
4218  */
4219 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
4220 
4221     // create connection state machine
4222     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
4223 
4224     if (!connection){
4225         return BTSTACK_MEMORY_ALLOC_FAILED;
4226     }
4227 
4228     // delete linkn key
4229     gap_drop_link_key_for_bd_addr(device);
4230 
4231     // configure LEVEL_2/3, dedicated bonding
4232     connection->state = SEND_CREATE_CONNECTION;
4233     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
4234     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
4235     connection->bonding_flags = BONDING_DEDICATED;
4236 
4237     // wait for GAP Security Result and send GAP Dedicated Bonding complete
4238 
4239     // handle: connnection failure (connection complete != ok)
4240     // handle: authentication failure
4241     // handle: disconnect on done
4242 
4243     hci_run();
4244 
4245     return 0;
4246 }
4247 #endif
4248 
4249 void gap_set_local_name(const char * local_name){
4250     hci_stack->local_name = local_name;
4251 }
4252 
4253 
4254 #ifdef ENABLE_BLE
4255 
4256 #ifdef ENABLE_LE_CENTRAL
4257 void gap_start_scan(void){
4258     hci_stack->le_scanning_enabled = 1;
4259     hci_run();
4260 }
4261 
4262 void gap_stop_scan(void){
4263     hci_stack->le_scanning_enabled = 0;
4264     hci_run();
4265 }
4266 
4267 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
4268     hci_stack->le_scan_type     = scan_type;
4269     hci_stack->le_scan_interval = scan_interval;
4270     hci_stack->le_scan_window   = scan_window;
4271     hci_run();
4272 }
4273 
4274 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
4275     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4276     if (!conn){
4277         log_info("gap_connect: no connection exists yet, creating context");
4278         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
4279         if (!conn){
4280             // notify client that alloc failed
4281             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4282             log_info("gap_connect: failed to alloc hci_connection_t");
4283             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
4284         }
4285         conn->state = SEND_CREATE_CONNECTION;
4286         log_info("gap_connect: send create connection next");
4287         hci_run();
4288         return 0;
4289     }
4290 
4291     if (!hci_is_le_connection(conn) ||
4292         conn->state == SEND_CREATE_CONNECTION ||
4293         conn->state == SENT_CREATE_CONNECTION) {
4294         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
4295         log_error("gap_connect: classic connection or connect is already being created");
4296         return GATT_CLIENT_IN_WRONG_STATE;
4297     }
4298 
4299     log_info("gap_connect: context exists with state %u", conn->state);
4300     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
4301     hci_run();
4302     return 0;
4303 }
4304 
4305 // @assumption: only a single outgoing LE Connection exists
4306 static hci_connection_t * gap_get_outgoing_connection(void){
4307     btstack_linked_item_t *it;
4308     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4309         hci_connection_t * conn = (hci_connection_t *) it;
4310         if (!hci_is_le_connection(conn)) continue;
4311         switch (conn->state){
4312             case SEND_CREATE_CONNECTION:
4313             case SENT_CREATE_CONNECTION:
4314             case SENT_CANCEL_CONNECTION:
4315                 return conn;
4316             default:
4317                 break;
4318         };
4319     }
4320     return NULL;
4321 }
4322 
4323 uint8_t gap_connect_cancel(void){
4324     hci_connection_t * conn = gap_get_outgoing_connection();
4325     if (!conn) return 0;
4326     switch (conn->state){
4327         case SEND_CREATE_CONNECTION:
4328             // skip sending create connection and emit event instead
4329             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
4330             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
4331             btstack_memory_hci_connection_free( conn );
4332             break;
4333         case SENT_CREATE_CONNECTION:
4334             // request to send cancel connection
4335             conn->state = SEND_CANCEL_CONNECTION;
4336             hci_run();
4337             break;
4338         default:
4339             break;
4340     }
4341     return 0;
4342 }
4343 #endif
4344 
4345 #ifdef ENABLE_LE_CENTRAL
4346 /**
4347  * @brief Set connection parameters for outgoing connections
4348  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
4349  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
4350  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
4351  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
4352  * @param conn_latency, default: 4
4353  * @param supervision_timeout (unit: 10ms), default: 720 ms
4354  * @param min_ce_length (unit: 0.625ms), default: 10 ms
4355  * @param max_ce_length (unit: 0.625ms), default: 30 ms
4356  */
4357 
4358 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
4359     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
4360     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
4361     hci_stack->le_connection_scan_interval = conn_scan_interval;
4362     hci_stack->le_connection_scan_window = conn_scan_window;
4363     hci_stack->le_connection_interval_min = conn_interval_min;
4364     hci_stack->le_connection_interval_max = conn_interval_max;
4365     hci_stack->le_connection_latency = conn_latency;
4366     hci_stack->le_supervision_timeout = supervision_timeout;
4367     hci_stack->le_minimum_ce_length = min_ce_length;
4368     hci_stack->le_maximum_ce_length = max_ce_length;
4369 }
4370 #endif
4371 
4372 /**
4373  * @brief Updates the connection parameters for a given LE connection
4374  * @param handle
4375  * @param conn_interval_min (unit: 1.25ms)
4376  * @param conn_interval_max (unit: 1.25ms)
4377  * @param conn_latency
4378  * @param supervision_timeout (unit: 10ms)
4379  * @returns 0 if ok
4380  */
4381 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4382     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4383     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4384     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4385     connection->le_conn_interval_min = conn_interval_min;
4386     connection->le_conn_interval_max = conn_interval_max;
4387     connection->le_conn_latency = conn_latency;
4388     connection->le_supervision_timeout = supervision_timeout;
4389     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
4390     hci_run();
4391     return 0;
4392 }
4393 
4394 /**
4395  * @brief Request an update of the connection parameter for a given LE connection
4396  * @param handle
4397  * @param conn_interval_min (unit: 1.25ms)
4398  * @param conn_interval_max (unit: 1.25ms)
4399  * @param conn_latency
4400  * @param supervision_timeout (unit: 10ms)
4401  * @returns 0 if ok
4402  */
4403 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4404     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4405     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4406     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4407     connection->le_conn_interval_min = conn_interval_min;
4408     connection->le_conn_interval_max = conn_interval_max;
4409     connection->le_conn_latency = conn_latency;
4410     connection->le_supervision_timeout = supervision_timeout;
4411     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
4412     hci_run();
4413     return 0;
4414 }
4415 
4416 #ifdef ENABLE_LE_PERIPHERAL
4417 
4418 static void gap_advertisments_changed(void){
4419     // disable advertisements before updating adv, scan data, or adv params
4420     if (hci_stack->le_advertisements_active){
4421         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
4422     }
4423     hci_run();
4424 }
4425 
4426 /**
4427  * @brief Set Advertisement Data
4428  * @param advertising_data_length
4429  * @param advertising_data (max 31 octets)
4430  * @note data is not copied, pointer has to stay valid
4431  */
4432 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
4433     hci_stack->le_advertisements_data_len = advertising_data_length;
4434     hci_stack->le_advertisements_data = advertising_data;
4435     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4436     gap_advertisments_changed();
4437 }
4438 
4439 /**
4440  * @brief Set Scan Response Data
4441  * @param advertising_data_length
4442  * @param advertising_data (max 31 octets)
4443  * @note data is not copied, pointer has to stay valid
4444  */
4445 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
4446     hci_stack->le_scan_response_data_len = scan_response_data_length;
4447     hci_stack->le_scan_response_data = scan_response_data;
4448     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4449     gap_advertisments_changed();
4450 }
4451 
4452 /**
4453  * @brief Set Advertisement Parameters
4454  * @param adv_int_min
4455  * @param adv_int_max
4456  * @param adv_type
4457  * @param direct_address_type
4458  * @param direct_address
4459  * @param channel_map
4460  * @param filter_policy
4461  *
4462  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
4463  */
4464  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4465     uint8_t direct_address_typ, bd_addr_t direct_address,
4466     uint8_t channel_map, uint8_t filter_policy) {
4467 
4468     hci_stack->le_advertisements_interval_min = adv_int_min;
4469     hci_stack->le_advertisements_interval_max = adv_int_max;
4470     hci_stack->le_advertisements_type = adv_type;
4471     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
4472     hci_stack->le_advertisements_channel_map = channel_map;
4473     hci_stack->le_advertisements_filter_policy = filter_policy;
4474     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
4475 
4476     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4477     gap_advertisments_changed();
4478  }
4479 
4480 /**
4481  * @brief Enable/Disable Advertisements
4482  * @param enabled
4483  */
4484 void gap_advertisements_enable(int enabled){
4485     hci_stack->le_advertisements_enabled = enabled;
4486     if (enabled && !hci_stack->le_advertisements_active){
4487         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
4488     }
4489     if (!enabled && hci_stack->le_advertisements_active){
4490         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
4491     }
4492     hci_run();
4493 }
4494 
4495 #endif
4496 
4497 void hci_le_set_own_address_type(uint8_t own_address_type){
4498     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
4499     if (own_address_type == hci_stack->le_own_addr_type) return;
4500     hci_stack->le_own_addr_type = own_address_type;
4501 
4502 #ifdef ENABLE_LE_PERIPHERAL
4503     // update advertisement parameters, too
4504     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4505     gap_advertisments_changed();
4506 #endif
4507 #ifdef ENABLE_LE_CENTRAL
4508     // note: we don't update scan parameters or modify ongoing connection attempts
4509 #endif
4510 }
4511 
4512 #endif
4513 
4514 uint8_t gap_disconnect(hci_con_handle_t handle){
4515     hci_connection_t * conn = hci_connection_for_handle(handle);
4516     if (!conn){
4517         hci_emit_disconnection_complete(handle, 0);
4518         return 0;
4519     }
4520     // ignore if already disconnected
4521     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
4522         return 0;
4523     }
4524     conn->state = SEND_DISCONNECT;
4525     hci_run();
4526     return 0;
4527 }
4528 
4529 /**
4530  * @brief Get connection type
4531  * @param con_handle
4532  * @result connection_type
4533  */
4534 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
4535     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4536     if (!conn) return GAP_CONNECTION_INVALID;
4537     switch (conn->address_type){
4538         case BD_ADDR_TYPE_LE_PUBLIC:
4539         case BD_ADDR_TYPE_LE_RANDOM:
4540             return GAP_CONNECTION_LE;
4541         case BD_ADDR_TYPE_SCO:
4542             return GAP_CONNECTION_SCO;
4543         case BD_ADDR_TYPE_CLASSIC:
4544             return GAP_CONNECTION_ACL;
4545         default:
4546             return GAP_CONNECTION_INVALID;
4547     }
4548 }
4549 
4550 #ifdef ENABLE_BLE
4551 
4552 uint8_t gap_le_set_phy(hci_con_handle_t connection_handle, uint8_t all_phys, uint8_t tx_phys, uint8_t rx_phys, uint8_t phy_options){
4553     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4554     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4555 
4556     conn->le_phy_update_all_phys    = all_phys;
4557     conn->le_phy_update_tx_phys     = tx_phys;
4558     conn->le_phy_update_rx_phys     = rx_phys;
4559     conn->le_phy_update_phy_options = phy_options;
4560 
4561     hci_run();
4562 
4563     return 0;
4564 }
4565 
4566 #ifdef ENABLE_LE_CENTRAL
4567 /**
4568  * @brief Auto Connection Establishment - Start Connecting to device
4569  * @param address_typ
4570  * @param address
4571  * @returns 0 if ok
4572  */
4573 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
4574     // check capacity
4575     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
4576     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
4577     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
4578     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
4579     entry->address_type = address_type;
4580     memcpy(entry->address, address, 6);
4581     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4582     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
4583     hci_run();
4584     return 0;
4585 }
4586 
4587 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
4588     btstack_linked_list_iterator_t it;
4589     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4590     while (btstack_linked_list_iterator_has_next(&it)){
4591         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4592         if (entry->address_type != address_type) continue;
4593         if (memcmp(entry->address, address, 6) != 0) continue;
4594         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4595             // remove from controller if already present
4596             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4597             continue;
4598         }
4599         // direclty remove entry from whitelist
4600         btstack_linked_list_iterator_remove(&it);
4601         btstack_memory_whitelist_entry_free(entry);
4602     }
4603 }
4604 
4605 /**
4606  * @brief Auto Connection Establishment - Stop Connecting to device
4607  * @param address_typ
4608  * @param address
4609  * @returns 0 if ok
4610  */
4611 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
4612     hci_remove_from_whitelist(address_type, address);
4613     hci_run();
4614     return 0;
4615 }
4616 
4617 /**
4618  * @brief Auto Connection Establishment - Stop everything
4619  * @note  Convenience function to stop all active auto connection attempts
4620  */
4621 void gap_auto_connection_stop_all(void){
4622     btstack_linked_list_iterator_t it;
4623     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4624     while (btstack_linked_list_iterator_has_next(&it)){
4625         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4626         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4627             // remove from controller if already present
4628             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4629             continue;
4630         }
4631         // directly remove entry from whitelist
4632         btstack_linked_list_iterator_remove(&it);
4633         btstack_memory_whitelist_entry_free(entry);
4634     }
4635     hci_run();
4636 }
4637 
4638 uint16_t gap_le_connection_interval(hci_con_handle_t connection_handle){
4639     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4640     if (!conn) return 0;
4641     return conn->le_connection_interval;
4642 }
4643 #endif
4644 #endif
4645 
4646 #ifdef ENABLE_CLASSIC
4647 /**
4648  * @brief Set Extended Inquiry Response data
4649  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
4650  * @note has to be done before stack starts up
4651  */
4652 void gap_set_extended_inquiry_response(const uint8_t * data){
4653     hci_stack->eir_data = data;
4654 }
4655 
4656 /**
4657  * @brief Start GAP Classic Inquiry
4658  * @param duration in 1.28s units
4659  * @return 0 if ok
4660  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
4661  */
4662 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
4663     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
4664     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4665     if (duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN || duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX){
4666         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
4667     }
4668     hci_stack->inquiry_state = duration_in_1280ms_units;
4669     hci_run();
4670     return 0;
4671 }
4672 
4673 /**
4674  * @brief Stop GAP Classic Inquiry
4675  * @returns 0 if ok
4676  */
4677 int gap_inquiry_stop(void){
4678     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX) {
4679         // emit inquiry complete event, before it even started
4680         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
4681         hci_emit_event(event, sizeof(event), 1);
4682         return 0;
4683     }
4684     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
4685     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
4686     hci_run();
4687     return 0;
4688 }
4689 
4690 
4691 /**
4692  * @brief Remote Name Request
4693  * @param addr
4694  * @param page_scan_repetition_mode
4695  * @param clock_offset only used when bit 15 is set
4696  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
4697  */
4698 int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
4699     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4700     memcpy(hci_stack->remote_name_addr, addr, 6);
4701     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
4702     hci_stack->remote_name_clock_offset = clock_offset;
4703     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
4704     hci_run();
4705     return 0;
4706 }
4707 
4708 static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){
4709     hci_stack->gap_pairing_state = state;
4710     memcpy(hci_stack->gap_pairing_addr, addr, 6);
4711     hci_run();
4712     return 0;
4713 }
4714 
4715 /**
4716  * @brief Legacy Pairing Pin Code Response
4717  * @param addr
4718  * @param pin
4719  * @return 0 if ok
4720  */
4721 int gap_pin_code_response(bd_addr_t addr, const char * pin){
4722     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4723     hci_stack->gap_pairing_input.gap_pairing_pin = pin;
4724     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
4725 }
4726 
4727 /**
4728  * @brief Abort Legacy Pairing
4729  * @param addr
4730  * @param pin
4731  * @return 0 if ok
4732  */
4733 int gap_pin_code_negative(bd_addr_t addr){
4734     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4735     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
4736 }
4737 
4738 /**
4739  * @brief SSP Passkey Response
4740  * @param addr
4741  * @param passkey
4742  * @return 0 if ok
4743  */
4744 int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){
4745     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4746     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
4747     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
4748 }
4749 
4750 /**
4751  * @brief Abort SSP Passkey Entry/Pairing
4752  * @param addr
4753  * @param pin
4754  * @return 0 if ok
4755  */
4756 int gap_ssp_passkey_negative(bd_addr_t addr){
4757     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4758     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
4759 }
4760 
4761 /**
4762  * @brief Accept SSP Numeric Comparison
4763  * @param addr
4764  * @param passkey
4765  * @return 0 if ok
4766  */
4767 int gap_ssp_confirmation_response(bd_addr_t addr){
4768     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4769     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
4770 }
4771 
4772 /**
4773  * @brief Abort SSP Numeric Comparison/Pairing
4774  * @param addr
4775  * @param pin
4776  * @return 0 if ok
4777  */
4778 int gap_ssp_confirmation_negative(bd_addr_t addr){
4779     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4780     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
4781 }
4782 
4783 /**
4784  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
4785  * @param inquiry_mode see bluetooth_defines.h
4786  */
4787 void hci_set_inquiry_mode(inquiry_mode_t mode){
4788     hci_stack->inquiry_mode = mode;
4789 }
4790 
4791 /**
4792  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
4793  */
4794 void hci_set_sco_voice_setting(uint16_t voice_setting){
4795     hci_stack->sco_voice_setting = voice_setting;
4796 }
4797 
4798 /**
4799  * @brief Get SCO Voice Setting
4800  * @return current voice setting
4801  */
4802 uint16_t hci_get_sco_voice_setting(void){
4803     return hci_stack->sco_voice_setting;
4804 }
4805 
4806 /** @brief Get SCO packet length for current SCO Voice setting
4807  *  @note  Using SCO packets of the exact length is required for USB transfer
4808  *  @return Length of SCO packets in bytes (not audio frames)
4809  */
4810 int hci_get_sco_packet_length(void){
4811     int sco_packet_length = 0;
4812 
4813 #ifdef ENABLE_CLASSIC
4814 #ifdef ENABLE_SCO_OVER_HCI
4815     // see Core Spec for H2 USB Transfer.
4816 
4817     // CVSD requires twice as much bytes
4818     int multiplier = hci_stack->sco_voice_setting & 0x0020 ? 2 : 1;
4819 
4820     // 3 byte SCO header + 24 bytes per connection
4821     sco_packet_length = 3 + 24 * hci_number_sco_connections() * multiplier;
4822 #endif
4823 #endif
4824     return sco_packet_length;
4825 }
4826 
4827 /**
4828 * @brief Sets the master/slave policy
4829 * @param policy (0: attempt to become master, 1: let connecting device decide)
4830 */
4831 void hci_set_master_slave_policy(uint8_t policy){
4832     hci_stack->master_slave_policy = policy;
4833 }
4834 
4835 #endif
4836 
4837 HCI_STATE hci_get_state(void){
4838     return hci_stack->state;
4839 }
4840 
4841 
4842 /**
4843  * @brief Set callback for Bluetooth Hardware Error
4844  */
4845 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
4846     hci_stack->hardware_error_callback = fn;
4847 }
4848 
4849 void hci_disconnect_all(void){
4850     btstack_linked_list_iterator_t it;
4851     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4852     while (btstack_linked_list_iterator_has_next(&it)){
4853         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4854         if (con->state == SENT_DISCONNECT) continue;
4855         con->state = SEND_DISCONNECT;
4856     }
4857     hci_run();
4858 }
4859 
4860 uint16_t hci_get_manufacturer(void){
4861     return hci_stack->manufacturer;
4862 }
4863 
4864 #ifdef ENABLE_BLE
4865 
4866 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4867     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
4868     if (!hci_con) return NULL;
4869     return &hci_con->sm_connection;
4870 }
4871 
4872 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
4873 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
4874 
4875 int gap_encryption_key_size(hci_con_handle_t con_handle){
4876     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4877     if (!sm_conn) return 0;     // wrong connection
4878     if (!sm_conn->sm_connection_encrypted) return 0;
4879     return sm_conn->sm_actual_encryption_key_size;
4880 }
4881 
4882 int gap_authenticated(hci_con_handle_t con_handle){
4883     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4884     if (!sm_conn) return 0;     // wrong connection
4885     if (!sm_conn->sm_connection_encrypted) return 0; // unencrypted connection cannot be authenticated
4886     return sm_conn->sm_connection_authenticated;
4887 }
4888 
4889 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
4890     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4891     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
4892     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
4893     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
4894     return sm_conn->sm_connection_authorization_state;
4895 }
4896 #endif
4897 
4898 #ifdef ENABLE_CLASSIC
4899 uint8_t gap_sniff_mode_enter(hci_con_handle_t con_handle, uint16_t sniff_min_interval, uint16_t sniff_max_interval, uint16_t sniff_attempt, uint16_t sniff_timeout){
4900     hci_connection_t * conn = hci_connection_for_handle(con_handle);
4901     if (!conn) return GAP_CONNECTION_INVALID;
4902     conn->sniff_min_interval = sniff_min_interval;
4903     conn->sniff_max_interval = sniff_max_interval;
4904     conn->sniff_attempt = sniff_attempt;
4905     conn->sniff_timeout = sniff_timeout;
4906     hci_run();
4907     return 0;
4908 }
4909 
4910 /**
4911  * @brief Exit Sniff mode
4912  * @param con_handle
4913  @ @return 0 if ok
4914  */
4915 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
4916     hci_connection_t * conn = hci_connection_for_handle(con_handle);
4917     if (!conn) return GAP_CONNECTION_INVALID;
4918     conn->sniff_min_interval = 0xffff;
4919     hci_run();
4920     return 0;
4921 }
4922 #endif
4923