xref: /btstack/src/hci.c (revision 293fd5fb21e86fbb29e9789cc0a2c06dafbbf1b3)
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_CLASSIC);
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_CLASSIC){
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_CLASSIC:
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_CLASSIC);
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_CLASSIC : 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_CLASSIC;
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                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
2159 
2160                     // restart timer
2161                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2162                     btstack_run_loop_add_timer(&conn->timeout);
2163 
2164                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2165 
2166                     hci_emit_nr_connections_changed();
2167                 } else {
2168                     // connection failed
2169                     hci_handle_connection_failed(conn, packet[2]);
2170                 }
2171             }
2172             break;
2173 
2174         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
2175             reverse_bd_addr(&packet[5], addr);
2176             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2177             if (packet[2]){
2178                 // connection failed
2179                 break;
2180             }
2181             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2182             if (!conn) {
2183                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2184             }
2185             if (!conn) {
2186                 break;
2187             }
2188             conn->state = OPEN;
2189             conn->con_handle = little_endian_read_16(packet, 3);
2190 
2191 #ifdef ENABLE_SCO_OVER_HCI
2192             // update SCO
2193             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
2194                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
2195             }
2196             // trigger can send now
2197             if (hci_have_usb_transport()){
2198                 hci_stack->sco_can_send_now = 1;
2199             }
2200 #endif
2201             break;
2202 
2203         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2204             handle = little_endian_read_16(packet, 3);
2205             conn = hci_connection_for_handle(handle);
2206             if (!conn) break;
2207             if (!packet[2]){
2208                 uint8_t * features = &packet[5];
2209                 if (features[6] & (1 << 3)){
2210                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
2211                 }
2212                 if (features[3] & (1<<7)){
2213                     conn->remote_supported_feature_eSCO = 1;
2214                 }
2215             }
2216             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2217             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
2218             if (conn->bonding_flags & BONDING_DEDICATED){
2219                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2220             }
2221             break;
2222 
2223         case HCI_EVENT_LINK_KEY_REQUEST:
2224             log_info("HCI_EVENT_LINK_KEY_REQUEST");
2225             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
2226             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
2227             if (hci_stack->bondable && !hci_stack->link_key_db) break;
2228             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
2229             hci_run();
2230             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
2231             return;
2232 
2233         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2234             reverse_bd_addr(&packet[2], addr);
2235             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2236             if (!conn) break;
2237             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
2238             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2239             // Change Connection Encryption keeps link key type
2240             if (link_key_type != CHANGED_COMBINATION_KEY){
2241                 conn->link_key_type = link_key_type;
2242             }
2243             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2244             // still forward event to allow dismiss of pairing dialog
2245             break;
2246         }
2247 
2248         case HCI_EVENT_PIN_CODE_REQUEST:
2249             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
2250             // non-bondable mode: pin code negative reply will be sent
2251             if (!hci_stack->bondable){
2252                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
2253                 hci_run();
2254                 return;
2255             }
2256             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
2257             if (!hci_stack->link_key_db) break;
2258             hci_event_pin_code_request_get_bd_addr(packet, addr);
2259             hci_stack->link_key_db->delete_link_key(addr);
2260             break;
2261 
2262         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2263             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
2264             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
2265             break;
2266 
2267         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2268             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2269             if (!hci_stack->ssp_auto_accept) break;
2270             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
2271             break;
2272 
2273         case HCI_EVENT_USER_PASSKEY_REQUEST:
2274             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2275             if (!hci_stack->ssp_auto_accept) break;
2276             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
2277             break;
2278         case HCI_EVENT_MODE_CHANGE:
2279             handle = hci_event_mode_change_get_handle(packet);
2280             conn = hci_connection_for_handle(handle);
2281             if (!conn) break;
2282             conn->connection_mode = hci_event_mode_change_get_mode(packet);
2283             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
2284             break;
2285 #endif
2286 
2287         case HCI_EVENT_ENCRYPTION_CHANGE:
2288             handle = little_endian_read_16(packet, 3);
2289             conn = hci_connection_for_handle(handle);
2290             if (!conn) break;
2291             if (packet[2] == 0) {
2292                 if (packet[5]){
2293                     if (hci_is_le_connection(conn)){
2294                         // For LE, we accept connection as encrypted
2295                         conn->authentication_flags |= CONNECTION_ENCRYPTED;
2296                     }
2297 #ifdef ENABLE_CLASSIC
2298                     else {
2299                         // For Classic, we need to validate encryption key size first
2300                         conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
2301                     }
2302 #endif
2303                 } else {
2304                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
2305                 }
2306             }
2307 
2308             break;
2309 
2310 #ifdef ENABLE_CLASSIC
2311         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2312             handle = little_endian_read_16(packet, 3);
2313             conn = hci_connection_for_handle(handle);
2314             if (!conn) break;
2315 
2316             // dedicated bonding: send result and disconnect
2317             if (conn->bonding_flags & BONDING_DEDICATED){
2318                 conn->bonding_flags &= ~BONDING_DEDICATED;
2319                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2320                 conn->bonding_status = packet[2];
2321                 break;
2322             }
2323 
2324             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
2325                 // link key sufficient for requested security
2326                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2327                 break;
2328             }
2329             // not enough
2330             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2331             break;
2332 #endif
2333 
2334         // HCI_EVENT_DISCONNECTION_COMPLETE
2335         // has been split, to first notify stack before shutting connection down
2336         // see end of function, too.
2337         case HCI_EVENT_DISCONNECTION_COMPLETE:
2338             if (packet[2]) break;   // status != 0
2339             handle = little_endian_read_16(packet, 3);
2340             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
2341             if (hci_stack->acl_fragmentation_total_size > 0) {
2342                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
2343                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0;
2344                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
2345                     hci_stack->acl_fragmentation_total_size = 0;
2346                     hci_stack->acl_fragmentation_pos = 0;
2347                     if (release_buffer){
2348                         hci_release_packet_buffer();
2349                     }
2350                 }
2351             }
2352 
2353             // re-enable advertisements for le connections if active
2354             conn = hci_connection_for_handle(handle);
2355             if (!conn) break;
2356             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2357 #ifdef ENABLE_BLE
2358 #ifdef ENABLE_LE_PERIPHERAL
2359             if (hci_is_le_connection(conn)){
2360                 hci_reenable_advertisements_if_needed();
2361             }
2362 #endif
2363 #endif
2364             break;
2365 
2366         case HCI_EVENT_HARDWARE_ERROR:
2367             log_error("Hardware Error: 0x%02x", packet[2]);
2368             if (hci_stack->hardware_error_callback){
2369                 (*hci_stack->hardware_error_callback)(packet[2]);
2370             } else {
2371                 // if no special requests, just reboot stack
2372                 hci_power_control_off();
2373                 hci_power_control_on();
2374             }
2375             break;
2376 
2377 #ifdef ENABLE_CLASSIC
2378         case HCI_EVENT_ROLE_CHANGE:
2379             if (packet[2]) break;   // status != 0
2380             reverse_bd_addr(&packet[3], addr);
2381             addr_type = BD_ADDR_TYPE_CLASSIC;
2382             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2383             if (!conn) break;
2384             conn->role = packet[9];
2385             break;
2386 #endif
2387 
2388         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2389             // release packet buffer only for asynchronous transport and if there are not further fragements
2390             if (hci_transport_synchronous()) {
2391                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2392                 return; // instead of break: to avoid re-entering hci_run()
2393             }
2394             hci_stack->acl_fragmentation_tx_active = 0;
2395             if (hci_stack->acl_fragmentation_total_size) break;
2396             hci_release_packet_buffer();
2397 
2398             // L2CAP receives this event via the hci_emit_event below
2399 
2400 #ifdef ENABLE_CLASSIC
2401             // For SCO, we do the can_send_now_check here
2402             hci_notify_if_sco_can_send_now();
2403 #endif
2404             break;
2405 
2406 #ifdef ENABLE_CLASSIC
2407         case HCI_EVENT_SCO_CAN_SEND_NOW:
2408             // For SCO, we do the can_send_now_check here
2409             hci_stack->sco_can_send_now = 1;
2410             hci_notify_if_sco_can_send_now();
2411             return;
2412 
2413         // explode inquriy results for easier consumption
2414         case HCI_EVENT_INQUIRY_RESULT:
2415         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
2416         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
2417             gap_inquiry_explode(packet);
2418             break;
2419 #endif
2420 
2421 #ifdef ENABLE_BLE
2422         case HCI_EVENT_LE_META:
2423             switch (packet[2]){
2424 #ifdef ENABLE_LE_CENTRAL
2425                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
2426                     // log_info("advertising report received");
2427                     if (!hci_stack->le_scanning_enabled) break;
2428                     le_handle_advertisement_report(packet, size);
2429                     break;
2430 #endif
2431                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
2432                     // Connection management
2433                     reverse_bd_addr(&packet[8], addr);
2434                     addr_type = (bd_addr_type_t)packet[7];
2435                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2436                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2437 
2438 #ifdef ENABLE_LE_CENTRAL
2439                     // if auto-connect, remove from whitelist in both roles
2440                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
2441                         hci_remove_from_whitelist(addr_type, addr);
2442                     }
2443                     // handle error: error is reported only to the initiator -> outgoing connection
2444                     if (packet[3]){
2445 
2446                         // handle cancelled outgoing connection
2447                         // "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2448                         //  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2449                         //  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2450                         if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2451                             conn = gap_get_outgoing_connection();
2452                         }
2453 
2454                         // outgoing connection establishment is done
2455                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2456                         // remove entry
2457                         if (conn){
2458                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2459                             btstack_memory_hci_connection_free( conn );
2460                         }
2461                         break;
2462                     }
2463 #endif
2464                     // on success, both hosts receive connection complete event
2465                     if (packet[6] == HCI_ROLE_MASTER){
2466 #ifdef ENABLE_LE_CENTRAL
2467                         // if we're master, it was an outgoing connection and we're done with it
2468                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2469 #endif
2470                     } else {
2471 #ifdef ENABLE_LE_PERIPHERAL
2472                         // if we're slave, it was an incoming connection, advertisements have stopped
2473                         hci_stack->le_advertisements_active = 0;
2474 #endif
2475                     }
2476                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2477                     if (!conn){
2478                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2479                     }
2480                     // no memory, sorry.
2481                     if (!conn){
2482                         break;
2483                     }
2484 
2485                     conn->state = OPEN;
2486                     conn->role  = packet[6];
2487                     conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
2488                     conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
2489 
2490 #ifdef ENABLE_LE_PERIPHERAL
2491                     if (packet[6] == HCI_ROLE_SLAVE){
2492                         hci_reenable_advertisements_if_needed();
2493                     }
2494 #endif
2495 
2496                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2497 
2498                     // restart timer
2499                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2500                     // btstack_run_loop_add_timer(&conn->timeout);
2501 
2502                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2503 
2504                     hci_emit_nr_connections_changed();
2505                     break;
2506 
2507                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2508                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
2509                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
2510                     conn = hci_connection_for_handle(handle);
2511                     if (!conn) break;
2512                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
2513                     break;
2514 
2515                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
2516                     // connection
2517                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
2518                     conn = hci_connection_for_handle(handle);
2519                     if (conn) {
2520                         // read arguments
2521                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
2522                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
2523                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
2524                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
2525 
2526                         // validate against current connection parameter range
2527                         le_connection_parameter_range_t existing_range;
2528                         gap_get_connection_parameter_range(&existing_range);
2529                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
2530                         if (update_parameter){
2531                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
2532                             conn->le_conn_interval_min = le_conn_interval_min;
2533                             conn->le_conn_interval_max = le_conn_interval_max;
2534                             conn->le_conn_latency = le_conn_latency;
2535                             conn->le_supervision_timeout = le_supervision_timeout;
2536                         } else {
2537                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2538                         }
2539                     }
2540                     break;
2541                 default:
2542                     break;
2543             }
2544             break;
2545 #endif
2546         case HCI_EVENT_VENDOR_SPECIFIC:
2547             // Vendor specific commands often create vendor specific event instead of num completed packets
2548             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
2549             switch (hci_stack->manufacturer){
2550                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
2551                     hci_stack->num_cmd_packets = 1;
2552                     break;
2553                 default:
2554                     break;
2555             }
2556             break;
2557         default:
2558             break;
2559     }
2560 
2561     // handle BT initialization
2562     if (hci_stack->state == HCI_STATE_INITIALIZING){
2563         hci_initializing_event_handler(packet, size);
2564     }
2565 
2566     // help with BT sleep
2567     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2568         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2569         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2570         hci_initializing_next_state();
2571     }
2572 
2573     // notify upper stack
2574 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2575 
2576     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2577     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2578         if (!packet[2]){
2579             handle = little_endian_read_16(packet, 3);
2580             hci_connection_t * aConn = hci_connection_for_handle(handle);
2581             if (aConn) {
2582                 uint8_t status = aConn->bonding_status;
2583                 uint16_t flags = aConn->bonding_flags;
2584                 bd_addr_t bd_address;
2585                 memcpy(&bd_address, aConn->address, 6);
2586                 hci_shutdown_connection(aConn);
2587                 // connection struct is gone, don't access anymore
2588                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2589                     hci_emit_dedicated_bonding_result(bd_address, status);
2590                 }
2591             }
2592         }
2593     }
2594 
2595 	// execute main loop
2596 	hci_run();
2597 }
2598 
2599 #ifdef ENABLE_CLASSIC
2600 
2601 static void sco_tx_timeout_handler(btstack_timer_source_t * ts);
2602 static void sco_schedule_tx(hci_connection_t * conn);
2603 
2604 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){
2605     log_debug("SCO TX Timeout");
2606     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts);
2607     hci_connection_t * conn = hci_connection_for_handle(con_handle);
2608     if (!conn) return;
2609 
2610     // trigger send
2611     conn->sco_tx_ready = 1;
2612     // extra packet if CVSD but SCO buffer is too short
2613     if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && hci_stack->sco_data_packet_length < 123){
2614         conn->sco_tx_ready++;
2615     }
2616     hci_notify_if_sco_can_send_now();
2617 }
2618 
2619 
2620 #define SCO_TX_AFTER_RX_MS (6)
2621 
2622 static void sco_schedule_tx(hci_connection_t * conn){
2623 
2624     uint32_t now = btstack_run_loop_get_time_ms();
2625     uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS;
2626     int time_delta_ms = sco_tx_ms - now;
2627 
2628     btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco;
2629 
2630     // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms);
2631     btstack_run_loop_set_timer(timer, time_delta_ms);
2632     btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle);
2633     btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler);
2634     btstack_run_loop_add_timer(timer);
2635 }
2636 
2637 static void sco_handler(uint8_t * packet, uint16_t size){
2638     // lookup connection struct
2639     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2640     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
2641     if (!conn) return;
2642 
2643     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
2644     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
2645         if (size == 83 && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
2646             packet[2] = 0x3c;
2647             memmove(&packet[3], &packet[23], 63);
2648             size = 63;
2649         }
2650     }
2651 
2652     if (hci_have_usb_transport()){
2653         // Nothing to do
2654     } else {
2655         // 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);
2656         if (hci_stack->synchronous_flow_control_enabled == 0){
2657             uint32_t now = btstack_run_loop_get_time_ms();
2658 
2659             if (!conn->sco_rx_valid){
2660                 // ignore first 10 packets
2661                 conn->sco_rx_count++;
2662                 // log_debug("sco rx count %u", conn->sco_rx_count);
2663                 if (conn->sco_rx_count == 10) {
2664                     // use first timestamp as is and pretent it just started
2665                     conn->sco_rx_ms = now;
2666                     conn->sco_rx_valid = 1;
2667                     conn->sco_rx_count = 0;
2668                     sco_schedule_tx(conn);
2669                 }
2670             } else {
2671                 // track expected arrival timme
2672                 conn->sco_rx_count++;
2673                 conn->sco_rx_ms += 7;
2674                 int delta = (int32_t) (now - conn->sco_rx_ms);
2675                 if (delta > 0){
2676                     conn->sco_rx_ms++;
2677                 }
2678                 // log_debug("sco rx %u", conn->sco_rx_ms);
2679                 sco_schedule_tx(conn);
2680             }
2681         }
2682     }
2683     // deliver to app
2684     if (hci_stack->sco_packet_handler) {
2685         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2686     }
2687 
2688 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2689     conn->num_packets_completed++;
2690     hci_stack->host_completed_packets = 1;
2691     hci_run();
2692 #endif
2693 }
2694 #endif
2695 
2696 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2697     hci_dump_packet(packet_type, 1, packet, size);
2698     switch (packet_type) {
2699         case HCI_EVENT_PACKET:
2700             event_handler(packet, size);
2701             break;
2702         case HCI_ACL_DATA_PACKET:
2703             acl_handler(packet, size);
2704             break;
2705 #ifdef ENABLE_CLASSIC
2706         case HCI_SCO_DATA_PACKET:
2707             sco_handler(packet, size);
2708             break;
2709 #endif
2710         default:
2711             break;
2712     }
2713 }
2714 
2715 /**
2716  * @brief Add event packet handler.
2717  */
2718 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2719     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2720 }
2721 
2722 
2723 /** Register HCI packet handlers */
2724 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2725     hci_stack->acl_packet_handler = handler;
2726 }
2727 
2728 #ifdef ENABLE_CLASSIC
2729 /**
2730  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2731  */
2732 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2733     hci_stack->sco_packet_handler = handler;
2734 }
2735 #endif
2736 
2737 static void hci_state_reset(void){
2738     // no connections yet
2739     hci_stack->connections = NULL;
2740 
2741     // keep discoverable/connectable as this has been requested by the client(s)
2742     // hci_stack->discoverable = 0;
2743     // hci_stack->connectable = 0;
2744     // hci_stack->bondable = 1;
2745     // hci_stack->own_addr_type = 0;
2746 
2747     // buffer is free
2748     hci_stack->hci_packet_buffer_reserved = 0;
2749 
2750     // no pending cmds
2751     hci_stack->decline_reason = 0;
2752     hci_stack->new_scan_enable_value = 0xff;
2753 
2754     // LE
2755 #ifdef ENABLE_BLE
2756     memset(hci_stack->le_random_address, 0, 6);
2757     hci_stack->le_random_address_set = 0;
2758 #endif
2759 #ifdef ENABLE_LE_CENTRAL
2760     hci_stack->le_scanning_active  = 0;
2761     hci_stack->le_scan_type = 0xff;
2762     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2763     hci_stack->le_whitelist = 0;
2764     hci_stack->le_whitelist_capacity = 0;
2765 #endif
2766 }
2767 
2768 #ifdef ENABLE_CLASSIC
2769 /**
2770  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2771  */
2772 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2773     // store and open remote device db
2774     hci_stack->link_key_db = link_key_db;
2775     if (hci_stack->link_key_db) {
2776         hci_stack->link_key_db->open();
2777     }
2778 }
2779 #endif
2780 
2781 void hci_init(const hci_transport_t *transport, const void *config){
2782 
2783 #ifdef HAVE_MALLOC
2784     if (!hci_stack) {
2785         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2786     }
2787 #else
2788     hci_stack = &hci_stack_static;
2789 #endif
2790     memset(hci_stack, 0, sizeof(hci_stack_t));
2791 
2792     // reference to use transport layer implementation
2793     hci_stack->hci_transport = transport;
2794 
2795     // reference to used config
2796     hci_stack->config = config;
2797 
2798     // setup pointer for outgoing packet buffer
2799     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2800 
2801     // max acl payload size defined in config.h
2802     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2803 
2804     // register packet handlers with transport
2805     transport->register_packet_handler(&packet_handler);
2806 
2807     hci_stack->state = HCI_STATE_OFF;
2808 
2809     // class of device
2810     hci_stack->class_of_device = 0x007a020c; // Smartphone
2811 
2812     // bondable by default
2813     hci_stack->bondable = 1;
2814 
2815 #ifdef ENABLE_CLASSIC
2816     // classic name
2817     hci_stack->local_name = default_classic_name;
2818 
2819     // Master slave policy
2820     hci_stack->master_slave_policy = 1;
2821 
2822     // Errata-11838 mandates 7 bytes for GAP Security Level 1-3, we use 16 as default
2823     hci_stack->gap_required_encyrption_key_size = 16;
2824 #endif
2825 
2826     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2827     hci_stack->ssp_enable = 1;
2828     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2829     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2830     hci_stack->ssp_auto_accept = 1;
2831 
2832     // voice setting - signed 16 bit pcm data with CVSD over the air
2833     hci_stack->sco_voice_setting = 0x60;
2834 
2835 #ifdef ENABLE_LE_CENTRAL
2836     // connection parameter to use for outgoing connections
2837     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
2838     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
2839     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
2840     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
2841     hci_stack->le_connection_latency      = 4;         // 4
2842     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
2843     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
2844     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
2845 
2846     // default LE Scanning
2847     hci_stack->le_scan_interval = 0x1e0;
2848     hci_stack->le_scan_window   =  0x30;
2849 #endif
2850 
2851 #ifdef ENABLE_LE_PERIPHERAL
2852     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
2853 #endif
2854 
2855     // connection parameter range used to answer connection parameter update requests in l2cap
2856     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2857     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2858     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2859     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2860     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2861     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2862 
2863     hci_state_reset();
2864 }
2865 
2866 /**
2867  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2868  */
2869 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2870     hci_stack->chipset = chipset_driver;
2871 
2872     // reset chipset driver - init is also called on power_up
2873     if (hci_stack->chipset && hci_stack->chipset->init){
2874         hci_stack->chipset->init(hci_stack->config);
2875     }
2876 }
2877 
2878 /**
2879  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2880  */
2881 void hci_set_control(const btstack_control_t *hardware_control){
2882     // references to used control implementation
2883     hci_stack->control = hardware_control;
2884     // init with transport config
2885     hardware_control->init(hci_stack->config);
2886 }
2887 
2888 void hci_close(void){
2889     // close remote device db
2890     if (hci_stack->link_key_db) {
2891         hci_stack->link_key_db->close();
2892     }
2893 
2894     btstack_linked_list_iterator_t lit;
2895     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2896     while (btstack_linked_list_iterator_has_next(&lit)){
2897         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2898         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2899         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2900         hci_shutdown_connection(connection);
2901     }
2902 
2903     hci_power_control(HCI_POWER_OFF);
2904 
2905 #ifdef HAVE_MALLOC
2906     free(hci_stack);
2907 #endif
2908     hci_stack = NULL;
2909 }
2910 
2911 #ifdef ENABLE_CLASSIC
2912 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){
2913     // validate ranage and set
2914     if (encryption_key_size < 7)  return;
2915     if (encryption_key_size > 16) return;
2916     hci_stack->gap_required_encyrption_key_size = encryption_key_size;
2917 }
2918 #endif
2919 
2920 #ifdef ENABLE_CLASSIC
2921 void gap_set_class_of_device(uint32_t class_of_device){
2922     hci_stack->class_of_device = class_of_device;
2923 }
2924 
2925 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
2926     hci_stack->default_link_policy_settings = default_link_policy_settings;
2927 }
2928 
2929 void hci_disable_l2cap_timeout_check(void){
2930     disable_l2cap_timeouts = 1;
2931 }
2932 #endif
2933 
2934 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2935 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2936 void hci_set_bd_addr(bd_addr_t addr){
2937     memcpy(hci_stack->custom_bd_addr, addr, 6);
2938     hci_stack->custom_bd_addr_set = 1;
2939 }
2940 #endif
2941 
2942 // State-Module-Driver overview
2943 // state                    module  low-level
2944 // HCI_STATE_OFF             off      close
2945 // HCI_STATE_INITIALIZING,   on       open
2946 // HCI_STATE_WORKING,        on       open
2947 // HCI_STATE_HALTING,        on       open
2948 // HCI_STATE_SLEEPING,    off/sleep   close
2949 // HCI_STATE_FALLING_ASLEEP  on       open
2950 
2951 static int hci_power_control_on(void){
2952 
2953     // power on
2954     int err = 0;
2955     if (hci_stack->control && hci_stack->control->on){
2956         err = (*hci_stack->control->on)();
2957     }
2958     if (err){
2959         log_error( "POWER_ON failed");
2960         hci_emit_hci_open_failed();
2961         return err;
2962     }
2963 
2964     // int chipset driver
2965     if (hci_stack->chipset && hci_stack->chipset->init){
2966         hci_stack->chipset->init(hci_stack->config);
2967     }
2968 
2969     // init transport
2970     if (hci_stack->hci_transport->init){
2971         hci_stack->hci_transport->init(hci_stack->config);
2972     }
2973 
2974     // open transport
2975     err = hci_stack->hci_transport->open();
2976     if (err){
2977         log_error( "HCI_INIT failed, turning Bluetooth off again");
2978         if (hci_stack->control && hci_stack->control->off){
2979             (*hci_stack->control->off)();
2980         }
2981         hci_emit_hci_open_failed();
2982         return err;
2983     }
2984     return 0;
2985 }
2986 
2987 static void hci_power_control_off(void){
2988 
2989     log_info("hci_power_control_off");
2990 
2991     // close low-level device
2992     hci_stack->hci_transport->close();
2993 
2994     log_info("hci_power_control_off - hci_transport closed");
2995 
2996     // power off
2997     if (hci_stack->control && hci_stack->control->off){
2998         (*hci_stack->control->off)();
2999     }
3000 
3001     log_info("hci_power_control_off - control closed");
3002 
3003     hci_stack->state = HCI_STATE_OFF;
3004 }
3005 
3006 static void hci_power_control_sleep(void){
3007 
3008     log_info("hci_power_control_sleep");
3009 
3010 #if 0
3011     // don't close serial port during sleep
3012 
3013     // close low-level device
3014     hci_stack->hci_transport->close(hci_stack->config);
3015 #endif
3016 
3017     // sleep mode
3018     if (hci_stack->control && hci_stack->control->sleep){
3019         (*hci_stack->control->sleep)();
3020     }
3021 
3022     hci_stack->state = HCI_STATE_SLEEPING;
3023 }
3024 
3025 static int hci_power_control_wake(void){
3026 
3027     log_info("hci_power_control_wake");
3028 
3029     // wake on
3030     if (hci_stack->control && hci_stack->control->wake){
3031         (*hci_stack->control->wake)();
3032     }
3033 
3034 #if 0
3035     // open low-level device
3036     int err = hci_stack->hci_transport->open(hci_stack->config);
3037     if (err){
3038         log_error( "HCI_INIT failed, turning Bluetooth off again");
3039         if (hci_stack->control && hci_stack->control->off){
3040             (*hci_stack->control->off)();
3041         }
3042         hci_emit_hci_open_failed();
3043         return err;
3044     }
3045 #endif
3046 
3047     return 0;
3048 }
3049 
3050 static void hci_power_transition_to_initializing(void){
3051     // set up state machine
3052     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
3053     hci_stack->hci_packet_buffer_reserved = 0;
3054     hci_stack->state = HCI_STATE_INITIALIZING;
3055     hci_stack->substate = HCI_INIT_SEND_RESET;
3056 }
3057 
3058 int hci_power_control(HCI_POWER_MODE power_mode){
3059 
3060     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
3061 
3062     int err = 0;
3063     switch (hci_stack->state){
3064 
3065         case HCI_STATE_OFF:
3066             switch (power_mode){
3067                 case HCI_POWER_ON:
3068                     err = hci_power_control_on();
3069                     if (err) {
3070                         log_error("hci_power_control_on() error %d", err);
3071                         return err;
3072                     }
3073                     hci_power_transition_to_initializing();
3074                     break;
3075                 case HCI_POWER_OFF:
3076                     // do nothing
3077                     break;
3078                 case HCI_POWER_SLEEP:
3079                     // do nothing (with SLEEP == OFF)
3080                     break;
3081             }
3082             break;
3083 
3084         case HCI_STATE_INITIALIZING:
3085             switch (power_mode){
3086                 case HCI_POWER_ON:
3087                     // do nothing
3088                     break;
3089                 case HCI_POWER_OFF:
3090                     // no connections yet, just turn it off
3091                     hci_power_control_off();
3092                     break;
3093                 case HCI_POWER_SLEEP:
3094                     // no connections yet, just turn it off
3095                     hci_power_control_sleep();
3096                     break;
3097             }
3098             break;
3099 
3100         case HCI_STATE_WORKING:
3101             switch (power_mode){
3102                 case HCI_POWER_ON:
3103                     // do nothing
3104                     break;
3105                 case HCI_POWER_OFF:
3106                     // see hci_run
3107                     hci_stack->state = HCI_STATE_HALTING;
3108                     hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3109                     break;
3110                 case HCI_POWER_SLEEP:
3111                     // see hci_run
3112                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3113                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3114                     break;
3115             }
3116             break;
3117 
3118         case HCI_STATE_HALTING:
3119             switch (power_mode){
3120                 case HCI_POWER_ON:
3121                     hci_power_transition_to_initializing();
3122                     break;
3123                 case HCI_POWER_OFF:
3124                     // do nothing
3125                     break;
3126                 case HCI_POWER_SLEEP:
3127                     // see hci_run
3128                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3129                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3130                     break;
3131             }
3132             break;
3133 
3134         case HCI_STATE_FALLING_ASLEEP:
3135             switch (power_mode){
3136                 case HCI_POWER_ON:
3137 
3138 #ifdef HAVE_PLATFORM_IPHONE_OS
3139                     // nothing to do, if H4 supports power management
3140                     if (btstack_control_iphone_power_management_enabled()){
3141                         hci_stack->state = HCI_STATE_INITIALIZING;
3142                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
3143                         break;
3144                     }
3145 #endif
3146                     hci_power_transition_to_initializing();
3147                     break;
3148                 case HCI_POWER_OFF:
3149                     // see hci_run
3150                     hci_stack->state = HCI_STATE_HALTING;
3151                     hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3152                     break;
3153                 case HCI_POWER_SLEEP:
3154                     // do nothing
3155                     break;
3156             }
3157             break;
3158 
3159         case HCI_STATE_SLEEPING:
3160             switch (power_mode){
3161                 case HCI_POWER_ON:
3162 
3163 #ifdef HAVE_PLATFORM_IPHONE_OS
3164                     // nothing to do, if H4 supports power management
3165                     if (btstack_control_iphone_power_management_enabled()){
3166                         hci_stack->state = HCI_STATE_INITIALIZING;
3167                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
3168                         hci_update_scan_enable();
3169                         break;
3170                     }
3171 #endif
3172                     err = hci_power_control_wake();
3173                     if (err) return err;
3174                     hci_power_transition_to_initializing();
3175                     break;
3176                 case HCI_POWER_OFF:
3177                     hci_stack->state = HCI_STATE_HALTING;
3178                     hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3179                     break;
3180                 case HCI_POWER_SLEEP:
3181                     // do nothing
3182                     break;
3183             }
3184             break;
3185     }
3186 
3187     // create internal event
3188 	hci_emit_state();
3189 
3190 	// trigger next/first action
3191 	hci_run();
3192 
3193     return 0;
3194 }
3195 
3196 
3197 #ifdef ENABLE_CLASSIC
3198 
3199 static void hci_update_scan_enable(void){
3200     // 2 = page scan, 1 = inq scan
3201     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
3202     hci_run();
3203 }
3204 
3205 void gap_discoverable_control(uint8_t enable){
3206     if (enable) enable = 1; // normalize argument
3207 
3208     if (hci_stack->discoverable == enable){
3209         hci_emit_discoverable_enabled(hci_stack->discoverable);
3210         return;
3211     }
3212 
3213     hci_stack->discoverable = enable;
3214     hci_update_scan_enable();
3215 }
3216 
3217 void gap_connectable_control(uint8_t enable){
3218     if (enable) enable = 1; // normalize argument
3219 
3220     // don't emit event
3221     if (hci_stack->connectable == enable) return;
3222 
3223     hci_stack->connectable = enable;
3224     hci_update_scan_enable();
3225 }
3226 #endif
3227 
3228 void gap_local_bd_addr(bd_addr_t address_buffer){
3229     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
3230 }
3231 
3232 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3233 static void hci_host_num_completed_packets(void){
3234 
3235     // create packet manually as arrays are not supported and num_commands should not get reduced
3236     hci_reserve_packet_buffer();
3237     uint8_t * packet = hci_get_outgoing_packet_buffer();
3238 
3239     uint16_t size = 0;
3240     uint16_t num_handles = 0;
3241     packet[size++] = 0x35;
3242     packet[size++] = 0x0c;
3243     size++;  // skip param len
3244     size++;  // skip num handles
3245 
3246     // add { handle, packets } entries
3247     btstack_linked_item_t * it;
3248     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3249         hci_connection_t * connection = (hci_connection_t *) it;
3250         if (connection->num_packets_completed){
3251             little_endian_store_16(packet, size, connection->con_handle);
3252             size += 2;
3253             little_endian_store_16(packet, size, connection->num_packets_completed);
3254             size += 2;
3255             //
3256             num_handles++;
3257             connection->num_packets_completed = 0;
3258         }
3259     }
3260 
3261     packet[2] = size - 3;
3262     packet[3] = num_handles;
3263 
3264     hci_stack->host_completed_packets = 0;
3265 
3266     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3267     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3268 
3269     // release packet buffer for synchronous transport implementations
3270     if (hci_transport_synchronous()){
3271         hci_release_packet_buffer();
3272         hci_emit_transport_packet_sent();
3273     }
3274 }
3275 #endif
3276 
3277 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
3278     UNUSED(ds);
3279     hci_stack->substate = HCI_HALTING_CLOSE;
3280     // allow packet handlers to defer final shutdown
3281     hci_emit_state();
3282     hci_run();
3283 }
3284 
3285 static void hci_run(void){
3286 
3287     // log_info("hci_run: entered");
3288     btstack_linked_item_t * it;
3289 
3290     // send continuation fragments first, as they block the prepared packet buffer
3291     if (hci_stack->acl_fragmentation_total_size > 0) {
3292         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
3293         hci_connection_t *connection = hci_connection_for_handle(con_handle);
3294         if (connection) {
3295             if (hci_can_send_prepared_acl_packet_now(con_handle)){
3296                 hci_send_acl_packet_fragments(connection);
3297                 return;
3298             }
3299         } else {
3300             // connection gone -> discard further fragments
3301             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
3302             hci_stack->acl_fragmentation_total_size = 0;
3303             hci_stack->acl_fragmentation_pos = 0;
3304         }
3305     }
3306 
3307 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3308     // send host num completed packets next as they don't require num_cmd_packets > 0
3309     if (!hci_can_send_comand_packet_transport()) return;
3310     if (hci_stack->host_completed_packets){
3311         hci_host_num_completed_packets();
3312         return;
3313     }
3314 #endif
3315 
3316     if (!hci_can_send_command_packet_now()) return;
3317 
3318     // global/non-connection oriented commands
3319 
3320 #ifdef ENABLE_CLASSIC
3321     // decline incoming connections
3322     if (hci_stack->decline_reason){
3323         uint8_t reason = hci_stack->decline_reason;
3324         hci_stack->decline_reason = 0;
3325         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
3326         return;
3327     }
3328     // send scan enable
3329     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
3330         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
3331         hci_stack->new_scan_enable_value = 0xff;
3332         return;
3333     }
3334     // start/stop inquiry
3335     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX){
3336         uint8_t duration = hci_stack->inquiry_state;
3337         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3338         hci_send_cmd(&hci_inquiry, GAP_IAC_GENERAL_INQUIRY, duration, 0);
3339         return;
3340     }
3341     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
3342         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
3343         hci_send_cmd(&hci_inquiry_cancel);
3344         return;
3345     }
3346     // remote name request
3347     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
3348         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
3349         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
3350             hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
3351         return;
3352     }
3353     // pairing
3354     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
3355         uint8_t state = hci_stack->gap_pairing_state;
3356         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
3357         switch (state){
3358             case GAP_PAIRING_STATE_SEND_PIN:
3359                 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);
3360                 break;
3361             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
3362                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
3363                 break;
3364             case GAP_PAIRING_STATE_SEND_PASSKEY:
3365                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
3366                 break;
3367             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
3368                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
3369                 break;
3370             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
3371                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
3372                 break;
3373             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
3374                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
3375                 break;
3376             default:
3377                 break;
3378         }
3379         return;
3380     }
3381 #endif
3382 
3383 #ifdef ENABLE_BLE
3384     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
3385     if ((hci_stack->state == HCI_STATE_WORKING)
3386     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
3387 
3388 #ifdef ENABLE_LE_CENTRAL
3389         // handle le scan
3390         if ((hci_stack->le_scanning_enabled != hci_stack->le_scanning_active)){
3391             hci_stack->le_scanning_active = hci_stack->le_scanning_enabled;
3392             hci_send_cmd(&hci_le_set_scan_enable, hci_stack->le_scanning_enabled, 0);
3393             return;
3394         }
3395         if (hci_stack->le_scan_type != 0xff){
3396             // defaults: active scanning, accept all advertisement packets
3397             int scan_type = hci_stack->le_scan_type;
3398             hci_stack->le_scan_type = 0xff;
3399             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);
3400             return;
3401         }
3402 #endif
3403 #ifdef ENABLE_LE_PERIPHERAL
3404         // le advertisement control
3405         if (hci_stack->le_advertisements_todo){
3406             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
3407         }
3408         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
3409             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
3410             hci_send_cmd(&hci_le_set_advertise_enable, 0);
3411             return;
3412         }
3413         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
3414             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3415             hci_send_cmd(&hci_le_set_advertising_parameters,
3416                  hci_stack->le_advertisements_interval_min,
3417                  hci_stack->le_advertisements_interval_max,
3418                  hci_stack->le_advertisements_type,
3419                  hci_stack->le_own_addr_type,
3420                  hci_stack->le_advertisements_direct_address_type,
3421                  hci_stack->le_advertisements_direct_address,
3422                  hci_stack->le_advertisements_channel_map,
3423                  hci_stack->le_advertisements_filter_policy);
3424             return;
3425         }
3426         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3427             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3428             uint8_t adv_data_clean[31];
3429             memset(adv_data_clean, 0, sizeof(adv_data_clean));
3430             memcpy(adv_data_clean, hci_stack->le_advertisements_data, hci_stack->le_advertisements_data_len);
3431             hci_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len);
3432             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3433             return;
3434         }
3435         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3436             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3437             uint8_t scan_data_clean[31];
3438             memset(scan_data_clean, 0, sizeof(scan_data_clean));
3439             memcpy(scan_data_clean, hci_stack->le_scan_response_data, hci_stack->le_scan_response_data_len);
3440             hci_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len);
3441             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean);
3442             return;
3443         }
3444         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
3445             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
3446             hci_send_cmd(&hci_le_set_advertise_enable, 1);
3447             return;
3448         }
3449 #endif
3450 
3451 #ifdef ENABLE_LE_CENTRAL
3452         //
3453         // LE Whitelist Management
3454         //
3455 
3456         // check if whitelist needs modification
3457         btstack_linked_list_iterator_t lit;
3458         int modification_pending = 0;
3459         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3460         while (btstack_linked_list_iterator_has_next(&lit)){
3461             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3462             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3463                 modification_pending = 1;
3464                 break;
3465             }
3466         }
3467 
3468         if (modification_pending){
3469             // stop connnecting if modification pending
3470             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
3471                 hci_send_cmd(&hci_le_create_connection_cancel);
3472                 return;
3473             }
3474 
3475             // add/remove entries
3476             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3477             while (btstack_linked_list_iterator_has_next(&lit)){
3478                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3479                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
3480                     entry->state = LE_WHITELIST_ON_CONTROLLER;
3481                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3482                     return;
3483 
3484                 }
3485                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
3486                     bd_addr_t address;
3487                     bd_addr_type_t address_type = entry->address_type;
3488                     memcpy(address, entry->address, 6);
3489                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3490                     btstack_memory_whitelist_entry_free(entry);
3491                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
3492                     return;
3493                 }
3494             }
3495         }
3496 
3497         // start connecting
3498         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
3499             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
3500             bd_addr_t null_addr;
3501             memset(null_addr, 0, 6);
3502             hci_send_cmd(&hci_le_create_connection,
3503                 hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
3504                 hci_stack->le_connection_scan_window,    // scan interval: 30 ms
3505                  1,         // use whitelist
3506                  0,         // peer address type
3507                  null_addr, // peer bd addr
3508                  hci_stack->le_own_addr_type, // our addr type:
3509                  hci_stack->le_connection_interval_min,    // conn interval min
3510                  hci_stack->le_connection_interval_max,    // conn interval max
3511                  hci_stack->le_connection_latency,         // conn latency
3512                  hci_stack->le_supervision_timeout,        // conn latency
3513                  hci_stack->le_minimum_ce_length,          // min ce length
3514                  hci_stack->le_maximum_ce_length           // max ce length
3515                 );
3516             return;
3517         }
3518 #endif
3519     }
3520 #endif
3521 
3522     // send pending HCI commands
3523     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3524         hci_connection_t * connection = (hci_connection_t *) it;
3525 
3526         switch(connection->state){
3527             case SEND_CREATE_CONNECTION:
3528                 switch(connection->address_type){
3529 #ifdef ENABLE_CLASSIC
3530                     case BD_ADDR_TYPE_CLASSIC:
3531                         log_info("sending hci_create_connection");
3532                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
3533                         break;
3534 #endif
3535                     default:
3536 #ifdef ENABLE_BLE
3537 #ifdef ENABLE_LE_CENTRAL
3538                         // track outgoing connection
3539                         hci_stack->outgoing_addr_type = connection->address_type;
3540                         memcpy(hci_stack->outgoing_addr, connection->address, 6);
3541                         log_info("sending hci_le_create_connection");
3542                         hci_send_cmd(&hci_le_create_connection,
3543                              hci_stack->le_connection_scan_interval,    // conn scan interval
3544                              hci_stack->le_connection_scan_window,      // conn scan windows
3545                              0,         // don't use whitelist
3546                              connection->address_type, // peer address type
3547                              connection->address,      // peer bd addr
3548                              hci_stack->le_own_addr_type, // our addr type:
3549                              hci_stack->le_connection_interval_min,    // conn interval min
3550                              hci_stack->le_connection_interval_max,    // conn interval max
3551                              hci_stack->le_connection_latency,         // conn latency
3552                              hci_stack->le_supervision_timeout,        // conn latency
3553                              hci_stack->le_minimum_ce_length,          // min ce length
3554                              hci_stack->le_maximum_ce_length          // max ce length
3555                              );
3556                         connection->state = SENT_CREATE_CONNECTION;
3557 #endif
3558 #endif
3559                         break;
3560                 }
3561                 return;
3562 
3563 #ifdef ENABLE_CLASSIC
3564             case RECEIVED_CONNECTION_REQUEST:
3565                 connection->role  = HCI_ROLE_SLAVE;
3566                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
3567                     log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
3568                     connection->state = ACCEPTED_CONNECTION_REQUEST;
3569                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
3570                 }
3571                 return;
3572 #endif
3573 
3574 #ifdef ENABLE_BLE
3575 #ifdef ENABLE_LE_CENTRAL
3576             case SEND_CANCEL_CONNECTION:
3577                 connection->state = SENT_CANCEL_CONNECTION;
3578                 hci_send_cmd(&hci_le_create_connection_cancel);
3579                 return;
3580 #endif
3581 #endif
3582             case SEND_DISCONNECT:
3583                 connection->state = SENT_DISCONNECT;
3584                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
3585                 return;
3586 
3587             default:
3588                 break;
3589         }
3590 
3591         // no further commands if connection is about to get shut down
3592         if (connection->state == SENT_DISCONNECT) continue;
3593 
3594         if (connection->authentication_flags & READ_RSSI){
3595             connectionClearAuthenticationFlags(connection, READ_RSSI);
3596             hci_send_cmd(&hci_read_rssi, connection->con_handle);
3597             return;
3598         }
3599 
3600 #ifdef ENABLE_CLASSIC
3601         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
3602             log_info("responding to link key request");
3603             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
3604             link_key_t link_key;
3605             link_key_type_t link_key_type;
3606             if ( hci_stack->link_key_db
3607               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
3608               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
3609                connection->link_key_type = link_key_type;
3610                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
3611             } else {
3612                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
3613             }
3614             return;
3615         }
3616 
3617         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
3618             log_info("denying to pin request");
3619             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
3620             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
3621             return;
3622         }
3623 
3624         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
3625             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
3626             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
3627             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3628                 // tweak authentication requirements
3629                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3630                 if (connection->bonding_flags & BONDING_DEDICATED){
3631                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3632                 }
3633                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
3634                     authreq |= 1;
3635                 }
3636                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3637             } else {
3638                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3639             }
3640             return;
3641         }
3642 
3643         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3644             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
3645             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3646             return;
3647         }
3648 
3649         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3650             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
3651             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3652             return;
3653         }
3654 
3655         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
3656             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
3657             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3658             return;
3659         }
3660 
3661         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3662             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
3663             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
3664             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
3665             return;
3666         }
3667 
3668         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
3669             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3670             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3671             return;
3672         }
3673 
3674         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3675             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3676             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3677             return;
3678         }
3679         if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){
3680             connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE;
3681             hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1);
3682             return;
3683         }
3684 #endif
3685 
3686         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
3687             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
3688             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
3689             return;
3690         }
3691 
3692 #ifdef ENABLE_CLASSIC
3693         uint16_t sniff_min_interval;
3694         switch (connection->sniff_min_interval){
3695             case 0:
3696                 break;
3697             case 0xffff:
3698                 connection->sniff_min_interval = 0;
3699                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
3700                 return;
3701             default:
3702                 sniff_min_interval = connection->sniff_min_interval;
3703                 connection->sniff_min_interval = 0;
3704                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
3705                 return;
3706         }
3707 #endif
3708 
3709 #ifdef ENABLE_BLE
3710         switch (connection->le_con_parameter_update_state){
3711             // response to L2CAP CON PARAMETER UPDATE REQUEST
3712             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
3713                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3714                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
3715                     connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3716                     0x0000, 0xffff);
3717                 return;
3718             case CON_PARAMETER_UPDATE_REPLY:
3719                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3720                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
3721                     connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3722                     0x0000, 0xffff);
3723                 return;
3724             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
3725                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3726                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
3727                 return;
3728             default:
3729                 break;
3730         }
3731         if (connection->le_phy_update_all_phys != 0xff){
3732             uint8_t all_phys = connection->le_phy_update_all_phys;
3733             connection->le_phy_update_all_phys = 0xff;
3734             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);
3735             return;
3736         }
3737 #endif
3738     }
3739 
3740     hci_connection_t * connection;
3741     switch (hci_stack->state){
3742         case HCI_STATE_INITIALIZING:
3743             hci_initializing_run();
3744             break;
3745 
3746         case HCI_STATE_HALTING:
3747 
3748             log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
3749             switch (hci_stack->substate){
3750                 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
3751                 case HCI_HALTING_DISCONNECT_ALL_TIMER:
3752 
3753 #ifdef ENABLE_BLE
3754 #ifdef ENABLE_LE_CENTRAL
3755                     // free whitelist entries
3756                     {
3757                         btstack_linked_list_iterator_t lit;
3758                         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3759                         while (btstack_linked_list_iterator_has_next(&lit)){
3760                             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3761                             btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3762                             btstack_memory_whitelist_entry_free(entry);
3763                         }
3764                     }
3765 #endif
3766 #endif
3767                     // close all open connections
3768                     connection =  (hci_connection_t *) hci_stack->connections;
3769                     if (connection){
3770                         hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
3771                         if (!hci_can_send_command_packet_now()) return;
3772 
3773                         // check state
3774                         if (connection->state == SENT_DISCONNECT) return;
3775                         connection->state = SENT_DISCONNECT;
3776 
3777                         log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
3778 
3779                         // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
3780                         hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
3781 
3782                         // ... which would be ignored anyway as we shutdown (free) the connection now
3783                         hci_shutdown_connection(connection);
3784 
3785                         // finally, send the disconnect command
3786                         hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
3787                         return;
3788                     }
3789 
3790                     if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){
3791                         // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
3792                         log_info("HCI_STATE_HALTING: wait 50 ms");
3793                         hci_stack->substate = HCI_HALTING_W4_TIMER;
3794                         btstack_run_loop_set_timer(&hci_stack->timeout, 50);
3795                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
3796                         btstack_run_loop_add_timer(&hci_stack->timeout);
3797                         break;
3798                     }
3799 
3800                     /* explicit fall-through */
3801 
3802                 case HCI_HALTING_CLOSE:
3803                     log_info("HCI_STATE_HALTING, calling off");
3804 
3805                     // switch mode
3806                     hci_power_control_off();
3807 
3808                     log_info("HCI_STATE_HALTING, emitting state");
3809                     hci_emit_state();
3810                     log_info("HCI_STATE_HALTING, done");
3811                     break;
3812 
3813                 case HCI_HALTING_W4_TIMER:
3814                     // keep waiting
3815 
3816                     break;
3817                 default:
3818                     break;
3819             }
3820 
3821             break;
3822 
3823         case HCI_STATE_FALLING_ASLEEP:
3824             switch(hci_stack->substate) {
3825                 case HCI_FALLING_ASLEEP_DISCONNECT:
3826                     log_info("HCI_STATE_FALLING_ASLEEP");
3827                     // close all open connections
3828                     connection =  (hci_connection_t *) hci_stack->connections;
3829 
3830 #ifdef HAVE_PLATFORM_IPHONE_OS
3831                     // don't close connections, if H4 supports power management
3832                     if (btstack_control_iphone_power_management_enabled()){
3833                         connection = NULL;
3834                     }
3835 #endif
3836                     if (connection){
3837 
3838                         // send disconnect
3839                         if (!hci_can_send_command_packet_now()) return;
3840 
3841                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3842                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3843 
3844                         // send disconnected event right away - causes higher layer connections to get closed, too.
3845                         hci_shutdown_connection(connection);
3846                         return;
3847                     }
3848 
3849                     if (hci_classic_supported()){
3850                         // disable page and inquiry scan
3851                         if (!hci_can_send_command_packet_now()) return;
3852 
3853                         log_info("HCI_STATE_HALTING, disabling inq scans");
3854                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3855 
3856                         // continue in next sub state
3857                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3858                         break;
3859                     }
3860                     // no break - fall through for ble-only chips
3861 
3862                 case HCI_FALLING_ASLEEP_COMPLETE:
3863                     log_info("HCI_STATE_HALTING, calling sleep");
3864 #ifdef HAVE_PLATFORM_IPHONE_OS
3865                     // don't actually go to sleep, if H4 supports power management
3866                     if (btstack_control_iphone_power_management_enabled()){
3867                         // SLEEP MODE reached
3868                         hci_stack->state = HCI_STATE_SLEEPING;
3869                         hci_emit_state();
3870                         break;
3871                     }
3872 #endif
3873                     // switch mode
3874                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3875                     hci_emit_state();
3876                     break;
3877 
3878                 default:
3879                     break;
3880             }
3881             break;
3882 
3883         default:
3884             break;
3885     }
3886 }
3887 
3888 int hci_send_cmd_packet(uint8_t *packet, int size){
3889     // house-keeping
3890 
3891     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3892         hci_stack->loopback_mode = packet[3];
3893     }
3894 
3895 #ifdef ENABLE_CLASSIC
3896     bd_addr_t addr;
3897     hci_connection_t * conn;
3898 
3899     // create_connection?
3900     if (IS_COMMAND(packet, hci_create_connection)){
3901         reverse_bd_addr(&packet[3], addr);
3902         log_info("Create_connection to %s", bd_addr_to_str(addr));
3903 
3904         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3905         if (!conn){
3906             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3907             if (!conn){
3908                 // notify client that alloc failed
3909                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3910                 return -1; // packet not sent to controller
3911             }
3912             conn->state = SEND_CREATE_CONNECTION;
3913         }
3914         log_info("conn state %u", conn->state);
3915         switch (conn->state){
3916             // if connection active exists
3917             case OPEN:
3918                 // and OPEN, emit connection complete command
3919                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3920                 return -1; // packet not sent to controller
3921             case SEND_CREATE_CONNECTION:
3922                 // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
3923                 break;
3924             default:
3925                 // otherwise, just ignore as it is already in the open process
3926                 return -1; // packet not sent to controller
3927         }
3928         conn->state = SENT_CREATE_CONNECTION;
3929 
3930         // track outgoing connection
3931         hci_stack->outgoing_addr_type = BD_ADDR_TYPE_CLASSIC;
3932         memcpy(hci_stack->outgoing_addr, addr, 6);
3933     }
3934 
3935     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3936         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3937     }
3938     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3939         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3940     }
3941 
3942     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3943         if (hci_stack->link_key_db){
3944             reverse_bd_addr(&packet[3], addr);
3945             hci_stack->link_key_db->delete_link_key(addr);
3946         }
3947     }
3948 
3949     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3950     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3951         reverse_bd_addr(&packet[3], addr);
3952         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3953         if (conn){
3954             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3955         }
3956     }
3957 
3958     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3959     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3960     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3961     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3962         reverse_bd_addr(&packet[3], addr);
3963         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3964         if (conn){
3965             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3966         }
3967     }
3968 
3969 #ifdef ENABLE_SCO_OVER_HCI
3970     // setup_synchronous_connection? Voice setting at offset 22
3971     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3972         // TODO: compare to current setting if sco connection already active
3973         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3974     }
3975     // accept_synchronus_connection? Voice setting at offset 18
3976     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3977         // TODO: compare to current setting if sco connection already active
3978         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3979     }
3980 #endif
3981 #endif
3982 
3983 #ifdef ENABLE_BLE
3984     if (IS_COMMAND(packet, hci_le_set_random_address)){
3985         hci_stack->le_random_address_set = 1;
3986         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3987     }
3988 #ifdef ENABLE_LE_PERIPHERAL
3989     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3990         hci_stack->le_advertisements_active = packet[3];
3991     }
3992 #endif
3993 #ifdef ENABLE_LE_CENTRAL
3994     if (IS_COMMAND(packet, hci_le_create_connection)){
3995         // white list used?
3996         uint8_t initiator_filter_policy = packet[7];
3997         switch (initiator_filter_policy){
3998             case 0:
3999                 // whitelist not used
4000                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
4001                 break;
4002             case 1:
4003                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
4004                 break;
4005             default:
4006                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
4007                 break;
4008         }
4009     }
4010     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
4011         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
4012     }
4013 #endif
4014 #endif
4015 
4016     hci_stack->num_cmd_packets--;
4017 
4018     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
4019     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
4020 }
4021 
4022 // disconnect because of security block
4023 void hci_disconnect_security_block(hci_con_handle_t con_handle){
4024     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4025     if (!connection) return;
4026     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
4027 }
4028 
4029 
4030 // Configure Secure Simple Pairing
4031 
4032 #ifdef ENABLE_CLASSIC
4033 
4034 // enable will enable SSP during init
4035 void gap_ssp_set_enable(int enable){
4036     hci_stack->ssp_enable = enable;
4037 }
4038 
4039 static int hci_local_ssp_activated(void){
4040     return gap_ssp_supported() && hci_stack->ssp_enable;
4041 }
4042 
4043 // if set, BTstack will respond to io capability request using authentication requirement
4044 void gap_ssp_set_io_capability(int io_capability){
4045     hci_stack->ssp_io_capability = io_capability;
4046 }
4047 void gap_ssp_set_authentication_requirement(int authentication_requirement){
4048     hci_stack->ssp_authentication_requirement = authentication_requirement;
4049 }
4050 
4051 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
4052 void gap_ssp_set_auto_accept(int auto_accept){
4053     hci_stack->ssp_auto_accept = auto_accept;
4054 }
4055 #endif
4056 
4057 // va_list part of hci_send_cmd
4058 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
4059     if (!hci_can_send_command_packet_now()){
4060         log_error("hci_send_cmd called but cannot send packet now");
4061         return 0;
4062     }
4063 
4064     // for HCI INITIALIZATION
4065     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
4066     hci_stack->last_cmd_opcode = cmd->opcode;
4067 
4068     hci_reserve_packet_buffer();
4069     uint8_t * packet = hci_stack->hci_packet_buffer;
4070     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
4071     int err = hci_send_cmd_packet(packet, size);
4072 
4073     // release packet buffer for synchronous transport implementations
4074     if (hci_transport_synchronous()){
4075         hci_release_packet_buffer();
4076         hci_emit_transport_packet_sent();
4077     }
4078 
4079     return err;
4080 }
4081 
4082 /**
4083  * pre: numcmds >= 0 - it's allowed to send a command to the controller
4084  */
4085 int hci_send_cmd(const hci_cmd_t *cmd, ...){
4086     va_list argptr;
4087     va_start(argptr, cmd);
4088     int res = hci_send_cmd_va_arg(cmd, argptr);
4089     va_end(argptr);
4090     return res;
4091 }
4092 
4093 // Create various non-HCI events.
4094 // TODO: generalize, use table similar to hci_create_command
4095 
4096 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
4097     // dump packet
4098     if (dump) {
4099         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
4100     }
4101 
4102     // dispatch to all event handlers
4103     btstack_linked_list_iterator_t it;
4104     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
4105     while (btstack_linked_list_iterator_has_next(&it)){
4106         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
4107         entry->callback(HCI_EVENT_PACKET, 0, event, size);
4108     }
4109 }
4110 
4111 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
4112     if (!hci_stack->acl_packet_handler) return;
4113     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
4114 }
4115 
4116 #ifdef ENABLE_CLASSIC
4117 static void hci_notify_if_sco_can_send_now(void){
4118     // notify SCO sender if waiting
4119     if (!hci_stack->sco_waiting_for_can_send_now) return;
4120     if (hci_can_send_sco_packet_now()){
4121         hci_stack->sco_waiting_for_can_send_now = 0;
4122         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
4123         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
4124         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
4125     }
4126 }
4127 
4128 // parsing end emitting has been merged to reduce code size
4129 static void gap_inquiry_explode(uint8_t * packet){
4130     uint8_t event[19+GAP_INQUIRY_MAX_NAME_LEN];
4131 
4132     uint8_t * eir_data;
4133     ad_context_t context;
4134     const uint8_t * name;
4135     uint8_t         name_len;
4136 
4137     int event_type = hci_event_packet_get_type(packet);
4138     int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1;    // 2 for old event, 1 otherwise
4139     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
4140 
4141     // event[1] is set at the end
4142     int i;
4143     for (i=0; i<num_responses;i++){
4144         memset(event, 0, sizeof(event));
4145         event[0] = GAP_EVENT_INQUIRY_RESULT;
4146         uint8_t event_size = 18;    // if name is not set by EIR
4147 
4148         memcpy(&event[2],  &packet[3 +                                             i*6], 6); // bd_addr
4149         event[8] =          packet[3 + num_responses*(6)                         + i*1];     // page_scan_repetition_mode
4150         memcpy(&event[9],  &packet[3 + num_responses*(6+1+num_reserved_fields)   + i*3], 3); // class of device
4151         memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset
4152 
4153         switch (event_type){
4154             case HCI_EVENT_INQUIRY_RESULT:
4155                 // 14,15,16,17 = 0, size 18
4156                 break;
4157             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
4158                 event[14] = 1;
4159                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
4160                 // 16,17 = 0, size 18
4161                 break;
4162             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
4163                 event[14] = 1;
4164                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
4165                 // for EIR packets, there is only one reponse in it
4166                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
4167                 name = NULL;
4168                 // EIR data is 240 bytes in EIR event
4169                 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
4170                     uint8_t data_type    = ad_iterator_get_data_type(&context);
4171                     uint8_t data_size    = ad_iterator_get_data_len(&context);
4172                     const uint8_t * data = ad_iterator_get_data(&context);
4173                     // Prefer Complete Local Name over Shortend Local Name
4174                     switch (data_type){
4175                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
4176                             if (name) continue;
4177                             /* explicit fall-through */
4178                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
4179                             name = data;
4180                             name_len = data_size;
4181                             break;
4182                         default:
4183                             break;
4184                     }
4185                 }
4186                 if (name){
4187                     event[16] = 1;
4188                     // truncate name if needed
4189                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
4190                     event[17] = len;
4191                     memcpy(&event[18], name, len);
4192                     event_size += len;
4193                 }
4194                 break;
4195         }
4196         event[1] = event_size - 2;
4197         hci_emit_event(event, event_size, 1);
4198     }
4199 }
4200 #endif
4201 
4202 void hci_emit_state(void){
4203     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
4204     uint8_t event[3];
4205     event[0] = BTSTACK_EVENT_STATE;
4206     event[1] = sizeof(event) - 2;
4207     event[2] = hci_stack->state;
4208     hci_emit_event(event, sizeof(event), 1);
4209 }
4210 
4211 #ifdef ENABLE_CLASSIC
4212 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
4213     uint8_t event[13];
4214     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
4215     event[1] = sizeof(event) - 2;
4216     event[2] = status;
4217     little_endian_store_16(event, 3, con_handle);
4218     reverse_bd_addr(address, &event[5]);
4219     event[11] = 1; // ACL connection
4220     event[12] = 0; // encryption disabled
4221     hci_emit_event(event, sizeof(event), 1);
4222 }
4223 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
4224     if (disable_l2cap_timeouts) return;
4225     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
4226     uint8_t event[4];
4227     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
4228     event[1] = sizeof(event) - 2;
4229     little_endian_store_16(event, 2, conn->con_handle);
4230     hci_emit_event(event, sizeof(event), 1);
4231 }
4232 #endif
4233 
4234 #ifdef ENABLE_BLE
4235 #ifdef ENABLE_LE_CENTRAL
4236 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
4237     uint8_t event[21];
4238     event[0] = HCI_EVENT_LE_META;
4239     event[1] = sizeof(event) - 2;
4240     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
4241     event[3] = status;
4242     little_endian_store_16(event, 4, con_handle);
4243     event[6] = 0; // TODO: role
4244     event[7] = address_type;
4245     reverse_bd_addr(address, &event[8]);
4246     little_endian_store_16(event, 14, 0); // interval
4247     little_endian_store_16(event, 16, 0); // latency
4248     little_endian_store_16(event, 18, 0); // supervision timeout
4249     event[20] = 0; // master clock accuracy
4250     hci_emit_event(event, sizeof(event), 1);
4251 }
4252 #endif
4253 #endif
4254 
4255 static void hci_emit_transport_packet_sent(void){
4256     // notify upper stack that it might be possible to send again
4257     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
4258     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
4259 }
4260 
4261 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
4262     uint8_t event[6];
4263     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
4264     event[1] = sizeof(event) - 2;
4265     event[2] = 0; // status = OK
4266     little_endian_store_16(event, 3, con_handle);
4267     event[5] = reason;
4268     hci_emit_event(event, sizeof(event), 1);
4269 }
4270 
4271 static void hci_emit_nr_connections_changed(void){
4272     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
4273     uint8_t event[3];
4274     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
4275     event[1] = sizeof(event) - 2;
4276     event[2] = nr_hci_connections();
4277     hci_emit_event(event, sizeof(event), 1);
4278 }
4279 
4280 static void hci_emit_hci_open_failed(void){
4281     log_info("BTSTACK_EVENT_POWERON_FAILED");
4282     uint8_t event[2];
4283     event[0] = BTSTACK_EVENT_POWERON_FAILED;
4284     event[1] = sizeof(event) - 2;
4285     hci_emit_event(event, sizeof(event), 1);
4286 }
4287 
4288 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
4289     log_info("hci_emit_dedicated_bonding_result %u ", status);
4290     uint8_t event[9];
4291     int pos = 0;
4292     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
4293     event[pos++] = sizeof(event) - 2;
4294     event[pos++] = status;
4295     reverse_bd_addr(address, &event[pos]);
4296     hci_emit_event(event, sizeof(event), 1);
4297 }
4298 
4299 
4300 #ifdef ENABLE_CLASSIC
4301 
4302 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
4303     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
4304     uint8_t event[5];
4305     int pos = 0;
4306     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
4307     event[pos++] = sizeof(event) - 2;
4308     little_endian_store_16(event, 2, con_handle);
4309     pos += 2;
4310     event[pos++] = level;
4311     hci_emit_event(event, sizeof(event), 1);
4312 }
4313 
4314 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
4315     if (!connection) return LEVEL_0;
4316     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
4317     if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0;
4318     gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type);
4319     // LEVEL 4 always requires 128 bit encrytion key size
4320     if (security_level == LEVEL_4 && connection->encryption_key_size < 16){
4321         security_level = LEVEL_3;
4322     }
4323     return security_level;
4324 }
4325 
4326 static void hci_emit_discoverable_enabled(uint8_t enabled){
4327     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
4328     uint8_t event[3];
4329     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
4330     event[1] = sizeof(event) - 2;
4331     event[2] = enabled;
4332     hci_emit_event(event, sizeof(event), 1);
4333 }
4334 
4335 // query if remote side supports eSCO
4336 int hci_remote_esco_supported(hci_con_handle_t con_handle){
4337     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4338     if (!connection) return 0;
4339     return connection->remote_supported_feature_eSCO;
4340 }
4341 
4342 // query if remote side supports SSP
4343 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
4344     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4345     if (!connection) return 0;
4346     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
4347 }
4348 
4349 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
4350     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
4351 }
4352 
4353 // GAP API
4354 /**
4355  * @bbrief enable/disable bonding. default is enabled
4356  * @praram enabled
4357  */
4358 void gap_set_bondable_mode(int enable){
4359     hci_stack->bondable = enable ? 1 : 0;
4360 }
4361 /**
4362  * @brief Get bondable mode.
4363  * @return 1 if bondable
4364  */
4365 int gap_get_bondable_mode(void){
4366     return hci_stack->bondable;
4367 }
4368 
4369 /**
4370  * @brief map link keys to security levels
4371  */
4372 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
4373     switch (link_key_type){
4374         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
4375             return LEVEL_4;
4376         case COMBINATION_KEY:
4377         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
4378             return LEVEL_3;
4379         default:
4380             return LEVEL_2;
4381     }
4382 }
4383 
4384 /**
4385  * @brief map link keys to secure connection yes/no
4386  */
4387 int gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){
4388     switch (link_key_type){
4389         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
4390         case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
4391             return 1;
4392         default:
4393             return 0;
4394     }
4395 }
4396 
4397 /**
4398  * @brief map link keys to authenticated
4399  */
4400 int gap_authenticated_for_link_key_type(link_key_type_t link_key_type){
4401     switch (link_key_type){
4402         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
4403         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
4404             return 1;
4405         default:
4406             return 0;
4407     }
4408 }
4409 
4410 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
4411     log_info("gap_mitm_protection_required_for_security_level %u", level);
4412     return level > LEVEL_2;
4413 }
4414 
4415 /**
4416  * @brief get current security level
4417  */
4418 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
4419     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4420     if (!connection) return LEVEL_0;
4421     return gap_security_level_for_connection(connection);
4422 }
4423 
4424 /**
4425  * @brief request connection to device to
4426  * @result GAP_AUTHENTICATION_RESULT
4427  */
4428 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
4429     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4430     if (!connection){
4431         hci_emit_security_level(con_handle, LEVEL_0);
4432         return;
4433     }
4434     gap_security_level_t current_level = gap_security_level(con_handle);
4435     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
4436         requested_level, connection->requested_security_level, current_level);
4437 
4438     // assumption: earlier requested security higher than current level => security request is active
4439     if (current_level < connection->requested_security_level){
4440         if (connection->requested_security_level < requested_level){
4441             // increase requested level as new level is higher
4442 
4443             // TODO: handle re-authentication when done
4444 
4445             connection->requested_security_level = requested_level;
4446         }
4447         return;
4448     }
4449 
4450     // no request active, notify if security sufficient
4451     if (requested_level <= current_level){
4452         hci_emit_security_level(con_handle, current_level);
4453         return;
4454     }
4455 
4456     // start pairing to increase security level
4457     connection->requested_security_level = requested_level;
4458 
4459 #if 0
4460     // sending encryption request without a link key results in an error.
4461     // TODO: figure out how to use it properly
4462 
4463     // would enabling ecnryption suffice (>= LEVEL_2)?
4464     if (hci_stack->link_key_db){
4465         link_key_type_t link_key_type;
4466         link_key_t      link_key;
4467         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
4468             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
4469                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4470                 return;
4471             }
4472         }
4473     }
4474 #endif
4475 
4476     // start to authenticate connection
4477     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
4478     hci_run();
4479 }
4480 
4481 /**
4482  * @brief start dedicated bonding with device. disconnect after bonding
4483  * @param device
4484  * @param request MITM protection
4485  * @result GAP_DEDICATED_BONDING_COMPLETE
4486  */
4487 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
4488 
4489     // create connection state machine
4490     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
4491 
4492     if (!connection){
4493         return BTSTACK_MEMORY_ALLOC_FAILED;
4494     }
4495 
4496     // delete linkn key
4497     gap_drop_link_key_for_bd_addr(device);
4498 
4499     // configure LEVEL_2/3, dedicated bonding
4500     connection->state = SEND_CREATE_CONNECTION;
4501     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
4502     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
4503     connection->bonding_flags = BONDING_DEDICATED;
4504 
4505     // wait for GAP Security Result and send GAP Dedicated Bonding complete
4506 
4507     // handle: connnection failure (connection complete != ok)
4508     // handle: authentication failure
4509     // handle: disconnect on done
4510 
4511     hci_run();
4512 
4513     return 0;
4514 }
4515 #endif
4516 
4517 void gap_set_local_name(const char * local_name){
4518     hci_stack->local_name = local_name;
4519 }
4520 
4521 
4522 #ifdef ENABLE_BLE
4523 
4524 #ifdef ENABLE_LE_CENTRAL
4525 void gap_start_scan(void){
4526     hci_stack->le_scanning_enabled = 1;
4527     hci_run();
4528 }
4529 
4530 void gap_stop_scan(void){
4531     hci_stack->le_scanning_enabled = 0;
4532     hci_run();
4533 }
4534 
4535 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
4536     hci_stack->le_scan_type     = scan_type;
4537     hci_stack->le_scan_interval = scan_interval;
4538     hci_stack->le_scan_window   = scan_window;
4539     hci_run();
4540 }
4541 
4542 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
4543     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4544     if (!conn){
4545         log_info("gap_connect: no connection exists yet, creating context");
4546         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
4547         if (!conn){
4548             // notify client that alloc failed
4549             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4550             log_info("gap_connect: failed to alloc hci_connection_t");
4551             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
4552         }
4553         conn->state = SEND_CREATE_CONNECTION;
4554         log_info("gap_connect: send create connection next");
4555         hci_run();
4556         return 0;
4557     }
4558 
4559     if (!hci_is_le_connection(conn) ||
4560         conn->state == SEND_CREATE_CONNECTION ||
4561         conn->state == SENT_CREATE_CONNECTION) {
4562         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
4563         log_error("gap_connect: classic connection or connect is already being created");
4564         return GATT_CLIENT_IN_WRONG_STATE;
4565     }
4566 
4567     log_info("gap_connect: context exists with state %u", conn->state);
4568     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
4569     hci_run();
4570     return 0;
4571 }
4572 
4573 // @assumption: only a single outgoing LE Connection exists
4574 static hci_connection_t * gap_get_outgoing_connection(void){
4575     btstack_linked_item_t *it;
4576     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4577         hci_connection_t * conn = (hci_connection_t *) it;
4578         if (!hci_is_le_connection(conn)) continue;
4579         switch (conn->state){
4580             case SEND_CREATE_CONNECTION:
4581             case SENT_CREATE_CONNECTION:
4582             case SENT_CANCEL_CONNECTION:
4583                 return conn;
4584             default:
4585                 break;
4586         };
4587     }
4588     return NULL;
4589 }
4590 
4591 uint8_t gap_connect_cancel(void){
4592     hci_connection_t * conn = gap_get_outgoing_connection();
4593     if (!conn) return 0;
4594     switch (conn->state){
4595         case SEND_CREATE_CONNECTION:
4596             // skip sending create connection and emit event instead
4597             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
4598             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
4599             btstack_memory_hci_connection_free( conn );
4600             break;
4601         case SENT_CREATE_CONNECTION:
4602             // request to send cancel connection
4603             conn->state = SEND_CANCEL_CONNECTION;
4604             hci_run();
4605             break;
4606         default:
4607             break;
4608     }
4609     return 0;
4610 }
4611 #endif
4612 
4613 #ifdef ENABLE_LE_CENTRAL
4614 /**
4615  * @brief Set connection parameters for outgoing connections
4616  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
4617  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
4618  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
4619  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
4620  * @param conn_latency, default: 4
4621  * @param supervision_timeout (unit: 10ms), default: 720 ms
4622  * @param min_ce_length (unit: 0.625ms), default: 10 ms
4623  * @param max_ce_length (unit: 0.625ms), default: 30 ms
4624  */
4625 
4626 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
4627     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
4628     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
4629     hci_stack->le_connection_scan_interval = conn_scan_interval;
4630     hci_stack->le_connection_scan_window = conn_scan_window;
4631     hci_stack->le_connection_interval_min = conn_interval_min;
4632     hci_stack->le_connection_interval_max = conn_interval_max;
4633     hci_stack->le_connection_latency = conn_latency;
4634     hci_stack->le_supervision_timeout = supervision_timeout;
4635     hci_stack->le_minimum_ce_length = min_ce_length;
4636     hci_stack->le_maximum_ce_length = max_ce_length;
4637 }
4638 #endif
4639 
4640 /**
4641  * @brief Updates the connection parameters for a given LE connection
4642  * @param handle
4643  * @param conn_interval_min (unit: 1.25ms)
4644  * @param conn_interval_max (unit: 1.25ms)
4645  * @param conn_latency
4646  * @param supervision_timeout (unit: 10ms)
4647  * @returns 0 if ok
4648  */
4649 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4650     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4651     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4652     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4653     connection->le_conn_interval_min = conn_interval_min;
4654     connection->le_conn_interval_max = conn_interval_max;
4655     connection->le_conn_latency = conn_latency;
4656     connection->le_supervision_timeout = supervision_timeout;
4657     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
4658     hci_run();
4659     return 0;
4660 }
4661 
4662 /**
4663  * @brief Request an update of the connection parameter for a given LE connection
4664  * @param handle
4665  * @param conn_interval_min (unit: 1.25ms)
4666  * @param conn_interval_max (unit: 1.25ms)
4667  * @param conn_latency
4668  * @param supervision_timeout (unit: 10ms)
4669  * @returns 0 if ok
4670  */
4671 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4672     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4673     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4674     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4675     connection->le_conn_interval_min = conn_interval_min;
4676     connection->le_conn_interval_max = conn_interval_max;
4677     connection->le_conn_latency = conn_latency;
4678     connection->le_supervision_timeout = supervision_timeout;
4679     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
4680     hci_run();
4681     return 0;
4682 }
4683 
4684 #ifdef ENABLE_LE_PERIPHERAL
4685 
4686 static void gap_advertisments_changed(void){
4687     // disable advertisements before updating adv, scan data, or adv params
4688     if (hci_stack->le_advertisements_active){
4689         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
4690     }
4691     hci_run();
4692 }
4693 
4694 /**
4695  * @brief Set Advertisement Data
4696  * @param advertising_data_length
4697  * @param advertising_data (max 31 octets)
4698  * @note data is not copied, pointer has to stay valid
4699  */
4700 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
4701     hci_stack->le_advertisements_data_len = advertising_data_length;
4702     hci_stack->le_advertisements_data = advertising_data;
4703     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4704     gap_advertisments_changed();
4705 }
4706 
4707 /**
4708  * @brief Set Scan Response Data
4709  * @param advertising_data_length
4710  * @param advertising_data (max 31 octets)
4711  * @note data is not copied, pointer has to stay valid
4712  */
4713 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
4714     hci_stack->le_scan_response_data_len = scan_response_data_length;
4715     hci_stack->le_scan_response_data = scan_response_data;
4716     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4717     gap_advertisments_changed();
4718 }
4719 
4720 /**
4721  * @brief Set Advertisement Parameters
4722  * @param adv_int_min
4723  * @param adv_int_max
4724  * @param adv_type
4725  * @param direct_address_type
4726  * @param direct_address
4727  * @param channel_map
4728  * @param filter_policy
4729  *
4730  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
4731  */
4732  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4733     uint8_t direct_address_typ, bd_addr_t direct_address,
4734     uint8_t channel_map, uint8_t filter_policy) {
4735 
4736     hci_stack->le_advertisements_interval_min = adv_int_min;
4737     hci_stack->le_advertisements_interval_max = adv_int_max;
4738     hci_stack->le_advertisements_type = adv_type;
4739     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
4740     hci_stack->le_advertisements_channel_map = channel_map;
4741     hci_stack->le_advertisements_filter_policy = filter_policy;
4742     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
4743 
4744     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4745     gap_advertisments_changed();
4746  }
4747 
4748 /**
4749  * @brief Enable/Disable Advertisements
4750  * @param enabled
4751  */
4752 void gap_advertisements_enable(int enabled){
4753     hci_stack->le_advertisements_enabled = enabled;
4754     if (enabled && !hci_stack->le_advertisements_active){
4755         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
4756     }
4757     if (!enabled && hci_stack->le_advertisements_active){
4758         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
4759     }
4760     hci_run();
4761 }
4762 
4763 #endif
4764 
4765 void hci_le_set_own_address_type(uint8_t own_address_type){
4766     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
4767     if (own_address_type == hci_stack->le_own_addr_type) return;
4768     hci_stack->le_own_addr_type = own_address_type;
4769 
4770 #ifdef ENABLE_LE_PERIPHERAL
4771     // update advertisement parameters, too
4772     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4773     gap_advertisments_changed();
4774 #endif
4775 #ifdef ENABLE_LE_CENTRAL
4776     // note: we don't update scan parameters or modify ongoing connection attempts
4777 #endif
4778 }
4779 
4780 #endif
4781 
4782 uint8_t gap_disconnect(hci_con_handle_t handle){
4783     hci_connection_t * conn = hci_connection_for_handle(handle);
4784     if (!conn){
4785         hci_emit_disconnection_complete(handle, 0);
4786         return 0;
4787     }
4788     // ignore if already disconnected
4789     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
4790         return 0;
4791     }
4792     conn->state = SEND_DISCONNECT;
4793     hci_run();
4794     return 0;
4795 }
4796 
4797 int gap_read_rssi(hci_con_handle_t con_handle){
4798     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
4799     if (hci_connection == NULL) return 0;
4800     connectionSetAuthenticationFlags(hci_connection, READ_RSSI);
4801     hci_run();
4802     return 1;
4803 }
4804 
4805 /**
4806  * @brief Get connection type
4807  * @param con_handle
4808  * @result connection_type
4809  */
4810 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
4811     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4812     if (!conn) return GAP_CONNECTION_INVALID;
4813     switch (conn->address_type){
4814         case BD_ADDR_TYPE_LE_PUBLIC:
4815         case BD_ADDR_TYPE_LE_RANDOM:
4816             return GAP_CONNECTION_LE;
4817         case BD_ADDR_TYPE_SCO:
4818             return GAP_CONNECTION_SCO;
4819         case BD_ADDR_TYPE_CLASSIC:
4820             return GAP_CONNECTION_ACL;
4821         default:
4822             return GAP_CONNECTION_INVALID;
4823     }
4824 }
4825 
4826 #ifdef ENABLE_BLE
4827 
4828 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){
4829     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4830     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4831 
4832     conn->le_phy_update_all_phys    = all_phys;
4833     conn->le_phy_update_tx_phys     = tx_phys;
4834     conn->le_phy_update_rx_phys     = rx_phys;
4835     conn->le_phy_update_phy_options = phy_options;
4836 
4837     hci_run();
4838 
4839     return 0;
4840 }
4841 
4842 #ifdef ENABLE_LE_CENTRAL
4843 /**
4844  * @brief Auto Connection Establishment - Start Connecting to device
4845  * @param address_typ
4846  * @param address
4847  * @returns 0 if ok
4848  */
4849 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
4850     // check capacity
4851     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
4852     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
4853     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
4854     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
4855     entry->address_type = address_type;
4856     memcpy(entry->address, address, 6);
4857     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4858     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
4859     hci_run();
4860     return 0;
4861 }
4862 
4863 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
4864     btstack_linked_list_iterator_t it;
4865     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4866     while (btstack_linked_list_iterator_has_next(&it)){
4867         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4868         if (entry->address_type != address_type) continue;
4869         if (memcmp(entry->address, address, 6) != 0) continue;
4870         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4871             // remove from controller if already present
4872             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4873             continue;
4874         }
4875         // direclty remove entry from whitelist
4876         btstack_linked_list_iterator_remove(&it);
4877         btstack_memory_whitelist_entry_free(entry);
4878     }
4879 }
4880 
4881 /**
4882  * @brief Auto Connection Establishment - Stop Connecting to device
4883  * @param address_typ
4884  * @param address
4885  * @returns 0 if ok
4886  */
4887 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
4888     hci_remove_from_whitelist(address_type, address);
4889     hci_run();
4890     return 0;
4891 }
4892 
4893 /**
4894  * @brief Auto Connection Establishment - Stop everything
4895  * @note  Convenience function to stop all active auto connection attempts
4896  */
4897 void gap_auto_connection_stop_all(void){
4898     btstack_linked_list_iterator_t it;
4899     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4900     while (btstack_linked_list_iterator_has_next(&it)){
4901         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4902         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4903             // remove from controller if already present
4904             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4905             continue;
4906         }
4907         // directly remove entry from whitelist
4908         btstack_linked_list_iterator_remove(&it);
4909         btstack_memory_whitelist_entry_free(entry);
4910     }
4911     hci_run();
4912 }
4913 
4914 uint16_t gap_le_connection_interval(hci_con_handle_t connection_handle){
4915     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4916     if (!conn) return 0;
4917     return conn->le_connection_interval;
4918 }
4919 #endif
4920 #endif
4921 
4922 #ifdef ENABLE_CLASSIC
4923 /**
4924  * @brief Set Extended Inquiry Response data
4925  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
4926  * @note has to be done before stack starts up
4927  */
4928 void gap_set_extended_inquiry_response(const uint8_t * data){
4929     hci_stack->eir_data = data;
4930 }
4931 
4932 /**
4933  * @brief Start GAP Classic Inquiry
4934  * @param duration in 1.28s units
4935  * @return 0 if ok
4936  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
4937  */
4938 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
4939     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
4940     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4941     if (duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN || duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX){
4942         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
4943     }
4944     hci_stack->inquiry_state = duration_in_1280ms_units;
4945     hci_run();
4946     return 0;
4947 }
4948 
4949 /**
4950  * @brief Stop GAP Classic Inquiry
4951  * @returns 0 if ok
4952  */
4953 int gap_inquiry_stop(void){
4954     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX) {
4955         // emit inquiry complete event, before it even started
4956         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
4957         hci_emit_event(event, sizeof(event), 1);
4958         return 0;
4959     }
4960     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
4961     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
4962     hci_run();
4963     return 0;
4964 }
4965 
4966 
4967 /**
4968  * @brief Remote Name Request
4969  * @param addr
4970  * @param page_scan_repetition_mode
4971  * @param clock_offset only used when bit 15 is set
4972  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
4973  */
4974 int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
4975     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4976     memcpy(hci_stack->remote_name_addr, addr, 6);
4977     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
4978     hci_stack->remote_name_clock_offset = clock_offset;
4979     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
4980     hci_run();
4981     return 0;
4982 }
4983 
4984 static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){
4985     hci_stack->gap_pairing_state = state;
4986     memcpy(hci_stack->gap_pairing_addr, addr, 6);
4987     hci_run();
4988     return 0;
4989 }
4990 
4991 /**
4992  * @brief Legacy Pairing Pin Code Response
4993  * @param addr
4994  * @param pin
4995  * @return 0 if ok
4996  */
4997 int gap_pin_code_response(bd_addr_t addr, const char * pin){
4998     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4999     hci_stack->gap_pairing_input.gap_pairing_pin = pin;
5000     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
5001 }
5002 
5003 /**
5004  * @brief Abort Legacy Pairing
5005  * @param addr
5006  * @param pin
5007  * @return 0 if ok
5008  */
5009 int gap_pin_code_negative(bd_addr_t addr){
5010     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5011     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
5012 }
5013 
5014 /**
5015  * @brief SSP Passkey Response
5016  * @param addr
5017  * @param passkey
5018  * @return 0 if ok
5019  */
5020 int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){
5021     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5022     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
5023     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
5024 }
5025 
5026 /**
5027  * @brief Abort SSP Passkey Entry/Pairing
5028  * @param addr
5029  * @param pin
5030  * @return 0 if ok
5031  */
5032 int gap_ssp_passkey_negative(bd_addr_t addr){
5033     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5034     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
5035 }
5036 
5037 /**
5038  * @brief Accept SSP Numeric Comparison
5039  * @param addr
5040  * @param passkey
5041  * @return 0 if ok
5042  */
5043 int gap_ssp_confirmation_response(bd_addr_t addr){
5044     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5045     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
5046 }
5047 
5048 /**
5049  * @brief Abort SSP Numeric Comparison/Pairing
5050  * @param addr
5051  * @param pin
5052  * @return 0 if ok
5053  */
5054 int gap_ssp_confirmation_negative(bd_addr_t addr){
5055     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5056     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
5057 }
5058 
5059 /**
5060  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
5061  * @param inquiry_mode see bluetooth_defines.h
5062  */
5063 void hci_set_inquiry_mode(inquiry_mode_t mode){
5064     hci_stack->inquiry_mode = mode;
5065 }
5066 
5067 /**
5068  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
5069  */
5070 void hci_set_sco_voice_setting(uint16_t voice_setting){
5071     hci_stack->sco_voice_setting = voice_setting;
5072 }
5073 
5074 /**
5075  * @brief Get SCO Voice Setting
5076  * @return current voice setting
5077  */
5078 uint16_t hci_get_sco_voice_setting(void){
5079     return hci_stack->sco_voice_setting;
5080 }
5081 
5082 static int hci_have_usb_transport(void){
5083     if (!hci_stack->hci_transport) return 0;
5084     const char * transport_name = hci_stack->hci_transport->name;
5085     if (!transport_name) return 0;
5086     return (transport_name[0] == 'H') && (transport_name[1] == '2');
5087 }
5088 
5089 /** @brief Get SCO packet length for current SCO Voice setting
5090  *  @note  Using SCO packets of the exact length is required for USB transfer
5091  *  @return Length of SCO packets in bytes (not audio frames)
5092  */
5093 int hci_get_sco_packet_length(void){
5094     int sco_packet_length = 0;
5095 
5096 #ifdef ENABLE_SCO_OVER_HCI
5097 
5098     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
5099     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
5100 
5101     if (hci_have_usb_transport()){
5102         // see Core Spec for H2 USB Transfer.
5103         // 3 byte SCO header + 24 bytes per connection
5104         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
5105         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
5106     } else {
5107         // 3 byte SCO header + SCO packet size over the air (60 bytes)
5108         sco_packet_length = 3 + 60 * multiplier;
5109         // assert that it still fits inside an SCO buffer
5110         if (sco_packet_length > hci_stack->sco_data_packet_length){
5111             sco_packet_length = 3 + 60;
5112         }
5113     }
5114 #endif
5115     return sco_packet_length;
5116 }
5117 
5118 /**
5119 * @brief Sets the master/slave policy
5120 * @param policy (0: attempt to become master, 1: let connecting device decide)
5121 */
5122 void hci_set_master_slave_policy(uint8_t policy){
5123     hci_stack->master_slave_policy = policy;
5124 }
5125 
5126 #endif
5127 
5128 HCI_STATE hci_get_state(void){
5129     return hci_stack->state;
5130 }
5131 
5132 #ifdef ENABLE_CLASSIC
5133 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr)){
5134     hci_stack->gap_classic_accept_callback = accept_callback;
5135 }
5136 #endif
5137 
5138 /**
5139  * @brief Set callback for Bluetooth Hardware Error
5140  */
5141 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
5142     hci_stack->hardware_error_callback = fn;
5143 }
5144 
5145 void hci_disconnect_all(void){
5146     btstack_linked_list_iterator_t it;
5147     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
5148     while (btstack_linked_list_iterator_has_next(&it)){
5149         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
5150         if (con->state == SENT_DISCONNECT) continue;
5151         con->state = SEND_DISCONNECT;
5152     }
5153     hci_run();
5154 }
5155 
5156 uint16_t hci_get_manufacturer(void){
5157     return hci_stack->manufacturer;
5158 }
5159 
5160 #ifdef ENABLE_BLE
5161 
5162 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
5163     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
5164     if (!hci_con) return NULL;
5165     return &hci_con->sm_connection;
5166 }
5167 
5168 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
5169 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
5170 
5171 int gap_encryption_key_size(hci_con_handle_t con_handle){
5172     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5173     if (hci_connection == NULL) return 0;
5174     if (hci_is_le_connection(hci_connection)){
5175         sm_connection_t * sm_conn = &hci_connection->sm_connection;
5176         if (sm_conn->sm_connection_encrypted) {
5177             return sm_conn->sm_actual_encryption_key_size;
5178         }
5179     }
5180 #ifdef ENABLE_CLASSIC
5181     else {
5182         if ((hci_connection->authentication_flags & CONNECTION_ENCRYPTED)){
5183             return hci_connection->encryption_key_size;
5184         }
5185     }
5186 #endif
5187     return 0;
5188 }
5189 
5190 int gap_authenticated(hci_con_handle_t con_handle){
5191     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5192     if (hci_connection == NULL) return 0;
5193 
5194     switch (hci_connection->address_type){
5195         case BD_ADDR_TYPE_LE_PUBLIC:
5196         case BD_ADDR_TYPE_LE_RANDOM:
5197             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
5198             return hci_connection->sm_connection.sm_connection_authenticated;
5199 #ifdef ENABLE_CLASSIC
5200         case BD_ADDR_TYPE_SCO:
5201         case BD_ADDR_TYPE_CLASSIC:
5202             return gap_authenticated_for_link_key_type(hci_connection->link_key_type);
5203 #endif
5204         default:
5205             return 0;
5206     }
5207 }
5208 
5209 int gap_secure_connection(hci_con_handle_t con_handle){
5210     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5211     if (hci_connection == NULL) return 0;
5212 
5213     switch (hci_connection->address_type){
5214         case BD_ADDR_TYPE_LE_PUBLIC:
5215         case BD_ADDR_TYPE_LE_RANDOM:
5216             if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated
5217             return hci_connection->sm_connection.sm_connection_sc;
5218 #ifdef ENABLE_CLASSIC
5219         case BD_ADDR_TYPE_SCO:
5220         case BD_ADDR_TYPE_CLASSIC:
5221             return gap_secure_connection_for_link_key_type(hci_connection->link_key_type);
5222 #endif
5223         default:
5224             return 0;
5225     }
5226 }
5227 
5228 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
5229     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5230     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
5231     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
5232     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
5233     return sm_conn->sm_connection_authorization_state;
5234 }
5235 #endif
5236 
5237 #ifdef ENABLE_CLASSIC
5238 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){
5239     hci_connection_t * conn = hci_connection_for_handle(con_handle);
5240     if (!conn) return GAP_CONNECTION_INVALID;
5241     conn->sniff_min_interval = sniff_min_interval;
5242     conn->sniff_max_interval = sniff_max_interval;
5243     conn->sniff_attempt = sniff_attempt;
5244     conn->sniff_timeout = sniff_timeout;
5245     hci_run();
5246     return 0;
5247 }
5248 
5249 /**
5250  * @brief Exit Sniff mode
5251  * @param con_handle
5252  @ @return 0 if ok
5253  */
5254 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
5255     hci_connection_t * conn = hci_connection_for_handle(con_handle);
5256     if (!conn) return GAP_CONNECTION_INVALID;
5257     conn->sniff_min_interval = 0xffff;
5258     hci_run();
5259     return 0;
5260 }
5261 #endif
5262 
5263 void hci_halting_defer(void){
5264     if (hci_stack->state != HCI_STATE_HALTING) return;
5265     switch (hci_stack->substate){
5266         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
5267         case HCI_HALTING_CLOSE:
5268             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
5269             break;
5270         default:
5271             break;
5272     }
5273 }
5274