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