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