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