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