xref: /btstack/src/hci.c (revision 3b1c4bce5257d383a8bc3295d210cf91e1bcedc1)
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 /*
39  *  hci.c
40  *
41  *  Created by Matthias Ringwald on 4/29/09.
42  *
43  */
44 
45 #include "btstack_config.h"
46 
47 
48 #ifdef ENABLE_CLASSIC
49 #ifdef HAVE_EMBEDDED_TICK
50 #include "btstack_run_loop_embedded.h"
51 #endif
52 #endif
53 
54 #ifdef HAVE_PLATFORM_IPHONE_OS
55 #include "../port/ios/src/btstack_control_iphone.h"
56 #endif
57 
58 #ifdef ENABLE_BLE
59 #include "gap.h"
60 #endif
61 
62 #include <stdarg.h>
63 #include <string.h>
64 #include <stdio.h>
65 #include <inttypes.h>
66 
67 #include "btstack_debug.h"
68 #include "btstack_event.h"
69 #include "btstack_linked_list.h"
70 #include "btstack_memory.h"
71 #include "gap.h"
72 #include "hci.h"
73 #include "hci_cmd.h"
74 #include "hci_dump.h"
75 
76 
77 #define HCI_CONNECTION_TIMEOUT_MS 10000
78 #define HCI_RESET_RESEND_TIMEOUT_MS 200
79 
80 // prototypes
81 #ifdef ENABLE_CLASSIC
82 static void hci_update_scan_enable(void);
83 static void hci_emit_discoverable_enabled(uint8_t enabled);
84 static int  hci_local_ssp_activated(void);
85 static int  hci_remote_ssp_supported(hci_con_handle_t con_handle);
86 static void hci_notify_if_sco_can_send_now(void);
87 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
88 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
89 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
90 static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
91 static void hci_connection_timestamp(hci_connection_t *connection);
92 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
93 #endif
94 static int  hci_power_control_on(void);
95 static void hci_power_control_off(void);
96 static void hci_state_reset(void);
97 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
98 static void hci_emit_nr_connections_changed(void);
99 static void hci_emit_hci_open_failed(void);
100 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
101 static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
102 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
103 static void hci_run(void);
104 static int  hci_is_le_connection(hci_connection_t * connection);
105 static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
106 
107 #ifdef ENABLE_BLE
108 #ifdef ENABLE_LE_CENTRAL
109 // called from test/ble_client/advertising_data_parser.c
110 void le_handle_advertisement_report(uint8_t *packet, int size);
111 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address);
112 #endif
113 #endif
114 
115 // the STACK is here
116 #ifndef HAVE_MALLOC
117 static hci_stack_t   hci_stack_static;
118 #endif
119 static hci_stack_t * hci_stack = NULL;
120 
121 #ifdef ENABLE_CLASSIC
122 // test helper
123 static uint8_t disable_l2cap_timeouts = 0;
124 #endif
125 
126 /**
127  * create connection for given address
128  *
129  * @return connection OR NULL, if no memory left
130  */
131 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
132     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
133     hci_connection_t * conn = btstack_memory_hci_connection_get();
134     if (!conn) return NULL;
135     memset(conn, 0, sizeof(hci_connection_t));
136     bd_addr_copy(conn->address, addr);
137     conn->address_type = addr_type;
138     conn->con_handle = 0xffff;
139     conn->authentication_flags = AUTH_FLAGS_NONE;
140     conn->bonding_flags = 0;
141     conn->requested_security_level = LEVEL_0;
142 #ifdef ENABLE_CLASSIC
143     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
144     btstack_run_loop_set_timer_context(&conn->timeout, conn);
145     hci_connection_timestamp(conn);
146 #endif
147     conn->acl_recombination_length = 0;
148     conn->acl_recombination_pos = 0;
149     conn->num_acl_packets_sent = 0;
150     conn->num_sco_packets_sent = 0;
151     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
152     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
153     return conn;
154 }
155 
156 
157 /**
158  * get le connection parameter range
159 *
160  * @return le connection parameter range struct
161  */
162 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
163     *range = hci_stack->le_connection_parameter_range;
164 }
165 
166 /**
167  * set le connection parameter range
168  *
169  */
170 
171 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
172     hci_stack->le_connection_parameter_range = *range;
173 }
174 
175 /**
176  * get hci connections iterator
177  *
178  * @return hci connections iterator
179  */
180 
181 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
182     btstack_linked_list_iterator_init(it, &hci_stack->connections);
183 }
184 
185 /**
186  * get connection for a given handle
187  *
188  * @return connection OR NULL, if not found
189  */
190 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
191     btstack_linked_list_iterator_t it;
192     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
193     while (btstack_linked_list_iterator_has_next(&it)){
194         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
195         if ( item->con_handle == con_handle ) {
196             return item;
197         }
198     }
199     return NULL;
200 }
201 
202 /**
203  * get connection for given address
204  *
205  * @return connection OR NULL, if not found
206  */
207 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t  addr, bd_addr_type_t addr_type){
208     btstack_linked_list_iterator_t it;
209     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
210     while (btstack_linked_list_iterator_has_next(&it)){
211         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
212         if (connection->address_type != addr_type)  continue;
213         if (memcmp(addr, connection->address, 6) != 0) continue;
214         return connection;
215     }
216     return NULL;
217 }
218 
219 
220 #ifdef ENABLE_CLASSIC
221 
222 #ifdef ENABLE_SCO_OVER_HCI
223 static int hci_number_sco_connections(void){
224     int connections = 0;
225     btstack_linked_list_iterator_t it;
226     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
227     while (btstack_linked_list_iterator_has_next(&it)){
228         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
229         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
230         connections++;
231     }
232     return connections;
233 }
234 #endif
235 
236 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
237     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
238 #ifdef HAVE_EMBEDDED_TICK
239     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
240         // connections might be timed out
241         hci_emit_l2cap_check_timeout(connection);
242     }
243 #else
244     if (btstack_run_loop_get_time_ms() > connection->timestamp + HCI_CONNECTION_TIMEOUT_MS){
245         // connections might be timed out
246         hci_emit_l2cap_check_timeout(connection);
247     }
248 #endif
249 }
250 
251 static void hci_connection_timestamp(hci_connection_t *connection){
252 #ifdef HAVE_EMBEDDED_TICK
253     connection->timestamp = btstack_run_loop_embedded_get_ticks();
254 #else
255     connection->timestamp = btstack_run_loop_get_time_ms();
256 #endif
257 }
258 
259 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
260     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
261 }
262 
263 
264 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
265     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
266 }
267 
268 /**
269  * add authentication flags and reset timer
270  * @note: assumes classic connection
271  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
272  */
273 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
274     bd_addr_t addr;
275     reverse_bd_addr(bd_addr, addr);
276     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
277     if (conn) {
278         connectionSetAuthenticationFlags(conn, flags);
279         hci_connection_timestamp(conn);
280     }
281 }
282 
283 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
284     hci_connection_t * conn = hci_connection_for_handle(handle);
285     if (!conn) return 0;
286     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
287     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
288     return 0;
289 }
290 
291 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
292     if (!hci_stack->link_key_db) return;
293     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
294     hci_stack->link_key_db->delete_link_key(addr);
295 }
296 
297 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
298     if (!hci_stack->link_key_db) return;
299     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
300     hci_stack->link_key_db->put_link_key(addr, link_key, type);
301 }
302 #endif
303 
304 static int hci_is_le_connection(hci_connection_t * connection){
305     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
306     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
307 }
308 
309 /**
310  * count connections
311  */
312 static int nr_hci_connections(void){
313     int count = 0;
314     btstack_linked_item_t *it;
315     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
316     return count;
317 }
318 
319 static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
320 
321     unsigned int num_packets_sent_classic = 0;
322     unsigned int num_packets_sent_le = 0;
323 
324     btstack_linked_item_t *it;
325     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
326         hci_connection_t * connection = (hci_connection_t *) it;
327         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
328             num_packets_sent_classic += connection->num_acl_packets_sent;
329         } else {
330             num_packets_sent_le += connection->num_acl_packets_sent;
331         }
332     }
333     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
334     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
335     int free_slots_le = 0;
336 
337     if (free_slots_classic < 0){
338         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);
339         return 0;
340     }
341 
342     if (hci_stack->le_acl_packets_total_num){
343         // if we have LE slots, they are used
344         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
345         if (free_slots_le < 0){
346             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);
347             return 0;
348         }
349     } else {
350         // otherwise, classic slots are used for LE, too
351         free_slots_classic -= num_packets_sent_le;
352         if (free_slots_classic < 0){
353             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);
354             return 0;
355         }
356     }
357 
358     switch (address_type){
359         case BD_ADDR_TYPE_UNKNOWN:
360             log_error("hci_number_free_acl_slots: unknown address type");
361             return 0;
362 
363         case BD_ADDR_TYPE_CLASSIC:
364             return free_slots_classic;
365 
366         default:
367            if (hci_stack->le_acl_packets_total_num){
368                return free_slots_le;
369            }
370            return free_slots_classic;
371     }
372 }
373 
374 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
375     // get connection type
376     hci_connection_t * connection = hci_connection_for_handle(con_handle);
377     if (!connection){
378         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
379         return 0;
380     }
381     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
382 }
383 
384 #ifdef ENABLE_CLASSIC
385 static int hci_number_free_sco_slots(void){
386     unsigned int num_sco_packets_sent  = 0;
387     btstack_linked_item_t *it;
388     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
389         hci_connection_t * connection = (hci_connection_t *) it;
390         num_sco_packets_sent += connection->num_sco_packets_sent;
391     }
392     if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
393         log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
394         return 0;
395     }
396     // log_info("hci_number_free_sco_slots u", handle, num_sco_packets_sent);
397     return hci_stack->sco_packets_total_num - num_sco_packets_sent;
398 }
399 #endif
400 
401 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
402 int hci_can_send_command_packet_now(void){
403     if (hci_stack->hci_packet_buffer_reserved) return 0;
404 
405     // check for async hci transport implementations
406     if (hci_stack->hci_transport->can_send_packet_now){
407         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
408             return 0;
409         }
410     }
411 
412     return hci_stack->num_cmd_packets > 0;
413 }
414 
415 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
416     // check for async hci transport implementations
417     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
418     return hci_stack->hci_transport->can_send_packet_now(packet_type);
419 }
420 
421 static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
422     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
423     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
424 }
425 
426 int hci_can_send_acl_le_packet_now(void){
427     if (hci_stack->hci_packet_buffer_reserved) return 0;
428     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
429 }
430 
431 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
432     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
433     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
434 }
435 
436 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
437     if (hci_stack->hci_packet_buffer_reserved) return 0;
438     return hci_can_send_prepared_acl_packet_now(con_handle);
439 }
440 
441 #ifdef ENABLE_CLASSIC
442 int hci_can_send_acl_classic_packet_now(void){
443     if (hci_stack->hci_packet_buffer_reserved) return 0;
444     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_CLASSIC);
445 }
446 
447 int hci_can_send_prepared_sco_packet_now(void){
448     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
449     if (!hci_stack->synchronous_flow_control_enabled) return 1;
450     return hci_number_free_sco_slots() > 0;
451 }
452 
453 int hci_can_send_sco_packet_now(void){
454     if (hci_stack->hci_packet_buffer_reserved) return 0;
455     return hci_can_send_prepared_sco_packet_now();
456 }
457 
458 void hci_request_sco_can_send_now_event(void){
459     hci_stack->sco_waiting_for_can_send_now = 1;
460     hci_notify_if_sco_can_send_now();
461 }
462 #endif
463 
464 // used for internal checks in l2cap.c
465 int hci_is_packet_buffer_reserved(void){
466     return hci_stack->hci_packet_buffer_reserved;
467 }
468 
469 // reserves outgoing packet buffer. @returns 1 if successful
470 int hci_reserve_packet_buffer(void){
471     if (hci_stack->hci_packet_buffer_reserved) {
472         log_error("hci_reserve_packet_buffer called but buffer already reserved");
473         return 0;
474     }
475     hci_stack->hci_packet_buffer_reserved = 1;
476     return 1;
477 }
478 
479 void hci_release_packet_buffer(void){
480     hci_stack->hci_packet_buffer_reserved = 0;
481 }
482 
483 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
484 static int hci_transport_synchronous(void){
485     return hci_stack->hci_transport->can_send_packet_now == NULL;
486 }
487 
488 static int hci_send_acl_packet_fragments(hci_connection_t *connection){
489 
490     // 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);
491 
492     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
493     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
494     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
495         max_acl_data_packet_length = hci_stack->le_data_packets_length;
496     }
497 
498     // testing: reduce buffer to minimum
499     // max_acl_data_packet_length = 52;
500 
501     log_debug("hci_send_acl_packet_fragments entered");
502 
503     int err;
504     // multiple packets could be send on a synchronous HCI transport
505     while (1){
506 
507         log_debug("hci_send_acl_packet_fragments loop entered");
508 
509         // get current data
510         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
511         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
512         int more_fragments = 0;
513 
514         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
515         if (current_acl_data_packet_length > max_acl_data_packet_length){
516             more_fragments = 1;
517             current_acl_data_packet_length = max_acl_data_packet_length;
518         }
519 
520         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
521         if (acl_header_pos > 0){
522             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
523             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
524             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
525         }
526 
527         // update header len
528         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
529 
530         // count packet
531         connection->num_acl_packets_sent++;
532         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", more_fragments);
533 
534         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
535         if (more_fragments){
536             // update start of next fragment to send
537             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
538         } else {
539             // done
540             hci_stack->acl_fragmentation_pos = 0;
541             hci_stack->acl_fragmentation_total_size = 0;
542         }
543 
544         // send packet
545         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
546         const int size = current_acl_data_packet_length + 4;
547         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
548         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
549 
550         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", more_fragments);
551 
552         // done yet?
553         if (!more_fragments) break;
554 
555         // can send more?
556         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
557     }
558 
559     log_debug("hci_send_acl_packet_fragments loop over");
560 
561     // release buffer now for synchronous transport
562     if (hci_transport_synchronous()){
563         hci_release_packet_buffer();
564         // notify upper stack that it might be possible to send again
565         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
566         hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
567     }
568 
569     return err;
570 }
571 
572 // pre: caller has reserved the packet buffer
573 int hci_send_acl_packet_buffer(int size){
574 
575     // log_info("hci_send_acl_packet_buffer size %u", size);
576 
577     if (!hci_stack->hci_packet_buffer_reserved) {
578         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
579         return 0;
580     }
581 
582     uint8_t * packet = hci_stack->hci_packet_buffer;
583     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
584 
585     // check for free places on Bluetooth module
586     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
587         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
588         hci_release_packet_buffer();
589         return BTSTACK_ACL_BUFFERS_FULL;
590     }
591 
592     hci_connection_t *connection = hci_connection_for_handle( con_handle);
593     if (!connection) {
594         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
595         hci_release_packet_buffer();
596         return 0;
597     }
598 
599 #ifdef ENABLE_CLASSIC
600     hci_connection_timestamp(connection);
601 #endif
602 
603     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
604 
605     // setup data
606     hci_stack->acl_fragmentation_total_size = size;
607     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
608 
609     return hci_send_acl_packet_fragments(connection);
610 }
611 
612 #ifdef ENABLE_CLASSIC
613 // pre: caller has reserved the packet buffer
614 int hci_send_sco_packet_buffer(int size){
615 
616     // log_info("hci_send_acl_packet_buffer size %u", size);
617 
618     if (!hci_stack->hci_packet_buffer_reserved) {
619         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
620         return 0;
621     }
622 
623     uint8_t * packet = hci_stack->hci_packet_buffer;
624 
625     // skip checks in loopback mode
626     if (!hci_stack->loopback_mode){
627         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
628 
629         // check for free places on Bluetooth module
630         if (!hci_can_send_prepared_sco_packet_now()) {
631             log_error("hci_send_sco_packet_buffer called but no free ACL buffers on controller");
632             hci_release_packet_buffer();
633             return BTSTACK_ACL_BUFFERS_FULL;
634         }
635 
636         // track send packet in connection struct
637         hci_connection_t *connection = hci_connection_for_handle( con_handle);
638         if (!connection) {
639             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
640             hci_release_packet_buffer();
641             return 0;
642         }
643         connection->num_sco_packets_sent++;
644     }
645 
646     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
647     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
648 
649     if (hci_transport_synchronous()){
650         hci_release_packet_buffer();
651         // notify upper stack that it might be possible to send again
652         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
653         hci_emit_event(&event[0], sizeof(event), 0);    // don't dump
654     }
655 
656     return err;
657 }
658 #endif
659 
660 static void acl_handler(uint8_t *packet, int size){
661 
662     // log_info("acl_handler: size %u", size);
663 
664     // get info
665     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
666     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
667     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
668     uint16_t acl_length         = READ_ACL_LENGTH(packet);
669 
670     // ignore non-registered handle
671     if (!conn){
672         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
673         return;
674     }
675 
676     // assert packet is complete
677     if (acl_length + 4 != size){
678         log_error("hci.c: acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
679         return;
680     }
681 
682 #ifdef ENABLE_CLASSIC
683     // update idle timestamp
684     hci_connection_timestamp(conn);
685 #endif
686 
687     // handle different packet types
688     switch (acl_flags & 0x03) {
689 
690         case 0x01: // continuation fragment
691 
692             // sanity checks
693             if (conn->acl_recombination_pos == 0) {
694                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
695                 return;
696             }
697             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
698                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
699                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
700                 conn->acl_recombination_pos = 0;
701                 return;
702             }
703 
704             // append fragment payload (header already stored)
705             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
706             conn->acl_recombination_pos += acl_length;
707 
708             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
709             //        conn->acl_recombination_pos, conn->acl_recombination_length);
710 
711             // forward complete L2CAP packet if complete.
712             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
713                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
714                 // reset recombination buffer
715                 conn->acl_recombination_length = 0;
716                 conn->acl_recombination_pos = 0;
717             }
718             break;
719 
720         case 0x02: { // first fragment
721 
722             // sanity check
723             if (conn->acl_recombination_pos) {
724                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
725                 conn->acl_recombination_pos = 0;
726             }
727 
728             // peek into L2CAP packet!
729             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
730 
731             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
732 
733             // compare fragment size to L2CAP packet size
734             if (acl_length >= l2cap_length + 4){
735                 // forward fragment as L2CAP packet
736                 hci_emit_acl_packet(packet, acl_length + 4);
737             } else {
738 
739                 if (acl_length > HCI_ACL_BUFFER_SIZE){
740                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
741                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
742                     return;
743                 }
744 
745                 // store first fragment and tweak acl length for complete package
746                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
747                 conn->acl_recombination_pos    = acl_length + 4;
748                 conn->acl_recombination_length = l2cap_length;
749                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
750             }
751             break;
752 
753         }
754         default:
755             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
756             return;
757     }
758 
759     // execute main loop
760     hci_run();
761 }
762 
763 static void hci_shutdown_connection(hci_connection_t *conn){
764     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
765 
766 #ifdef ENABLE_SCO_OVER_HCI
767     int addr_type = conn->address_type;
768 #endif
769 
770     btstack_run_loop_remove_timer(&conn->timeout);
771 
772     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
773     btstack_memory_hci_connection_free( conn );
774 
775     // now it's gone
776     hci_emit_nr_connections_changed();
777 
778 #ifdef ENABLE_SCO_OVER_HCI
779     // update SCO
780     if (addr_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
781         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
782     }
783 #endif
784 }
785 
786 #ifdef ENABLE_CLASSIC
787 
788 static const uint16_t packet_type_sizes[] = {
789     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
790     HCI_ACL_DH1_SIZE, 0, 0, 0,
791     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
792     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
793 };
794 static const uint8_t  packet_type_feature_requirement_bit[] = {
795      0, // 3 slot packets
796      1, // 5 slot packets
797     25, // EDR 2 mpbs
798     26, // EDR 3 mbps
799     39, // 3 slot EDR packts
800     40, // 5 slot EDR packet
801 };
802 static const uint16_t packet_type_feature_packet_mask[] = {
803     0x0f00, // 3 slot packets
804     0xf000, // 5 slot packets
805     0x1102, // EDR 2 mpbs
806     0x2204, // EDR 3 mbps
807     0x0300, // 3 slot EDR packts
808     0x3000, // 5 slot EDR packet
809 };
810 
811 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
812     // enable packet types based on size
813     uint16_t packet_types = 0;
814     unsigned int i;
815     for (i=0;i<16;i++){
816         if (packet_type_sizes[i] == 0) continue;
817         if (packet_type_sizes[i] <= buffer_size){
818             packet_types |= 1 << i;
819         }
820     }
821     // disable packet types due to missing local supported features
822     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
823         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
824         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
825         if (feature_set) continue;
826         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
827         packet_types &= ~packet_type_feature_packet_mask[i];
828     }
829     // flip bits for "may not be used"
830     packet_types ^= 0x3306;
831     return packet_types;
832 }
833 
834 uint16_t hci_usable_acl_packet_types(void){
835     return hci_stack->packet_types;
836 }
837 #endif
838 
839 uint8_t* hci_get_outgoing_packet_buffer(void){
840     // hci packet buffer is >= acl data packet length
841     return hci_stack->hci_packet_buffer;
842 }
843 
844 uint16_t hci_max_acl_data_packet_length(void){
845     return hci_stack->acl_data_packet_length;
846 }
847 
848 #ifdef ENABLE_CLASSIC
849 int hci_extended_sco_link_supported(void){
850     // No. 31, byte 3, bit 7
851     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
852 }
853 #endif
854 
855 int hci_non_flushable_packet_boundary_flag_supported(void){
856     // No. 54, byte 6, bit 6
857     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
858 }
859 
860 static int gap_ssp_supported(void){
861     // No. 51, byte 6, bit 3
862     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
863 }
864 
865 static int hci_classic_supported(void){
866 #ifdef ENABLE_CLASSIC
867     // No. 37, byte 4, bit 5, = No BR/EDR Support
868     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
869 #else
870     return 0;
871 #endif
872 }
873 
874 static int hci_le_supported(void){
875 #ifdef ENABLE_BLE
876     // No. 37, byte 4, bit 6 = LE Supported (Controller)
877     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
878 #else
879     return 0;
880 #endif
881 }
882 
883 #ifdef ENABLE_BLE
884 
885 /**
886  * @brief Get addr type and address used for LE in Advertisements, Scan Responses,
887  */
888 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
889     *addr_type = hci_stack->le_own_addr_type;
890     if (hci_stack->le_own_addr_type){
891         memcpy(addr, hci_stack->le_random_address, 6);
892     } else {
893         memcpy(addr, hci_stack->local_bd_addr, 6);
894     }
895 }
896 
897 #ifdef ENABLE_LE_CENTRAL
898 void le_handle_advertisement_report(uint8_t *packet, int size){
899 
900     UNUSED(size);
901 
902     int offset = 3;
903     int num_reports = packet[offset];
904     offset += 1;
905 
906     int i;
907     // log_info("HCI: handle adv report with num reports: %d", num_reports);
908     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
909     for (i=0; i<num_reports;i++){
910         uint8_t data_length = packet[offset + 8];
911         uint8_t event_size = 10 + data_length;
912         int pos = 0;
913         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
914         event[pos++] = event_size;
915         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
916         offset += 8;
917         pos += 8;
918         event[pos++] = packet[offset + 1 + data_length]; // rssi
919         event[pos++] = packet[offset++]; //data_length;
920         memcpy(&event[pos], &packet[offset], data_length);
921         pos += data_length;
922         offset += data_length + 1; // rssi
923         hci_emit_event(event, pos, 1);
924     }
925 }
926 #endif
927 #endif
928 
929 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
930 
931 static uint32_t hci_transport_uart_get_main_baud_rate(void){
932     if (!hci_stack->config) return 0;
933     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
934     // Limit baud rate for Broadcom chipsets to 3 mbps
935     if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION && baud_rate > 3000000){
936         baud_rate = 3000000;
937     }
938     return baud_rate;
939 }
940 
941 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
942     UNUSED(ds);
943 
944     switch (hci_stack->substate){
945         case HCI_INIT_W4_SEND_RESET:
946             log_info("Resend HCI Reset");
947             hci_stack->substate = HCI_INIT_SEND_RESET;
948             hci_stack->num_cmd_packets = 1;
949             hci_run();
950             break;
951         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
952             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
953             if (hci_stack->hci_transport->reset_link){
954                 hci_stack->hci_transport->reset_link();
955             }
956             // no break - explicit fallthrough to HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT
957         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
958             log_info("Resend HCI Reset - CSR Warm Boot");
959             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
960             hci_stack->num_cmd_packets = 1;
961             hci_run();
962             break;
963         case HCI_INIT_W4_SEND_BAUD_CHANGE:
964             if (hci_stack->hci_transport->set_baudrate){
965                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
966                 log_info("Local baud rate change to %"PRIu32"(timeout handler)", baud_rate);
967                 hci_stack->hci_transport->set_baudrate(baud_rate);
968             }
969             // For CSR, HCI Reset is sent on new baud rate
970             if (hci_stack->manufacturer == COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
971                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
972                 hci_run();
973             }
974             break;
975         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
976             // otherwise continue
977             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
978             hci_send_cmd(&hci_read_local_supported_commands);
979             break;
980         default:
981             break;
982     }
983 }
984 #endif
985 
986 static void hci_initializing_next_state(void){
987     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
988 }
989 
990 // assumption: hci_can_send_command_packet_now() == true
991 static void hci_initializing_run(void){
992     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
993     switch (hci_stack->substate){
994         case HCI_INIT_SEND_RESET:
995             hci_state_reset();
996 
997 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
998             // prepare reset if command complete not received in 100ms
999             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1000             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1001             btstack_run_loop_add_timer(&hci_stack->timeout);
1002 #endif
1003             // send command
1004             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1005             hci_send_cmd(&hci_reset);
1006             break;
1007         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
1008             hci_send_cmd(&hci_read_local_version_information);
1009             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
1010             break;
1011         case HCI_INIT_SEND_READ_LOCAL_NAME:
1012             hci_send_cmd(&hci_read_local_name);
1013             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1014             break;
1015 
1016 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1017         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1018             hci_state_reset();
1019             // prepare reset if command complete not received in 100ms
1020             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1021             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1022             btstack_run_loop_add_timer(&hci_stack->timeout);
1023             // send command
1024             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1025             hci_send_cmd(&hci_reset);
1026             break;
1027         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
1028             hci_state_reset();
1029             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
1030             hci_send_cmd(&hci_reset);
1031             break;
1032         case HCI_INIT_SEND_BAUD_CHANGE: {
1033             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1034             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1035             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1036             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1037             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1038             // STLC25000D: baudrate change happens within 0.5 s after command was send,
1039             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
1040             if (hci_stack->manufacturer == COMPANY_ID_ST_MICROELECTRONICS){
1041                 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1042                 btstack_run_loop_add_timer(&hci_stack->timeout);
1043             }
1044             break;
1045         }
1046         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1047             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1048             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1049             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1050             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1051             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1052             break;
1053         }
1054         case HCI_INIT_CUSTOM_INIT:
1055             // Custom initialization
1056             if (hci_stack->chipset && hci_stack->chipset->next_command){
1057                 int valid_cmd = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
1058                 if (valid_cmd){
1059                     int size = 3 + hci_stack->hci_packet_buffer[2];
1060                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1061                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
1062                     switch (valid_cmd) {
1063                         case 1:
1064                         default:
1065                             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1066                             break;
1067                         case 2: // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1068                             log_info("CSR Warm Boot");
1069                             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1070                             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1071                             btstack_run_loop_add_timer(&hci_stack->timeout);
1072                             if (hci_stack->manufacturer == COMPANY_ID_CAMBRIDGE_SILICON_RADIO
1073                                 && hci_stack->config
1074                                 && hci_stack->chipset
1075                                 // && hci_stack->chipset->set_baudrate_command -- there's no such command
1076                                 && hci_stack->hci_transport->set_baudrate
1077                                 && hci_transport_uart_get_main_baud_rate()){
1078                                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1079                             } else {
1080                                hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1081                             }
1082                             break;
1083                     }
1084                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1085                     break;
1086                 }
1087                 log_info("Init script done");
1088 
1089                 // Init script download on Broadcom chipsets causes:
1090                 if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION){
1091                     // - baud rate to reset, restore UART baud rate if needed
1092                     int need_baud_change = hci_stack->config
1093                         && hci_stack->chipset
1094                         && hci_stack->chipset->set_baudrate_command
1095                         && hci_stack->hci_transport->set_baudrate
1096                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1097                     if (need_baud_change) {
1098                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1099                         log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate);
1100                         hci_stack->hci_transport->set_baudrate(baud_rate);
1101                     }
1102 
1103                     // - RTS will raise during update, but manual RTS/CTS in WICED port on RedBear Duo cannot handle this
1104                     //   -> Work around: wait a few milliseconds here.
1105                     log_info("BCM delay after init script");
1106                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1107                     btstack_run_loop_set_timer(&hci_stack->timeout, 10);
1108                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1109                     btstack_run_loop_add_timer(&hci_stack->timeout);
1110                     break;
1111                 }
1112                         }
1113             // otherwise continue
1114             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1115             hci_send_cmd(&hci_read_local_supported_commands);
1116             break;
1117         case HCI_INIT_SET_BD_ADDR:
1118             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1119             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1120             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1121             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1122             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1123             break;
1124 #endif
1125 
1126         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
1127             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
1128             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1129             hci_send_cmd(&hci_read_local_supported_commands);
1130             break;
1131         case HCI_INIT_READ_BD_ADDR:
1132             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
1133             hci_send_cmd(&hci_read_bd_addr);
1134             break;
1135         case HCI_INIT_READ_BUFFER_SIZE:
1136             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
1137             hci_send_cmd(&hci_read_buffer_size);
1138             break;
1139         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
1140             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
1141             hci_send_cmd(&hci_read_local_supported_features);
1142             break;
1143         case HCI_INIT_SET_EVENT_MASK:
1144             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
1145             if (hci_le_supported()){
1146                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1147             } else {
1148                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1149                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1150             }
1151             break;
1152 #ifdef ENABLE_CLASSIC
1153         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1154             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
1155             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1156             break;
1157         case HCI_INIT_WRITE_PAGE_TIMEOUT:
1158             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
1159             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
1160             break;
1161         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
1162             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
1163             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1164             break;
1165         case HCI_INIT_WRITE_LOCAL_NAME:
1166             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
1167             if (hci_stack->local_name){
1168                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
1169             } else {
1170                 char local_name[8+17+1];
1171                 // BTstack 11:22:33:44:55:66
1172                 memcpy(local_name, "BTstack ", 8);
1173                 memcpy(&local_name[8], bd_addr_to_str(hci_stack->local_bd_addr), 17);   // strlen(bd_addr_to_str(...)) = 17
1174                 local_name[8+17] = '\0';
1175                 log_info("---> Name %s", local_name);
1176                 hci_send_cmd(&hci_write_local_name, local_name);
1177             }
1178             break;
1179         case HCI_INIT_WRITE_EIR_DATA:
1180             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
1181             hci_send_cmd(&hci_write_extended_inquiry_response, 0, hci_stack->eir_data);
1182             break;
1183         case HCI_INIT_WRITE_INQUIRY_MODE:
1184             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
1185             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1186             break;
1187         case HCI_INIT_WRITE_SCAN_ENABLE:
1188             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1189             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
1190             break;
1191         // only sent if ENABLE_SCO_OVER_HCI is defined
1192         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1193             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1194             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1195             break;
1196         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1197             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1198             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1199             break;
1200         // only sent if ENABLE_SCO_OVER_HCI and manufacturer is Broadcom
1201         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1202             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1203             log_info("BCM: Route SCO data via HCI transport");
1204             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
1205             break;
1206 
1207 #endif
1208 #ifdef ENABLE_BLE
1209         // LE INIT
1210         case HCI_INIT_LE_READ_BUFFER_SIZE:
1211             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
1212             hci_send_cmd(&hci_le_read_buffer_size);
1213             break;
1214         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
1215             // LE Supported Host = 1, Simultaneous Host = 0
1216             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
1217             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1218             break;
1219 #ifdef ENABLE_LE_CENTRAL
1220         case HCI_INIT_READ_WHITE_LIST_SIZE:
1221             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
1222             hci_send_cmd(&hci_le_read_white_list_size);
1223             break;
1224         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1225             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, own address type, accept all advs
1226             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1227             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, hci_stack->le_own_addr_type, 0);
1228             break;
1229 #endif
1230 #endif
1231         default:
1232             return;
1233     }
1234 }
1235 
1236 static void hci_init_done(void){
1237     // done. tell the app
1238     log_info("hci_init_done -> HCI_STATE_WORKING");
1239     hci_stack->state = HCI_STATE_WORKING;
1240     hci_emit_state();
1241     hci_run();
1242 }
1243 
1244 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
1245     UNUSED(size);
1246 
1247     uint8_t command_completed = 0;
1248 
1249     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1250         uint16_t opcode = little_endian_read_16(packet,3);
1251         if (opcode == hci_stack->last_cmd_opcode){
1252             command_completed = 1;
1253             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
1254         } else {
1255             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
1256         }
1257     }
1258 
1259     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
1260         uint8_t  status = packet[2];
1261         uint16_t opcode = little_endian_read_16(packet,4);
1262         if (opcode == hci_stack->last_cmd_opcode){
1263             if (status){
1264                 command_completed = 1;
1265                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
1266             } else {
1267                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
1268             }
1269         } else {
1270             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1271         }
1272     }
1273 
1274 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1275 
1276     // Vendor == CSR
1277     if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1278         // TODO: track actual command
1279         command_completed = 1;
1280     }
1281 
1282     // Vendor == Toshiba
1283     if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1284         // TODO: track actual command
1285         command_completed = 1;
1286     }
1287 
1288     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1289     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1290     //
1291     // HCI Reset
1292     // Timeout 100 ms
1293     // HCI Reset
1294     // Command Complete Reset
1295     // HCI Read Local Version Information
1296     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1297     // hang...
1298     //
1299     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1300     if (!command_completed
1301             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1302             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
1303 
1304         uint16_t opcode = little_endian_read_16(packet,3);
1305         if (opcode == hci_reset.opcode){
1306             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1307             return;
1308         }
1309     }
1310 
1311     // CSR & H5
1312     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1313     if (!command_completed
1314             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1315             && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){
1316 
1317         uint16_t opcode = little_endian_read_16(packet,3);
1318         if (opcode == hci_reset.opcode){
1319             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1320             return;
1321         }
1322     }
1323 
1324     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
1325     // fix: Correct substate and behave as command below
1326     if (command_completed){
1327         switch (hci_stack->substate){
1328             case HCI_INIT_SEND_RESET:
1329                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1330                 break;
1331             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1332                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1333                 break;
1334             default:
1335                 break;
1336         }
1337     }
1338 
1339 #endif
1340 
1341     if (!command_completed) return;
1342 
1343     int need_baud_change = 0;
1344     int need_addr_change = 0;
1345 
1346 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1347     need_baud_change = hci_stack->config
1348                         && hci_stack->chipset
1349                         && hci_stack->chipset->set_baudrate_command
1350                         && hci_stack->hci_transport->set_baudrate
1351                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1352 
1353     need_addr_change = hci_stack->custom_bd_addr_set
1354                         && hci_stack->chipset
1355                         && hci_stack->chipset->set_bd_addr_command;
1356 #endif
1357 
1358     switch(hci_stack->substate){
1359 
1360 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1361         case HCI_INIT_SEND_RESET:
1362             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
1363             // fix: just correct substate and behave as command below
1364             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1365             btstack_run_loop_remove_timer(&hci_stack->timeout);
1366             break;
1367         case HCI_INIT_W4_SEND_RESET:
1368             btstack_run_loop_remove_timer(&hci_stack->timeout);
1369             break;
1370         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
1371             log_info("Received local name, need baud change %d", need_baud_change);
1372             if (need_baud_change){
1373                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
1374                 return;
1375             }
1376             // skip baud change
1377             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1378             return;
1379         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1380             // for STLC2500D, baud rate change already happened.
1381             // for others, baud rate gets changed now
1382             if ((hci_stack->manufacturer != COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
1383                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1384                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1385                 hci_stack->hci_transport->set_baudrate(baud_rate);
1386             }
1387             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1388             return;
1389         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1390             btstack_run_loop_remove_timer(&hci_stack->timeout);
1391             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1392             return;
1393         case HCI_INIT_W4_CUSTOM_INIT:
1394             // repeat custom init
1395             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1396             return;
1397 #else
1398         case HCI_INIT_W4_SEND_RESET:
1399             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1400             return ;
1401 #endif
1402 
1403         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1404             if (need_baud_change && hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION){
1405                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1406                 return;
1407             }
1408             if (need_addr_change){
1409                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1410                 return;
1411             }
1412             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1413             return;
1414 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1415         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
1416             if (need_baud_change){
1417                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1418                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1419                 hci_stack->hci_transport->set_baudrate(baud_rate);
1420             }
1421             if (need_addr_change){
1422                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1423                 return;
1424             }
1425             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1426             return;
1427         case HCI_INIT_W4_SET_BD_ADDR:
1428             // for STLC2500D, bd addr change only gets active after sending reset command
1429             if (hci_stack->manufacturer == COMPANY_ID_ST_MICROELECTRONICS){
1430                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
1431                 return;
1432             }
1433             // skipping st warm boot
1434             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1435             return;
1436         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
1437             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1438             return;
1439 #endif
1440         case HCI_INIT_W4_READ_BD_ADDR:
1441             // only read buffer size if supported
1442             if (hci_stack->local_supported_commands[0] & 0x01) {
1443                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
1444                 return;
1445             }
1446             // skipping read buffer size
1447             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1448             return;
1449         case HCI_INIT_W4_SET_EVENT_MASK:
1450             // skip Classic init commands for LE only chipsets
1451             if (!hci_classic_supported()){
1452 #ifdef ENABLE_BLE
1453                 if (hci_le_supported()){
1454                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
1455                     return;
1456                 }
1457 #endif
1458                 log_error("Neither BR/EDR nor LE supported");
1459                 hci_init_done();
1460                 return;
1461             }
1462             if (!gap_ssp_supported()){
1463                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
1464                 return;
1465             }
1466             break;
1467 #ifdef ENABLE_BLE
1468         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1469             // skip write le host if not supported (e.g. on LE only EM9301)
1470             if (hci_stack->local_supported_commands[0] & 0x02) break;
1471 #ifdef ENABLE_LE_CENTRAL
1472             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1473 #else
1474             hci_init_done();
1475 #endif
1476             return;
1477 #endif
1478         case HCI_INIT_W4_WRITE_LOCAL_NAME:
1479             // skip write eir data if no eir data set
1480             if (hci_stack->eir_data) break;
1481             hci_stack->substate = HCI_INIT_WRITE_INQUIRY_MODE;
1482             return;
1483 
1484 #ifdef ENABLE_SCO_OVER_HCI
1485         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1486             // skip write synchronous flow control if not supported
1487             if (hci_stack->local_supported_commands[0] & 0x04) break;
1488             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1489             // explicit fall through to reduce repetitions
1490 
1491         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1492             // skip write default erroneous data reporting if not supported
1493             if (hci_stack->local_supported_commands[0] & 0x08) break;
1494             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1495             // explicit fall through to reduce repetitions
1496 
1497         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1498             // skip bcm set sco pcm config on non-Broadcom chipsets
1499             if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION) break;
1500             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1501             // explicit fall through to reduce repetitions
1502 
1503         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1504             if (!hci_le_supported()){
1505                 // SKIP LE init for Classic only configuration
1506                 hci_init_done();
1507                 return;
1508             }
1509             break;
1510 #else
1511         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1512             if (!hci_le_supported()){
1513                 // SKIP LE init for Classic only configuration
1514                 hci_init_done();
1515                 return;
1516             }
1517 #endif
1518             break;
1519         // Response to command before init done state -> init done
1520         case (HCI_INIT_DONE-1):
1521             hci_init_done();
1522             return;
1523 
1524         default:
1525             break;
1526     }
1527     hci_initializing_next_state();
1528 }
1529 
1530 static void event_handler(uint8_t *packet, int size){
1531 
1532     uint16_t event_length = packet[1];
1533 
1534     // assert packet is complete
1535     if (size != event_length + 2){
1536         log_error("hci.c: event_handler called with event packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
1537         return;
1538     }
1539 
1540     bd_addr_t addr;
1541     bd_addr_type_t addr_type;
1542     uint8_t link_type;
1543     hci_con_handle_t handle;
1544     hci_connection_t * conn;
1545     int i;
1546 
1547     // warnings
1548     (void) link_type;
1549 
1550     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
1551 
1552     switch (hci_event_packet_get_type(packet)) {
1553 
1554         case HCI_EVENT_COMMAND_COMPLETE:
1555             // get num cmd packets - limit to 1 to reduce complexity
1556             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
1557 
1558             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
1559                 if (packet[5]) break;
1560                 // terminate, name 248 chars
1561                 packet[6+248] = 0;
1562                 log_info("local name: %s", &packet[6]);
1563             }
1564             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1565                 // from offset 5
1566                 // status
1567                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1568                 hci_stack->acl_data_packet_length = little_endian_read_16(packet, 6);
1569                 hci_stack->sco_data_packet_length = packet[8];
1570                 hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1571                 hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1572 
1573                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1574                     // determine usable ACL payload size
1575                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
1576                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1577                     }
1578                     log_info("hci_read_buffer_size: acl used size %u, count %u / sco size %u, count %u",
1579                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1580                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1581                 }
1582             }
1583 #ifdef ENABLE_BLE
1584             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1585                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1586                 hci_stack->le_acl_packets_total_num  = packet[8];
1587                     // determine usable ACL payload size
1588                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1589                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1590                     }
1591                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1592             }
1593 #ifdef ENABLE_LE_CENTRAL
1594             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1595                 hci_stack->le_whitelist_capacity = packet[6];
1596                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1597             }
1598 #endif
1599 #endif
1600             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1601                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1602 				hci_stack->local_bd_addr);
1603                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1604                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1605 #ifdef ENABLE_CLASSIC
1606                 if (hci_stack->link_key_db){
1607                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1608                 }
1609 #endif
1610             }
1611 #ifdef ENABLE_CLASSIC
1612             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1613                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1614             }
1615 #endif
1616 
1617             // Note: HCI init checks
1618             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1619                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1620 
1621 #ifdef ENABLE_CLASSIC
1622                 // determine usable ACL packet types based on host buffer size and supported features
1623                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1624                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
1625 #endif
1626                 // Classic/LE
1627                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1628             }
1629             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1630                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1631                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1632                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1633                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1634                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1635                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1636             }
1637             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1638                 hci_stack->local_supported_commands[0] =
1639                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7
1640                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6
1641                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4
1642                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08);        // bit 3 = Octet 18, bit 3
1643                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1644             }
1645 #ifdef ENABLE_CLASSIC
1646             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1647                 if (packet[5] == 0){
1648                     hci_stack->synchronous_flow_control_enabled = 1;
1649                 }
1650             }
1651 #endif
1652             break;
1653 
1654         case HCI_EVENT_COMMAND_STATUS:
1655             // get num cmd packets - limit to 1 to reduce complexity
1656             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
1657             break;
1658 
1659         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1660             int offset = 3;
1661             for (i=0; i<packet[2];i++){
1662                 handle = little_endian_read_16(packet, offset);
1663                 offset += 2;
1664                 uint16_t num_packets = little_endian_read_16(packet, offset);
1665                 offset += 2;
1666 
1667                 conn = hci_connection_for_handle(handle);
1668                 if (!conn){
1669                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1670                     continue;
1671                 }
1672 
1673                 if (conn->address_type == BD_ADDR_TYPE_SCO){
1674 #ifdef ENABLE_CLASSIC
1675                     if (conn->num_sco_packets_sent >= num_packets){
1676                         conn->num_sco_packets_sent -= num_packets;
1677                     } else {
1678                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1679                         conn->num_sco_packets_sent = 0;
1680                     }
1681                     hci_notify_if_sco_can_send_now();
1682 #endif
1683                 } else {
1684                     if (conn->num_acl_packets_sent >= num_packets){
1685                         conn->num_acl_packets_sent -= num_packets;
1686                     } else {
1687                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
1688                         conn->num_acl_packets_sent = 0;
1689                     }
1690                 }
1691                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1692             }
1693             break;
1694         }
1695 
1696 #ifdef ENABLE_CLASSIC
1697         case HCI_EVENT_CONNECTION_REQUEST:
1698             reverse_bd_addr(&packet[2], addr);
1699             // TODO: eval COD 8-10
1700             link_type = packet[11];
1701             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1702             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
1703             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1704             if (!conn) {
1705                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1706             }
1707             if (!conn) {
1708                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1709                 hci_stack->decline_reason = 0x0d;
1710                 bd_addr_copy(hci_stack->decline_addr, addr);
1711                 break;
1712             }
1713             conn->role  = HCI_ROLE_SLAVE;
1714             conn->state = RECEIVED_CONNECTION_REQUEST;
1715             // store info about eSCO
1716             if (link_type == 0x02){
1717                 conn->remote_supported_feature_eSCO = 1;
1718             }
1719             hci_run();
1720             break;
1721 
1722         case HCI_EVENT_CONNECTION_COMPLETE:
1723             // Connection management
1724             reverse_bd_addr(&packet[5], addr);
1725             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1726             addr_type = BD_ADDR_TYPE_CLASSIC;
1727             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1728             if (conn) {
1729                 if (!packet[2]){
1730                     conn->state = OPEN;
1731                     conn->con_handle = little_endian_read_16(packet, 3);
1732                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1733 
1734                     // restart timer
1735                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1736                     btstack_run_loop_add_timer(&conn->timeout);
1737 
1738                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1739 
1740                     hci_emit_nr_connections_changed();
1741                 } else {
1742                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1743                     uint8_t status = packet[2];
1744                     bd_addr_t bd_address;
1745                     memcpy(&bd_address, conn->address, 6);
1746 
1747                     // connection failed, remove entry
1748                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1749                     btstack_memory_hci_connection_free( conn );
1750 
1751                     // notify client if dedicated bonding
1752                     if (notify_dedicated_bonding_failed){
1753                         log_info("hci notify_dedicated_bonding_failed");
1754                         hci_emit_dedicated_bonding_result(bd_address, status);
1755                     }
1756 
1757                     // if authentication error, also delete link key
1758                     if (packet[2] == 0x05) {
1759                         gap_drop_link_key_for_bd_addr(addr);
1760                     }
1761                 }
1762             }
1763             break;
1764 
1765         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1766             reverse_bd_addr(&packet[5], addr);
1767             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1768             if (packet[2]){
1769                 // connection failed
1770                 break;
1771             }
1772             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1773             if (!conn) {
1774                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1775             }
1776             if (!conn) {
1777                 break;
1778             }
1779             conn->state = OPEN;
1780             conn->con_handle = little_endian_read_16(packet, 3);
1781 
1782 #ifdef ENABLE_SCO_OVER_HCI
1783             // update SCO
1784             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
1785                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1786             }
1787 #endif
1788             break;
1789 
1790         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1791             handle = little_endian_read_16(packet, 3);
1792             conn = hci_connection_for_handle(handle);
1793             if (!conn) break;
1794             if (!packet[2]){
1795                 uint8_t * features = &packet[5];
1796                 if (features[6] & (1 << 3)){
1797                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1798                 }
1799                 if (features[3] & (1<<7)){
1800                     conn->remote_supported_feature_eSCO = 1;
1801                 }
1802             }
1803             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1804             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
1805             if (conn->bonding_flags & BONDING_DEDICATED){
1806                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1807             }
1808             break;
1809 
1810         case HCI_EVENT_LINK_KEY_REQUEST:
1811             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1812             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1813             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1814             if (hci_stack->bondable && !hci_stack->link_key_db) break;
1815             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1816             hci_run();
1817             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1818             return;
1819 
1820         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1821             reverse_bd_addr(&packet[2], addr);
1822             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1823             if (!conn) break;
1824             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1825             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1826             // Change Connection Encryption keeps link key type
1827             if (link_key_type != CHANGED_COMBINATION_KEY){
1828                 conn->link_key_type = link_key_type;
1829             }
1830             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
1831             // still forward event to allow dismiss of pairing dialog
1832             break;
1833         }
1834 
1835         case HCI_EVENT_PIN_CODE_REQUEST:
1836             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1837             // non-bondable mode: pin code negative reply will be sent
1838             if (!hci_stack->bondable){
1839                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1840                 hci_run();
1841                 return;
1842             }
1843             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1844             if (!hci_stack->link_key_db) break;
1845             hci_event_pin_code_request_get_bd_addr(packet, addr);
1846             hci_stack->link_key_db->delete_link_key(addr);
1847             break;
1848 
1849         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1850             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1851             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1852             break;
1853 
1854         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
1855             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1856             if (!hci_stack->ssp_auto_accept) break;
1857             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1858             break;
1859 
1860         case HCI_EVENT_USER_PASSKEY_REQUEST:
1861             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1862             if (!hci_stack->ssp_auto_accept) break;
1863             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1864             break;
1865 #endif
1866 
1867         case HCI_EVENT_ENCRYPTION_CHANGE:
1868             handle = little_endian_read_16(packet, 3);
1869             conn = hci_connection_for_handle(handle);
1870             if (!conn) break;
1871             if (packet[2] == 0) {
1872                 if (packet[5]){
1873                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1874                 } else {
1875                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1876                 }
1877             }
1878 #ifdef ENABLE_CLASSIC
1879             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1880 #endif
1881             break;
1882 
1883 #ifdef ENABLE_CLASSIC
1884         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1885             handle = little_endian_read_16(packet, 3);
1886             conn = hci_connection_for_handle(handle);
1887             if (!conn) break;
1888 
1889             // dedicated bonding: send result and disconnect
1890             if (conn->bonding_flags & BONDING_DEDICATED){
1891                 conn->bonding_flags &= ~BONDING_DEDICATED;
1892                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1893                 conn->bonding_status = packet[2];
1894                 break;
1895             }
1896 
1897             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1898                 // link key sufficient for requested security
1899                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1900                 break;
1901             }
1902             // not enough
1903             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1904             break;
1905 #endif
1906 
1907         // HCI_EVENT_DISCONNECTION_COMPLETE
1908         // has been split, to first notify stack before shutting connection down
1909         // see end of function, too.
1910         case HCI_EVENT_DISCONNECTION_COMPLETE:
1911             if (packet[2]) break;   // status != 0
1912             handle = little_endian_read_16(packet, 3);
1913             // drop outgoing ACL fragments if it is for closed connection
1914             if (hci_stack->acl_fragmentation_total_size > 0) {
1915                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
1916                     log_info("hci: drop fragmented ACL data for closed connection");
1917                      hci_stack->acl_fragmentation_total_size = 0;
1918                      hci_stack->acl_fragmentation_pos = 0;
1919                 }
1920             }
1921 
1922             // re-enable advertisements for le connections if active
1923             conn = hci_connection_for_handle(handle);
1924             if (!conn) break;
1925 #ifdef ENABLE_BLE
1926 #ifdef ENABLE_LE_PERIPHERAL
1927             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
1928                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
1929             }
1930 #endif
1931 #endif
1932             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1933             break;
1934 
1935         case HCI_EVENT_HARDWARE_ERROR:
1936             log_error("Hardware Error: 0x%02x", packet[2]);
1937             if (hci_stack->hardware_error_callback){
1938                 (*hci_stack->hardware_error_callback)(packet[2]);
1939             } else {
1940                 // if no special requests, just reboot stack
1941                 hci_power_control_off();
1942                 hci_power_control_on();
1943             }
1944             break;
1945 
1946 #ifdef ENABLE_CLASSIC
1947         case HCI_EVENT_ROLE_CHANGE:
1948             if (packet[2]) break;   // status != 0
1949             handle = little_endian_read_16(packet, 3);
1950             conn = hci_connection_for_handle(handle);
1951             if (!conn) break;       // no conn
1952             conn->role = packet[9];
1953             break;
1954 #endif
1955 
1956         case HCI_EVENT_TRANSPORT_PACKET_SENT:
1957             // release packet buffer only for asynchronous transport and if there are not further fragements
1958             if (hci_transport_synchronous()) {
1959                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
1960                 return; // instead of break: to avoid re-entering hci_run()
1961             }
1962             if (hci_stack->acl_fragmentation_total_size) break;
1963             hci_release_packet_buffer();
1964 
1965             // L2CAP receives this event via the hci_emit_event below
1966 
1967 #ifdef ENABLE_CLASSIC
1968             // For SCO, we do the can_send_now_check here
1969             hci_notify_if_sco_can_send_now();
1970 #endif
1971             break;
1972 
1973 #ifdef ENABLE_CLASSIC
1974         case HCI_EVENT_SCO_CAN_SEND_NOW:
1975             // For SCO, we do the can_send_now_check here
1976             hci_notify_if_sco_can_send_now();
1977             return;
1978 #endif
1979 
1980 #ifdef ENABLE_BLE
1981         case HCI_EVENT_LE_META:
1982             switch (packet[2]){
1983 #ifdef ENABLE_LE_CENTRAL
1984                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1985                     // log_info("advertising report received");
1986                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1987                     le_handle_advertisement_report(packet, size);
1988                     break;
1989 #endif
1990                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1991                     // Connection management
1992                     reverse_bd_addr(&packet[8], addr);
1993                     addr_type = (bd_addr_type_t)packet[7];
1994                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
1995                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1996 #ifdef ENABLE_LE_CENTRAL
1997                     // if auto-connect, remove from whitelist in both roles
1998                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
1999                         hci_remove_from_whitelist(addr_type, addr);
2000                     }
2001                     // handle error: error is reported only to the initiator -> outgoing connection
2002                     if (packet[3]){
2003                         // outgoing connection establishment is done
2004                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2005                         // remove entry
2006                         if (conn){
2007                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2008                             btstack_memory_hci_connection_free( conn );
2009                         }
2010                         break;
2011                     }
2012 #endif
2013                     // on success, both hosts receive connection complete event
2014                     if (packet[6] == HCI_ROLE_MASTER){
2015 #ifdef ENABLE_LE_CENTRAL
2016                         // if we're master, it was an outgoing connection and we're done with it
2017                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2018 #endif
2019                     } else {
2020 #ifdef ENABLE_LE_PERIPHERAL
2021                         // if we're slave, it was an incoming connection, advertisements have stopped
2022                         hci_stack->le_advertisements_active = 0;
2023                         // try to re-enable them
2024                         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2025 #endif
2026                     }
2027                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2028                     if (!conn){
2029                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2030                     }
2031                     // no memory, sorry.
2032                     if (!conn){
2033                         break;
2034                     }
2035 
2036                     conn->state = OPEN;
2037                     conn->role  = packet[6];
2038                     conn->con_handle = little_endian_read_16(packet, 4);
2039 
2040                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2041 
2042                     // restart timer
2043                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2044                     // btstack_run_loop_add_timer(&conn->timeout);
2045 
2046                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2047 
2048                     hci_emit_nr_connections_changed();
2049                     break;
2050 
2051             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2052 
2053                 default:
2054                     break;
2055             }
2056             break;
2057 #endif
2058         default:
2059             break;
2060     }
2061 
2062     // handle BT initialization
2063     if (hci_stack->state == HCI_STATE_INITIALIZING){
2064         hci_initializing_event_handler(packet, size);
2065     }
2066 
2067     // help with BT sleep
2068     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2069         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2070         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2071         hci_initializing_next_state();
2072     }
2073 
2074     // notify upper stack
2075 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2076 
2077     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2078     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2079         if (!packet[2]){
2080             handle = little_endian_read_16(packet, 3);
2081             hci_connection_t * aConn = hci_connection_for_handle(handle);
2082             if (aConn) {
2083                 uint8_t status = aConn->bonding_status;
2084                 uint16_t flags = aConn->bonding_flags;
2085                 bd_addr_t bd_address;
2086                 memcpy(&bd_address, aConn->address, 6);
2087                 hci_shutdown_connection(aConn);
2088                 // connection struct is gone, don't access anymore
2089                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2090                     hci_emit_dedicated_bonding_result(bd_address, status);
2091                 }
2092             }
2093         }
2094     }
2095 
2096 	// execute main loop
2097 	hci_run();
2098 }
2099 
2100 #ifdef ENABLE_CLASSIC
2101 static void sco_handler(uint8_t * packet, uint16_t size){
2102     if (!hci_stack->sco_packet_handler) return;
2103     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2104 }
2105 #endif
2106 
2107 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2108     hci_dump_packet(packet_type, 1, packet, size);
2109     switch (packet_type) {
2110         case HCI_EVENT_PACKET:
2111             event_handler(packet, size);
2112             break;
2113         case HCI_ACL_DATA_PACKET:
2114             acl_handler(packet, size);
2115             break;
2116 #ifdef ENABLE_CLASSIC
2117         case HCI_SCO_DATA_PACKET:
2118             sco_handler(packet, size);
2119             break;
2120 #endif
2121         default:
2122             break;
2123     }
2124 }
2125 
2126 /**
2127  * @brief Add event packet handler.
2128  */
2129 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2130     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2131 }
2132 
2133 
2134 /** Register HCI packet handlers */
2135 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2136     hci_stack->acl_packet_handler = handler;
2137 }
2138 
2139 #ifdef ENABLE_CLASSIC
2140 /**
2141  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2142  */
2143 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2144     hci_stack->sco_packet_handler = handler;
2145 }
2146 #endif
2147 
2148 static void hci_state_reset(void){
2149     // no connections yet
2150     hci_stack->connections = NULL;
2151 
2152     // keep discoverable/connectable as this has been requested by the client(s)
2153     // hci_stack->discoverable = 0;
2154     // hci_stack->connectable = 0;
2155     // hci_stack->bondable = 1;
2156     // hci_stack->own_addr_type = 0;
2157 
2158     // buffer is free
2159     hci_stack->hci_packet_buffer_reserved = 0;
2160 
2161     // no pending cmds
2162     hci_stack->decline_reason = 0;
2163     hci_stack->new_scan_enable_value = 0xff;
2164 
2165     // LE
2166 #ifdef ENABLE_BLE
2167     memset(hci_stack->le_random_address, 0, 6);
2168     hci_stack->le_random_address_set = 0;
2169 #endif
2170 #ifdef ENABLE_LE_CENTRAL
2171     hci_stack->le_scanning_state = LE_SCAN_IDLE;
2172     hci_stack->le_scan_type = 0xff;
2173     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2174     hci_stack->le_whitelist = 0;
2175     hci_stack->le_whitelist_capacity = 0;
2176 #endif
2177 
2178     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2179     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2180     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2181     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2182     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2183     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2184 }
2185 
2186 #ifdef ENABLE_CLASSIC
2187 /**
2188  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2189  */
2190 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2191     // store and open remote device db
2192     hci_stack->link_key_db = link_key_db;
2193     if (hci_stack->link_key_db) {
2194         hci_stack->link_key_db->open();
2195     }
2196 }
2197 #endif
2198 
2199 void hci_init(const hci_transport_t *transport, const void *config){
2200 
2201 #ifdef HAVE_MALLOC
2202     if (!hci_stack) {
2203         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2204     }
2205 #else
2206     hci_stack = &hci_stack_static;
2207 #endif
2208     memset(hci_stack, 0, sizeof(hci_stack_t));
2209 
2210     // reference to use transport layer implementation
2211     hci_stack->hci_transport = transport;
2212 
2213     // reference to used config
2214     hci_stack->config = config;
2215 
2216     // setup pointer for outgoing packet buffer
2217     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2218 
2219     // max acl payload size defined in config.h
2220     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2221 
2222     // register packet handlers with transport
2223     transport->register_packet_handler(&packet_handler);
2224 
2225     hci_stack->state = HCI_STATE_OFF;
2226 
2227     // class of device
2228     hci_stack->class_of_device = 0x007a020c; // Smartphone
2229 
2230     // bondable by default
2231     hci_stack->bondable = 1;
2232 
2233     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2234     hci_stack->ssp_enable = 1;
2235     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2236     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2237     hci_stack->ssp_auto_accept = 1;
2238 
2239     // voice setting - signed 16 bit pcm data with CVSD over the air
2240     hci_stack->sco_voice_setting = 0x60;
2241 
2242     hci_state_reset();
2243 }
2244 
2245 /**
2246  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2247  */
2248 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2249     hci_stack->chipset = chipset_driver;
2250 
2251     // reset chipset driver - init is also called on power_up
2252     if (hci_stack->chipset && hci_stack->chipset->init){
2253         hci_stack->chipset->init(hci_stack->config);
2254     }
2255 }
2256 
2257 /**
2258  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2259  */
2260 void hci_set_control(const btstack_control_t *hardware_control){
2261     // references to used control implementation
2262     hci_stack->control = hardware_control;
2263     // init with transport config
2264     hardware_control->init(hci_stack->config);
2265 }
2266 
2267 void hci_close(void){
2268     // close remote device db
2269     if (hci_stack->link_key_db) {
2270         hci_stack->link_key_db->close();
2271     }
2272 
2273     btstack_linked_list_iterator_t lit;
2274     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2275     while (btstack_linked_list_iterator_has_next(&lit)){
2276         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2277         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2278         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2279         hci_shutdown_connection(connection);
2280     }
2281 
2282     hci_power_control(HCI_POWER_OFF);
2283 
2284 #ifdef HAVE_MALLOC
2285     free(hci_stack);
2286 #endif
2287     hci_stack = NULL;
2288 }
2289 
2290 #ifdef ENABLE_CLASSIC
2291 void gap_set_class_of_device(uint32_t class_of_device){
2292     hci_stack->class_of_device = class_of_device;
2293 }
2294 
2295 void hci_disable_l2cap_timeout_check(void){
2296     disable_l2cap_timeouts = 1;
2297 }
2298 #endif
2299 
2300 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2301 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2302 void hci_set_bd_addr(bd_addr_t addr){
2303     memcpy(hci_stack->custom_bd_addr, addr, 6);
2304     hci_stack->custom_bd_addr_set = 1;
2305 }
2306 #endif
2307 
2308 // State-Module-Driver overview
2309 // state                    module  low-level
2310 // HCI_STATE_OFF             off      close
2311 // HCI_STATE_INITIALIZING,   on       open
2312 // HCI_STATE_WORKING,        on       open
2313 // HCI_STATE_HALTING,        on       open
2314 // HCI_STATE_SLEEPING,    off/sleep   close
2315 // HCI_STATE_FALLING_ASLEEP  on       open
2316 
2317 static int hci_power_control_on(void){
2318 
2319     // power on
2320     int err = 0;
2321     if (hci_stack->control && hci_stack->control->on){
2322         err = (*hci_stack->control->on)();
2323     }
2324     if (err){
2325         log_error( "POWER_ON failed");
2326         hci_emit_hci_open_failed();
2327         return err;
2328     }
2329 
2330     // int chipset driver
2331     if (hci_stack->chipset && hci_stack->chipset->init){
2332         hci_stack->chipset->init(hci_stack->config);
2333     }
2334 
2335     // init transport
2336     if (hci_stack->hci_transport->init){
2337         hci_stack->hci_transport->init(hci_stack->config);
2338     }
2339 
2340     // open transport
2341     err = hci_stack->hci_transport->open();
2342     if (err){
2343         log_error( "HCI_INIT failed, turning Bluetooth off again");
2344         if (hci_stack->control && hci_stack->control->off){
2345             (*hci_stack->control->off)();
2346         }
2347         hci_emit_hci_open_failed();
2348         return err;
2349     }
2350     return 0;
2351 }
2352 
2353 static void hci_power_control_off(void){
2354 
2355     log_info("hci_power_control_off");
2356 
2357     // close low-level device
2358     hci_stack->hci_transport->close();
2359 
2360     log_info("hci_power_control_off - hci_transport closed");
2361 
2362     // power off
2363     if (hci_stack->control && hci_stack->control->off){
2364         (*hci_stack->control->off)();
2365     }
2366 
2367     log_info("hci_power_control_off - control closed");
2368 
2369     hci_stack->state = HCI_STATE_OFF;
2370 }
2371 
2372 static void hci_power_control_sleep(void){
2373 
2374     log_info("hci_power_control_sleep");
2375 
2376 #if 0
2377     // don't close serial port during sleep
2378 
2379     // close low-level device
2380     hci_stack->hci_transport->close(hci_stack->config);
2381 #endif
2382 
2383     // sleep mode
2384     if (hci_stack->control && hci_stack->control->sleep){
2385         (*hci_stack->control->sleep)();
2386     }
2387 
2388     hci_stack->state = HCI_STATE_SLEEPING;
2389 }
2390 
2391 static int hci_power_control_wake(void){
2392 
2393     log_info("hci_power_control_wake");
2394 
2395     // wake on
2396     if (hci_stack->control && hci_stack->control->wake){
2397         (*hci_stack->control->wake)();
2398     }
2399 
2400 #if 0
2401     // open low-level device
2402     int err = hci_stack->hci_transport->open(hci_stack->config);
2403     if (err){
2404         log_error( "HCI_INIT failed, turning Bluetooth off again");
2405         if (hci_stack->control && hci_stack->control->off){
2406             (*hci_stack->control->off)();
2407         }
2408         hci_emit_hci_open_failed();
2409         return err;
2410     }
2411 #endif
2412 
2413     return 0;
2414 }
2415 
2416 static void hci_power_transition_to_initializing(void){
2417     // set up state machine
2418     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2419     hci_stack->hci_packet_buffer_reserved = 0;
2420     hci_stack->state = HCI_STATE_INITIALIZING;
2421     hci_stack->substate = HCI_INIT_SEND_RESET;
2422 }
2423 
2424 int hci_power_control(HCI_POWER_MODE power_mode){
2425 
2426     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2427 
2428     int err = 0;
2429     switch (hci_stack->state){
2430 
2431         case HCI_STATE_OFF:
2432             switch (power_mode){
2433                 case HCI_POWER_ON:
2434                     err = hci_power_control_on();
2435                     if (err) {
2436                         log_error("hci_power_control_on() error %d", err);
2437                         return err;
2438                     }
2439                     hci_power_transition_to_initializing();
2440                     break;
2441                 case HCI_POWER_OFF:
2442                     // do nothing
2443                     break;
2444                 case HCI_POWER_SLEEP:
2445                     // do nothing (with SLEEP == OFF)
2446                     break;
2447             }
2448             break;
2449 
2450         case HCI_STATE_INITIALIZING:
2451             switch (power_mode){
2452                 case HCI_POWER_ON:
2453                     // do nothing
2454                     break;
2455                 case HCI_POWER_OFF:
2456                     // no connections yet, just turn it off
2457                     hci_power_control_off();
2458                     break;
2459                 case HCI_POWER_SLEEP:
2460                     // no connections yet, just turn it off
2461                     hci_power_control_sleep();
2462                     break;
2463             }
2464             break;
2465 
2466         case HCI_STATE_WORKING:
2467             switch (power_mode){
2468                 case HCI_POWER_ON:
2469                     // do nothing
2470                     break;
2471                 case HCI_POWER_OFF:
2472                     // see hci_run
2473                     hci_stack->state = HCI_STATE_HALTING;
2474                     break;
2475                 case HCI_POWER_SLEEP:
2476                     // see hci_run
2477                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2478                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2479                     break;
2480             }
2481             break;
2482 
2483         case HCI_STATE_HALTING:
2484             switch (power_mode){
2485                 case HCI_POWER_ON:
2486                     hci_power_transition_to_initializing();
2487                     break;
2488                 case HCI_POWER_OFF:
2489                     // do nothing
2490                     break;
2491                 case HCI_POWER_SLEEP:
2492                     // see hci_run
2493                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2494                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2495                     break;
2496             }
2497             break;
2498 
2499         case HCI_STATE_FALLING_ASLEEP:
2500             switch (power_mode){
2501                 case HCI_POWER_ON:
2502 
2503 #ifdef HAVE_PLATFORM_IPHONE_OS
2504                     // nothing to do, if H4 supports power management
2505                     if (btstack_control_iphone_power_management_enabled()){
2506                         hci_stack->state = HCI_STATE_INITIALIZING;
2507                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2508                         break;
2509                     }
2510 #endif
2511                     hci_power_transition_to_initializing();
2512                     break;
2513                 case HCI_POWER_OFF:
2514                     // see hci_run
2515                     hci_stack->state = HCI_STATE_HALTING;
2516                     break;
2517                 case HCI_POWER_SLEEP:
2518                     // do nothing
2519                     break;
2520             }
2521             break;
2522 
2523         case HCI_STATE_SLEEPING:
2524             switch (power_mode){
2525                 case HCI_POWER_ON:
2526 
2527 #ifdef HAVE_PLATFORM_IPHONE_OS
2528                     // nothing to do, if H4 supports power management
2529                     if (btstack_control_iphone_power_management_enabled()){
2530                         hci_stack->state = HCI_STATE_INITIALIZING;
2531                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2532                         hci_update_scan_enable();
2533                         break;
2534                     }
2535 #endif
2536                     err = hci_power_control_wake();
2537                     if (err) return err;
2538                     hci_power_transition_to_initializing();
2539                     break;
2540                 case HCI_POWER_OFF:
2541                     hci_stack->state = HCI_STATE_HALTING;
2542                     break;
2543                 case HCI_POWER_SLEEP:
2544                     // do nothing
2545                     break;
2546             }
2547             break;
2548     }
2549 
2550     // create internal event
2551 	hci_emit_state();
2552 
2553 	// trigger next/first action
2554 	hci_run();
2555 
2556     return 0;
2557 }
2558 
2559 
2560 #ifdef ENABLE_CLASSIC
2561 
2562 static void hci_update_scan_enable(void){
2563     // 2 = page scan, 1 = inq scan
2564     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2565     hci_run();
2566 }
2567 
2568 void gap_discoverable_control(uint8_t enable){
2569     if (enable) enable = 1; // normalize argument
2570 
2571     if (hci_stack->discoverable == enable){
2572         hci_emit_discoverable_enabled(hci_stack->discoverable);
2573         return;
2574     }
2575 
2576     hci_stack->discoverable = enable;
2577     hci_update_scan_enable();
2578 }
2579 
2580 void gap_connectable_control(uint8_t enable){
2581     if (enable) enable = 1; // normalize argument
2582 
2583     // don't emit event
2584     if (hci_stack->connectable == enable) return;
2585 
2586     hci_stack->connectable = enable;
2587     hci_update_scan_enable();
2588 }
2589 #endif
2590 
2591 void gap_local_bd_addr(bd_addr_t address_buffer){
2592     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
2593 }
2594 
2595 static void hci_run(void){
2596 
2597     // log_info("hci_run: entered");
2598     btstack_linked_item_t * it;
2599 
2600     // send continuation fragments first, as they block the prepared packet buffer
2601     if (hci_stack->acl_fragmentation_total_size > 0) {
2602         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2603         hci_connection_t *connection = hci_connection_for_handle(con_handle);
2604         if (connection) {
2605             if (hci_can_send_prepared_acl_packet_now(con_handle)){
2606                 hci_send_acl_packet_fragments(connection);
2607                 return;
2608             }
2609         } else {
2610             // connection gone -> discard further fragments
2611             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
2612             hci_stack->acl_fragmentation_total_size = 0;
2613             hci_stack->acl_fragmentation_pos = 0;
2614         }
2615     }
2616 
2617     if (!hci_can_send_command_packet_now()) return;
2618 
2619     // global/non-connection oriented commands
2620 
2621 #ifdef ENABLE_CLASSIC
2622     // decline incoming connections
2623     if (hci_stack->decline_reason){
2624         uint8_t reason = hci_stack->decline_reason;
2625         hci_stack->decline_reason = 0;
2626         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2627         return;
2628     }
2629 
2630     // send scan enable
2631     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
2632         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
2633         hci_stack->new_scan_enable_value = 0xff;
2634         return;
2635     }
2636 #endif
2637 
2638 #ifdef ENABLE_BLE
2639     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
2640     if ((hci_stack->state == HCI_STATE_WORKING)
2641     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
2642 
2643 #ifdef ENABLE_LE_CENTRAL
2644         // handle le scan
2645         switch(hci_stack->le_scanning_state){
2646             case LE_START_SCAN:
2647                 hci_stack->le_scanning_state = LE_SCANNING;
2648                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
2649                 return;
2650 
2651             case LE_STOP_SCAN:
2652                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
2653                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
2654                 return;
2655             default:
2656                 break;
2657         }
2658         if (hci_stack->le_scan_type != 0xff){
2659             // defaults: active scanning, accept all advertisement packets
2660             int scan_type = hci_stack->le_scan_type;
2661             hci_stack->le_scan_type = 0xff;
2662             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);
2663             return;
2664         }
2665 #endif
2666 #ifdef ENABLE_LE_PERIPHERAL
2667         // le advertisement control
2668         if (hci_stack->le_advertisements_todo){
2669             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
2670         }
2671         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
2672             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
2673             hci_send_cmd(&hci_le_set_advertise_enable, 0);
2674             return;
2675         }
2676         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
2677             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
2678             hci_send_cmd(&hci_le_set_advertising_parameters,
2679                  hci_stack->le_advertisements_interval_min,
2680                  hci_stack->le_advertisements_interval_max,
2681                  hci_stack->le_advertisements_type,
2682                  hci_stack->le_own_addr_type,
2683                  hci_stack->le_advertisements_direct_address_type,
2684                  hci_stack->le_advertisements_direct_address,
2685                  hci_stack->le_advertisements_channel_map,
2686                  hci_stack->le_advertisements_filter_policy);
2687             return;
2688         }
2689         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
2690             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
2691             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, hci_stack->le_advertisements_data);
2692             return;
2693         }
2694         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
2695             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
2696             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len,
2697                 hci_stack->le_scan_response_data);
2698             return;
2699         }
2700         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
2701             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
2702             hci_send_cmd(&hci_le_set_advertise_enable, 1);
2703             return;
2704         }
2705 #endif
2706 
2707 #ifdef ENABLE_LE_CENTRAL
2708         //
2709         // LE Whitelist Management
2710         //
2711 
2712         // check if whitelist needs modification
2713         btstack_linked_list_iterator_t lit;
2714         int modification_pending = 0;
2715         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2716         while (btstack_linked_list_iterator_has_next(&lit)){
2717             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2718             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
2719                 modification_pending = 1;
2720                 break;
2721             }
2722         }
2723 
2724         if (modification_pending){
2725             // stop connnecting if modification pending
2726             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
2727                 hci_send_cmd(&hci_le_create_connection_cancel);
2728                 return;
2729             }
2730 
2731             // add/remove entries
2732             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2733             while (btstack_linked_list_iterator_has_next(&lit)){
2734                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2735                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
2736                     entry->state = LE_WHITELIST_ON_CONTROLLER;
2737                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
2738                     return;
2739 
2740                 }
2741                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
2742                     bd_addr_t address;
2743                     bd_addr_type_t address_type = entry->address_type;
2744                     memcpy(address, entry->address, 6);
2745                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
2746                     btstack_memory_whitelist_entry_free(entry);
2747                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
2748                     return;
2749                 }
2750             }
2751         }
2752 
2753         // start connecting
2754         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
2755             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
2756             bd_addr_t null_addr;
2757             memset(null_addr, 0, 6);
2758             hci_send_cmd(&hci_le_create_connection,
2759                  0x0060,    // scan interval: 60 ms
2760                  0x0030,    // scan interval: 30 ms
2761                  1,         // use whitelist
2762                  0,         // peer address type
2763                  null_addr, // peer bd addr
2764                  hci_stack->le_own_addr_type, // our addr type:
2765                  0x0008,    // conn interval min
2766                  0x0018,    // conn interval max
2767                  0,         // conn latency
2768                  0x0048,    // supervision timeout
2769                  0x0001,    // min ce length
2770                  0x0001     // max ce length
2771                  );
2772             return;
2773         }
2774 #endif
2775     }
2776 #endif
2777 
2778     // send pending HCI commands
2779     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
2780         hci_connection_t * connection = (hci_connection_t *) it;
2781 
2782         switch(connection->state){
2783             case SEND_CREATE_CONNECTION:
2784                 switch(connection->address_type){
2785 #ifdef ENABLE_CLASSIC
2786                     case BD_ADDR_TYPE_CLASSIC:
2787                         log_info("sending hci_create_connection");
2788                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
2789                         break;
2790 #endif
2791                     default:
2792 #ifdef ENABLE_BLE
2793 #ifdef ENABLE_LE_CENTRAL
2794                         log_info("sending hci_le_create_connection");
2795                         hci_send_cmd(&hci_le_create_connection,
2796                                      0x0060,    // scan interval: 60 ms
2797                                      0x0030,    // scan interval: 30 ms
2798                                      0,         // don't use whitelist
2799                                      connection->address_type, // peer address type
2800                                      connection->address,      // peer bd addr
2801                                      hci_stack->le_own_addr_type,  // our addr type:
2802                                      0x0008,    // conn interval min
2803                                      0x0018,    // conn interval max
2804                                      0,         // conn latency
2805                                      0x0048,    // supervision timeout
2806                                      0x0001,    // min ce length
2807                                      0x0001     // max ce length
2808                                      );
2809 
2810                         connection->state = SENT_CREATE_CONNECTION;
2811 #endif
2812 #endif
2813                         break;
2814                 }
2815                 return;
2816 
2817 #ifdef ENABLE_CLASSIC
2818             case RECEIVED_CONNECTION_REQUEST:
2819                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
2820                 connection->state = ACCEPTED_CONNECTION_REQUEST;
2821                 connection->role  = HCI_ROLE_SLAVE;
2822                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
2823                     hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
2824                 }
2825                 return;
2826 #endif
2827 
2828 #ifdef ENABLE_BLE
2829 #ifdef ENABLE_LE_CENTRAL
2830             case SEND_CANCEL_CONNECTION:
2831                 connection->state = SENT_CANCEL_CONNECTION;
2832                 hci_send_cmd(&hci_le_create_connection_cancel);
2833                 return;
2834 #endif
2835 #endif
2836             case SEND_DISCONNECT:
2837                 connection->state = SENT_DISCONNECT;
2838                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
2839                 return;
2840 
2841             default:
2842                 break;
2843         }
2844 
2845 #ifdef ENABLE_CLASSIC
2846         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
2847             log_info("responding to link key request");
2848             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
2849             link_key_t link_key;
2850             link_key_type_t link_key_type;
2851             if ( hci_stack->link_key_db
2852               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
2853               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
2854                connection->link_key_type = link_key_type;
2855                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
2856             } else {
2857                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
2858             }
2859             return;
2860         }
2861 
2862         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
2863             log_info("denying to pin request");
2864             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
2865             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
2866             return;
2867         }
2868 
2869         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
2870             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
2871             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
2872             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
2873                 // tweak authentication requirements
2874                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
2875                 if (connection->bonding_flags & BONDING_DEDICATED){
2876                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
2877                 }
2878                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
2879                     authreq |= 1;
2880                 }
2881                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
2882             } else {
2883                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
2884             }
2885             return;
2886         }
2887 
2888         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
2889             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
2890             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
2891             return;
2892         }
2893 
2894         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
2895             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
2896             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
2897             return;
2898         }
2899 
2900         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
2901             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
2902             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
2903             return;
2904         }
2905 
2906         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
2907             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
2908             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
2909             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
2910             return;
2911         }
2912 
2913         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
2914             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
2915             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
2916             return;
2917         }
2918 
2919         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
2920             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
2921             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
2922             return;
2923         }
2924 #endif
2925 
2926         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
2927             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
2928             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
2929             return;
2930         }
2931 
2932 #ifdef ENABLE_BLE
2933         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2934             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2935 
2936             uint16_t connection_interval_min = connection->le_conn_interval_min;
2937             connection->le_conn_interval_min = 0;
2938             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2939                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2940                 0x0000, 0xffff);
2941         }
2942 #endif
2943     }
2944 
2945     hci_connection_t * connection;
2946     switch (hci_stack->state){
2947         case HCI_STATE_INITIALIZING:
2948             hci_initializing_run();
2949             break;
2950 
2951         case HCI_STATE_HALTING:
2952 
2953             log_info("HCI_STATE_HALTING");
2954 
2955             // free whitelist entries
2956 #ifdef ENABLE_BLE
2957 #ifdef ENABLE_LE_CENTRAL
2958             {
2959                 btstack_linked_list_iterator_t lit;
2960                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2961                 while (btstack_linked_list_iterator_has_next(&lit)){
2962                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2963                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
2964                     btstack_memory_whitelist_entry_free(entry);
2965                 }
2966             }
2967 #endif
2968 #endif
2969             // close all open connections
2970             connection =  (hci_connection_t *) hci_stack->connections;
2971             if (connection){
2972                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
2973                 if (!hci_can_send_command_packet_now()) return;
2974 
2975                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
2976 
2977                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
2978                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
2979 
2980                 // ... which would be ignored anyway as we shutdown (free) the connection now
2981                 hci_shutdown_connection(connection);
2982 
2983                 // finally, send the disconnect command
2984                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
2985                 return;
2986             }
2987             log_info("HCI_STATE_HALTING, calling off");
2988 
2989             // switch mode
2990             hci_power_control_off();
2991 
2992             log_info("HCI_STATE_HALTING, emitting state");
2993             hci_emit_state();
2994             log_info("HCI_STATE_HALTING, done");
2995             break;
2996 
2997         case HCI_STATE_FALLING_ASLEEP:
2998             switch(hci_stack->substate) {
2999                 case HCI_FALLING_ASLEEP_DISCONNECT:
3000                     log_info("HCI_STATE_FALLING_ASLEEP");
3001                     // close all open connections
3002                     connection =  (hci_connection_t *) hci_stack->connections;
3003 
3004 #ifdef HAVE_PLATFORM_IPHONE_OS
3005                     // don't close connections, if H4 supports power management
3006                     if (btstack_control_iphone_power_management_enabled()){
3007                         connection = NULL;
3008                     }
3009 #endif
3010                     if (connection){
3011 
3012                         // send disconnect
3013                         if (!hci_can_send_command_packet_now()) return;
3014 
3015                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3016                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3017 
3018                         // send disconnected event right away - causes higher layer connections to get closed, too.
3019                         hci_shutdown_connection(connection);
3020                         return;
3021                     }
3022 
3023                     if (hci_classic_supported()){
3024                         // disable page and inquiry scan
3025                         if (!hci_can_send_command_packet_now()) return;
3026 
3027                         log_info("HCI_STATE_HALTING, disabling inq scans");
3028                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3029 
3030                         // continue in next sub state
3031                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3032                         break;
3033                     }
3034                     // no break - fall through for ble-only chips
3035 
3036                 case HCI_FALLING_ASLEEP_COMPLETE:
3037                     log_info("HCI_STATE_HALTING, calling sleep");
3038 #ifdef HAVE_PLATFORM_IPHONE_OS
3039                     // don't actually go to sleep, if H4 supports power management
3040                     if (btstack_control_iphone_power_management_enabled()){
3041                         // SLEEP MODE reached
3042                         hci_stack->state = HCI_STATE_SLEEPING;
3043                         hci_emit_state();
3044                         break;
3045                     }
3046 #endif
3047                     // switch mode
3048                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3049                     hci_emit_state();
3050                     break;
3051 
3052                 default:
3053                     break;
3054             }
3055             break;
3056 
3057         default:
3058             break;
3059     }
3060 }
3061 
3062 int hci_send_cmd_packet(uint8_t *packet, int size){
3063     // house-keeping
3064 
3065     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3066         hci_stack->loopback_mode = packet[3];
3067     }
3068 
3069 #ifdef ENABLE_CLASSIC
3070     bd_addr_t addr;
3071     hci_connection_t * conn;
3072 
3073     // create_connection?
3074     if (IS_COMMAND(packet, hci_create_connection)){
3075         reverse_bd_addr(&packet[3], addr);
3076         log_info("Create_connection to %s", bd_addr_to_str(addr));
3077 
3078         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3079         if (!conn){
3080             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3081             if (!conn){
3082                 // notify client that alloc failed
3083                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3084                 return 0; // don't sent packet to controller
3085             }
3086             conn->state = SEND_CREATE_CONNECTION;
3087         }
3088         log_info("conn state %u", conn->state);
3089         switch (conn->state){
3090             // if connection active exists
3091             case OPEN:
3092                 // and OPEN, emit connection complete command, don't send to controller
3093                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3094                 return 0;
3095             case SEND_CREATE_CONNECTION:
3096                 // connection created by hci, e.g. dedicated bonding
3097                 break;
3098             default:
3099                 // otherwise, just ignore as it is already in the open process
3100                 return 0;
3101         }
3102         conn->state = SENT_CREATE_CONNECTION;
3103     }
3104 
3105     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3106         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3107     }
3108     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3109         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3110     }
3111 
3112     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3113         if (hci_stack->link_key_db){
3114             reverse_bd_addr(&packet[3], addr);
3115             hci_stack->link_key_db->delete_link_key(addr);
3116         }
3117     }
3118 
3119     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3120     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3121         reverse_bd_addr(&packet[3], addr);
3122         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3123         if (conn){
3124             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3125         }
3126     }
3127 
3128     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3129     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3130     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3131     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3132         reverse_bd_addr(&packet[3], addr);
3133         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3134         if (conn){
3135             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3136         }
3137     }
3138 
3139 #ifdef ENABLE_SCO_OVER_HCI
3140     // setup_synchronous_connection? Voice setting at offset 22
3141     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3142         // TODO: compare to current setting if sco connection already active
3143         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3144     }
3145     // accept_synchronus_connection? Voice setting at offset 18
3146     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3147         // TODO: compare to current setting if sco connection already active
3148         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3149     }
3150 #endif
3151 #endif
3152 
3153 #ifdef ENABLE_BLE
3154 #ifdef ENABLE_LE_PERIPHERAL
3155     if (IS_COMMAND(packet, hci_le_set_random_address)){
3156         hci_stack->le_random_address_set = 1;
3157         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3158     }
3159     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3160         hci_stack->le_advertisements_active = packet[3];
3161     }
3162 #endif
3163 #ifdef ENABLE_LE_CENTRAL
3164     if (IS_COMMAND(packet, hci_le_create_connection)){
3165         // white list used?
3166         uint8_t initiator_filter_policy = packet[7];
3167         switch (initiator_filter_policy){
3168             case 0:
3169                 // whitelist not used
3170                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3171                 break;
3172             case 1:
3173                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3174                 break;
3175             default:
3176                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3177                 break;
3178         }
3179     }
3180     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3181         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3182     }
3183 #endif
3184 #endif
3185 
3186     hci_stack->num_cmd_packets--;
3187 
3188     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3189     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3190 
3191     // release packet buffer for synchronous transport implementations
3192     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
3193         hci_stack->hci_packet_buffer_reserved = 0;
3194     }
3195 
3196     return err;
3197 }
3198 
3199 // disconnect because of security block
3200 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3201     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3202     if (!connection) return;
3203     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3204 }
3205 
3206 
3207 // Configure Secure Simple Pairing
3208 
3209 #ifdef ENABLE_CLASSIC
3210 
3211 // enable will enable SSP during init
3212 void gap_ssp_set_enable(int enable){
3213     hci_stack->ssp_enable = enable;
3214 }
3215 
3216 static int hci_local_ssp_activated(void){
3217     return gap_ssp_supported() && hci_stack->ssp_enable;
3218 }
3219 
3220 // if set, BTstack will respond to io capability request using authentication requirement
3221 void gap_ssp_set_io_capability(int io_capability){
3222     hci_stack->ssp_io_capability = io_capability;
3223 }
3224 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3225     hci_stack->ssp_authentication_requirement = authentication_requirement;
3226 }
3227 
3228 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3229 void gap_ssp_set_auto_accept(int auto_accept){
3230     hci_stack->ssp_auto_accept = auto_accept;
3231 }
3232 #endif
3233 
3234 // va_list part of hci_send_cmd
3235 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3236     if (!hci_can_send_command_packet_now()){
3237         log_error("hci_send_cmd called but cannot send packet now");
3238         return 0;
3239     }
3240 
3241     // for HCI INITIALIZATION
3242     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3243     hci_stack->last_cmd_opcode = cmd->opcode;
3244 
3245     hci_reserve_packet_buffer();
3246     uint8_t * packet = hci_stack->hci_packet_buffer;
3247     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3248     return hci_send_cmd_packet(packet, size);
3249 }
3250 
3251 /**
3252  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3253  */
3254 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3255     va_list argptr;
3256     va_start(argptr, cmd);
3257     int res = hci_send_cmd_va_arg(cmd, argptr);
3258     va_end(argptr);
3259     return res;
3260 }
3261 
3262 // Create various non-HCI events.
3263 // TODO: generalize, use table similar to hci_create_command
3264 
3265 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3266     // dump packet
3267     if (dump) {
3268         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3269     }
3270 
3271     // dispatch to all event handlers
3272     btstack_linked_list_iterator_t it;
3273     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3274     while (btstack_linked_list_iterator_has_next(&it)){
3275         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3276         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3277     }
3278 }
3279 
3280 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3281     if (!hci_stack->acl_packet_handler) return;
3282     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3283 }
3284 
3285 #ifdef ENABLE_CLASSIC
3286 static void hci_notify_if_sco_can_send_now(void){
3287     // notify SCO sender if waiting
3288     if (!hci_stack->sco_waiting_for_can_send_now) return;
3289     if (hci_can_send_sco_packet_now()){
3290         hci_stack->sco_waiting_for_can_send_now = 0;
3291         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3292         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3293         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3294     }
3295 }
3296 #endif
3297 
3298 void hci_emit_state(void){
3299     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3300     uint8_t event[3];
3301     event[0] = BTSTACK_EVENT_STATE;
3302     event[1] = sizeof(event) - 2;
3303     event[2] = hci_stack->state;
3304     hci_emit_event(event, sizeof(event), 1);
3305 }
3306 
3307 #ifdef ENABLE_CLASSIC
3308 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3309     uint8_t event[13];
3310     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3311     event[1] = sizeof(event) - 2;
3312     event[2] = status;
3313     little_endian_store_16(event, 3, con_handle);
3314     reverse_bd_addr(address, &event[5]);
3315     event[11] = 1; // ACL connection
3316     event[12] = 0; // encryption disabled
3317     hci_emit_event(event, sizeof(event), 1);
3318 }
3319 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3320     if (disable_l2cap_timeouts) return;
3321     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3322     uint8_t event[4];
3323     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3324     event[1] = sizeof(event) - 2;
3325     little_endian_store_16(event, 2, conn->con_handle);
3326     hci_emit_event(event, sizeof(event), 1);
3327 }
3328 #endif
3329 
3330 #ifdef ENABLE_BLE
3331 #ifdef ENABLE_LE_CENTRAL
3332 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3333     uint8_t event[21];
3334     event[0] = HCI_EVENT_LE_META;
3335     event[1] = sizeof(event) - 2;
3336     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
3337     event[3] = status;
3338     little_endian_store_16(event, 4, con_handle);
3339     event[6] = 0; // TODO: role
3340     event[7] = address_type;
3341     reverse_bd_addr(address, &event[8]);
3342     little_endian_store_16(event, 14, 0); // interval
3343     little_endian_store_16(event, 16, 0); // latency
3344     little_endian_store_16(event, 18, 0); // supervision timeout
3345     event[20] = 0; // master clock accuracy
3346     hci_emit_event(event, sizeof(event), 1);
3347 }
3348 #endif
3349 #endif
3350 
3351 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
3352     uint8_t event[6];
3353     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
3354     event[1] = sizeof(event) - 2;
3355     event[2] = 0; // status = OK
3356     little_endian_store_16(event, 3, con_handle);
3357     event[5] = reason;
3358     hci_emit_event(event, sizeof(event), 1);
3359 }
3360 
3361 static void hci_emit_nr_connections_changed(void){
3362     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
3363     uint8_t event[3];
3364     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3365     event[1] = sizeof(event) - 2;
3366     event[2] = nr_hci_connections();
3367     hci_emit_event(event, sizeof(event), 1);
3368 }
3369 
3370 static void hci_emit_hci_open_failed(void){
3371     log_info("BTSTACK_EVENT_POWERON_FAILED");
3372     uint8_t event[2];
3373     event[0] = BTSTACK_EVENT_POWERON_FAILED;
3374     event[1] = sizeof(event) - 2;
3375     hci_emit_event(event, sizeof(event), 1);
3376 }
3377 
3378 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
3379     log_info("hci_emit_dedicated_bonding_result %u ", status);
3380     uint8_t event[9];
3381     int pos = 0;
3382     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
3383     event[pos++] = sizeof(event) - 2;
3384     event[pos++] = status;
3385     reverse_bd_addr(address, &event[pos]);
3386     hci_emit_event(event, sizeof(event), 1);
3387 }
3388 
3389 
3390 #ifdef ENABLE_CLASSIC
3391 
3392 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3393     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3394     uint8_t event[5];
3395     int pos = 0;
3396     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3397     event[pos++] = sizeof(event) - 2;
3398     little_endian_store_16(event, 2, con_handle);
3399     pos += 2;
3400     event[pos++] = level;
3401     hci_emit_event(event, sizeof(event), 1);
3402 }
3403 
3404 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
3405     if (!connection) return LEVEL_0;
3406     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
3407     return gap_security_level_for_link_key_type(connection->link_key_type);
3408 }
3409 
3410 static void hci_emit_discoverable_enabled(uint8_t enabled){
3411     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
3412     uint8_t event[3];
3413     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
3414     event[1] = sizeof(event) - 2;
3415     event[2] = enabled;
3416     hci_emit_event(event, sizeof(event), 1);
3417 }
3418 
3419 #ifdef ENABLE_CLASSIC
3420 // query if remote side supports eSCO
3421 int hci_remote_esco_supported(hci_con_handle_t con_handle){
3422     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3423     if (!connection) return 0;
3424     return connection->remote_supported_feature_eSCO;
3425 }
3426 
3427 // query if remote side supports SSP
3428 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
3429     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3430     if (!connection) return 0;
3431     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
3432 }
3433 
3434 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
3435     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3436 }
3437 #endif
3438 
3439 // GAP API
3440 /**
3441  * @bbrief enable/disable bonding. default is enabled
3442  * @praram enabled
3443  */
3444 void gap_set_bondable_mode(int enable){
3445     hci_stack->bondable = enable ? 1 : 0;
3446 }
3447 /**
3448  * @brief Get bondable mode.
3449  * @return 1 if bondable
3450  */
3451 int gap_get_bondable_mode(void){
3452     return hci_stack->bondable;
3453 }
3454 
3455 /**
3456  * @brief map link keys to security levels
3457  */
3458 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
3459     switch (link_key_type){
3460         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
3461             return LEVEL_4;
3462         case COMBINATION_KEY:
3463         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
3464             return LEVEL_3;
3465         default:
3466             return LEVEL_2;
3467     }
3468 }
3469 
3470 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
3471     log_info("gap_mitm_protection_required_for_security_level %u", level);
3472     return level > LEVEL_2;
3473 }
3474 
3475 /**
3476  * @brief get current security level
3477  */
3478 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
3479     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3480     if (!connection) return LEVEL_0;
3481     return gap_security_level_for_connection(connection);
3482 }
3483 
3484 /**
3485  * @brief request connection to device to
3486  * @result GAP_AUTHENTICATION_RESULT
3487  */
3488 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
3489     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3490     if (!connection){
3491         hci_emit_security_level(con_handle, LEVEL_0);
3492         return;
3493     }
3494     gap_security_level_t current_level = gap_security_level(con_handle);
3495     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
3496     if (current_level >= requested_level){
3497         hci_emit_security_level(con_handle, current_level);
3498         return;
3499     }
3500 
3501     connection->requested_security_level = requested_level;
3502 
3503 #if 0
3504     // sending encryption request without a link key results in an error.
3505     // TODO: figure out how to use it properly
3506 
3507     // would enabling ecnryption suffice (>= LEVEL_2)?
3508     if (hci_stack->link_key_db){
3509         link_key_type_t link_key_type;
3510         link_key_t      link_key;
3511         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3512             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3513                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3514                 return;
3515             }
3516         }
3517     }
3518 #endif
3519 
3520     // try to authenticate connection
3521     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3522     hci_run();
3523 }
3524 
3525 /**
3526  * @brief start dedicated bonding with device. disconnect after bonding
3527  * @param device
3528  * @param request MITM protection
3529  * @result GAP_DEDICATED_BONDING_COMPLETE
3530  */
3531 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3532 
3533     // create connection state machine
3534     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3535 
3536     if (!connection){
3537         return BTSTACK_MEMORY_ALLOC_FAILED;
3538     }
3539 
3540     // delete linkn key
3541     gap_drop_link_key_for_bd_addr(device);
3542 
3543     // configure LEVEL_2/3, dedicated bonding
3544     connection->state = SEND_CREATE_CONNECTION;
3545     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
3546     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
3547     connection->bonding_flags = BONDING_DEDICATED;
3548 
3549     // wait for GAP Security Result and send GAP Dedicated Bonding complete
3550 
3551     // handle: connnection failure (connection complete != ok)
3552     // handle: authentication failure
3553     // handle: disconnect on done
3554 
3555     hci_run();
3556 
3557     return 0;
3558 }
3559 #endif
3560 
3561 void gap_set_local_name(const char * local_name){
3562     hci_stack->local_name = local_name;
3563 }
3564 
3565 
3566 #ifdef ENABLE_BLE
3567 
3568 #ifdef ENABLE_LE_CENTRAL
3569 void gap_start_scan(void){
3570     if (hci_stack->le_scanning_state == LE_SCANNING) return;
3571     hci_stack->le_scanning_state = LE_START_SCAN;
3572     hci_run();
3573 }
3574 
3575 void gap_stop_scan(void){
3576     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return;
3577     hci_stack->le_scanning_state = LE_STOP_SCAN;
3578     hci_run();
3579 }
3580 
3581 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
3582     hci_stack->le_scan_type     = scan_type;
3583     hci_stack->le_scan_interval = scan_interval;
3584     hci_stack->le_scan_window   = scan_window;
3585     hci_run();
3586 }
3587 
3588 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
3589     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3590     if (!conn){
3591         log_info("gap_connect: no connection exists yet, creating context");
3592         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3593         if (!conn){
3594             // notify client that alloc failed
3595             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3596             log_info("gap_connect: failed to alloc hci_connection_t");
3597             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
3598         }
3599         conn->state = SEND_CREATE_CONNECTION;
3600         log_info("gap_connect: send create connection next");
3601         hci_run();
3602         return 0;
3603     }
3604 
3605     if (!hci_is_le_connection(conn) ||
3606         conn->state == SEND_CREATE_CONNECTION ||
3607         conn->state == SENT_CREATE_CONNECTION) {
3608         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
3609         log_error("gap_connect: classic connection or connect is already being created");
3610         return GATT_CLIENT_IN_WRONG_STATE;
3611     }
3612 
3613     log_info("gap_connect: context exists with state %u", conn->state);
3614     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
3615     hci_run();
3616     return 0;
3617 }
3618 
3619 // @assumption: only a single outgoing LE Connection exists
3620 static hci_connection_t * gap_get_outgoing_connection(void){
3621     btstack_linked_item_t *it;
3622     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3623         hci_connection_t * conn = (hci_connection_t *) it;
3624         if (!hci_is_le_connection(conn)) continue;
3625         switch (conn->state){
3626             case SEND_CREATE_CONNECTION:
3627             case SENT_CREATE_CONNECTION:
3628                 return conn;
3629             default:
3630                 break;
3631         };
3632     }
3633     return NULL;
3634 }
3635 
3636 uint8_t gap_connect_cancel(void){
3637     hci_connection_t * conn = gap_get_outgoing_connection();
3638     if (!conn) return 0;
3639     switch (conn->state){
3640         case SEND_CREATE_CONNECTION:
3641             // skip sending create connection and emit event instead
3642             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
3643             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
3644             btstack_memory_hci_connection_free( conn );
3645             break;
3646         case SENT_CREATE_CONNECTION:
3647             // request to send cancel connection
3648             conn->state = SEND_CANCEL_CONNECTION;
3649             hci_run();
3650             break;
3651         default:
3652             break;
3653     }
3654     return 0;
3655 }
3656 #endif
3657 
3658 /**
3659  * @brief Updates the connection parameters for a given LE connection
3660  * @param handle
3661  * @param conn_interval_min (unit: 1.25ms)
3662  * @param conn_interval_max (unit: 1.25ms)
3663  * @param conn_latency
3664  * @param supervision_timeout (unit: 10ms)
3665  * @returns 0 if ok
3666  */
3667 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3668     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3669     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3670     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3671     connection->le_conn_interval_min = conn_interval_min;
3672     connection->le_conn_interval_max = conn_interval_max;
3673     connection->le_conn_latency = conn_latency;
3674     connection->le_supervision_timeout = supervision_timeout;
3675     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
3676     hci_run();
3677     return 0;
3678 }
3679 
3680 /**
3681  * @brief Request an update of the connection parameter for a given LE connection
3682  * @param handle
3683  * @param conn_interval_min (unit: 1.25ms)
3684  * @param conn_interval_max (unit: 1.25ms)
3685  * @param conn_latency
3686  * @param supervision_timeout (unit: 10ms)
3687  * @returns 0 if ok
3688  */
3689 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3690     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3691     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3692     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3693     connection->le_conn_interval_min = conn_interval_min;
3694     connection->le_conn_interval_max = conn_interval_max;
3695     connection->le_conn_latency = conn_latency;
3696     connection->le_supervision_timeout = supervision_timeout;
3697     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
3698     hci_run();
3699     return 0;
3700 }
3701 
3702 #ifdef ENABLE_LE_PERIPHERAL
3703 
3704 static void gap_advertisments_changed(void){
3705     // disable advertisements before updating adv, scan data, or adv params
3706     if (hci_stack->le_advertisements_active){
3707         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
3708     }
3709     hci_run();
3710 }
3711 
3712 /**
3713  * @brief Set Advertisement Data
3714  * @param advertising_data_length
3715  * @param advertising_data (max 31 octets)
3716  * @note data is not copied, pointer has to stay valid
3717  */
3718 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
3719     hci_stack->le_advertisements_data_len = advertising_data_length;
3720     hci_stack->le_advertisements_data = advertising_data;
3721     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3722     gap_advertisments_changed();
3723 }
3724 
3725 /**
3726  * @brief Set Scan Response Data
3727  * @param advertising_data_length
3728  * @param advertising_data (max 31 octets)
3729  * @note data is not copied, pointer has to stay valid
3730  */
3731 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
3732     hci_stack->le_scan_response_data_len = scan_response_data_length;
3733     hci_stack->le_scan_response_data = scan_response_data;
3734     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3735     gap_advertisments_changed();
3736 }
3737 
3738 /**
3739  * @brief Set Advertisement Parameters
3740  * @param adv_int_min
3741  * @param adv_int_max
3742  * @param adv_type
3743  * @param direct_address_type
3744  * @param direct_address
3745  * @param channel_map
3746  * @param filter_policy
3747  *
3748  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
3749  */
3750  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
3751     uint8_t direct_address_typ, bd_addr_t direct_address,
3752     uint8_t channel_map, uint8_t filter_policy) {
3753 
3754     hci_stack->le_advertisements_interval_min = adv_int_min;
3755     hci_stack->le_advertisements_interval_max = adv_int_max;
3756     hci_stack->le_advertisements_type = adv_type;
3757     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
3758     hci_stack->le_advertisements_channel_map = channel_map;
3759     hci_stack->le_advertisements_filter_policy = filter_policy;
3760     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
3761 
3762     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3763     gap_advertisments_changed();
3764  }
3765 
3766 /**
3767  * @brief Enable/Disable Advertisements
3768  * @param enabled
3769  */
3770 void gap_advertisements_enable(int enabled){
3771     hci_stack->le_advertisements_enabled = enabled;
3772     if (enabled && !hci_stack->le_advertisements_active){
3773         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
3774     }
3775     if (!enabled && hci_stack->le_advertisements_active){
3776         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
3777     }
3778     hci_run();
3779 }
3780 
3781 #endif
3782 
3783 void hci_le_set_own_address_type(uint8_t own_address_type){
3784     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
3785     if (own_address_type == hci_stack->le_own_addr_type) return;
3786     hci_stack->le_own_addr_type = own_address_type;
3787 
3788 #ifdef ENABLE_LE_PERIPHERAL
3789     // update advertisement parameters, too
3790     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3791     gap_advertisments_changed();
3792 #endif
3793 #ifdef ENABLE_LE_CENTRAL
3794     // note: we don't update scan parameters or modify ongoing connection attempts
3795 #endif
3796 }
3797 
3798 #endif
3799 
3800 uint8_t gap_disconnect(hci_con_handle_t handle){
3801     hci_connection_t * conn = hci_connection_for_handle(handle);
3802     if (!conn){
3803         hci_emit_disconnection_complete(handle, 0);
3804         return 0;
3805     }
3806     conn->state = SEND_DISCONNECT;
3807     hci_run();
3808     return 0;
3809 }
3810 
3811 /**
3812  * @brief Get connection type
3813  * @param con_handle
3814  * @result connection_type
3815  */
3816 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
3817     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
3818     if (!conn) return GAP_CONNECTION_INVALID;
3819     switch (conn->address_type){
3820         case BD_ADDR_TYPE_LE_PUBLIC:
3821         case BD_ADDR_TYPE_LE_RANDOM:
3822             return GAP_CONNECTION_LE;
3823         case BD_ADDR_TYPE_SCO:
3824             return GAP_CONNECTION_SCO;
3825         case BD_ADDR_TYPE_CLASSIC:
3826             return GAP_CONNECTION_ACL;
3827         default:
3828             return GAP_CONNECTION_INVALID;
3829     }
3830 }
3831 
3832 #ifdef ENABLE_BLE
3833 
3834 #ifdef ENABLE_LE_CENTRAL
3835 /**
3836  * @brief Auto Connection Establishment - Start Connecting to device
3837  * @param address_typ
3838  * @param address
3839  * @returns 0 if ok
3840  */
3841 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
3842     // check capacity
3843     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
3844     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3845     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
3846     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
3847     entry->address_type = address_type;
3848     memcpy(entry->address, address, 6);
3849     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
3850     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
3851     hci_run();
3852     return 0;
3853 }
3854 
3855 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
3856     btstack_linked_list_iterator_t it;
3857     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3858     while (btstack_linked_list_iterator_has_next(&it)){
3859         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3860         if (entry->address_type != address_type) continue;
3861         if (memcmp(entry->address, address, 6) != 0) continue;
3862         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3863             // remove from controller if already present
3864             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3865             continue;
3866         }
3867         // direclty remove entry from whitelist
3868         btstack_linked_list_iterator_remove(&it);
3869         btstack_memory_whitelist_entry_free(entry);
3870     }
3871 }
3872 
3873 /**
3874  * @brief Auto Connection Establishment - Stop Connecting to device
3875  * @param address_typ
3876  * @param address
3877  * @returns 0 if ok
3878  */
3879 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
3880     hci_remove_from_whitelist(address_type, address);
3881     hci_run();
3882     return 0;
3883 }
3884 
3885 /**
3886  * @brief Auto Connection Establishment - Stop everything
3887  * @note  Convenience function to stop all active auto connection attempts
3888  */
3889 void gap_auto_connection_stop_all(void){
3890     btstack_linked_list_iterator_t it;
3891     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3892     while (btstack_linked_list_iterator_has_next(&it)){
3893         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3894         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3895             // remove from controller if already present
3896             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3897             continue;
3898         }
3899         // directly remove entry from whitelist
3900         btstack_linked_list_iterator_remove(&it);
3901         btstack_memory_whitelist_entry_free(entry);
3902     }
3903     hci_run();
3904 }
3905 #endif
3906 #endif
3907 
3908 #ifdef ENABLE_CLASSIC
3909 /**
3910  * @brief Set Extended Inquiry Response data
3911  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
3912  * @note has to be done before stack starts up
3913  */
3914 void gap_set_extended_inquiry_response(const uint8_t * data){
3915     hci_stack->eir_data = data;
3916 }
3917 
3918 /**
3919  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
3920  * @param inquriy_mode see bluetooth_defines.h
3921  */
3922 void hci_set_inquiry_mode(inquiry_mode_t mode){
3923     hci_stack->inquiry_mode = mode;
3924 }
3925 
3926 /**
3927  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
3928  */
3929 void hci_set_sco_voice_setting(uint16_t voice_setting){
3930     hci_stack->sco_voice_setting = voice_setting;
3931 }
3932 
3933 /**
3934  * @brief Get SCO Voice Setting
3935  * @return current voice setting
3936  */
3937 uint16_t hci_get_sco_voice_setting(void){
3938     return hci_stack->sco_voice_setting;
3939 }
3940 
3941 /** @brief Get SCO packet length for current SCO Voice setting
3942  *  @note  Using SCO packets of the exact length is required for USB transfer
3943  *  @return Length of SCO packets in bytes (not audio frames)
3944  */
3945 int hci_get_sco_packet_length(void){
3946     // see Core Spec for H2 USB Transfer.
3947     if (hci_stack->sco_voice_setting & 0x0020) return 51;
3948     return 27;
3949 }
3950 #endif
3951 
3952 /**
3953  * @brief Set callback for Bluetooth Hardware Error
3954  */
3955 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
3956     hci_stack->hardware_error_callback = fn;
3957 }
3958 
3959 void hci_disconnect_all(void){
3960     btstack_linked_list_iterator_t it;
3961     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
3962     while (btstack_linked_list_iterator_has_next(&it)){
3963         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
3964         if (con->state == SENT_DISCONNECT) continue;
3965         con->state = SEND_DISCONNECT;
3966     }
3967     hci_run();
3968 }
3969 
3970 uint16_t hci_get_manufacturer(void){
3971     return hci_stack->manufacturer;
3972 }
3973