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