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