xref: /btstack/src/hci.c (revision f3b012f9c751214cad32f85758fbb939f3911c04)
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                 // from offset 5
1572                 // status
1573                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1574                 hci_stack->acl_data_packet_length = little_endian_read_16(packet, 6);
1575                 hci_stack->sco_data_packet_length = packet[8];
1576                 hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1577                 hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1578 
1579                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1580                     // determine usable ACL payload size
1581                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
1582                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1583                     }
1584                     log_info("hci_read_buffer_size: acl used size %u, count %u / sco size %u, count %u",
1585                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1586                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1587                 }
1588             }
1589 #ifdef ENABLE_BLE
1590             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1591                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1592                 hci_stack->le_acl_packets_total_num  = packet[8];
1593                     // determine usable ACL payload size
1594                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1595                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1596                     }
1597                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1598             }
1599 #ifdef ENABLE_LE_CENTRAL
1600             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1601                 hci_stack->le_whitelist_capacity = packet[6];
1602                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1603             }
1604 #endif
1605 #endif
1606             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1607                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1608 				hci_stack->local_bd_addr);
1609                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1610                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1611 #ifdef ENABLE_CLASSIC
1612                 if (hci_stack->link_key_db){
1613                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1614                 }
1615 #endif
1616             }
1617 #ifdef ENABLE_CLASSIC
1618             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1619                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1620             }
1621 #endif
1622 
1623             // Note: HCI init checks
1624             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1625                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1626 
1627 #ifdef ENABLE_CLASSIC
1628                 // determine usable ACL packet types based on host buffer size and supported features
1629                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1630                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
1631 #endif
1632                 // Classic/LE
1633                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1634             }
1635             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1636                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1637                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1638                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1639                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1640                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1641                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1642             }
1643             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1644                 hci_stack->local_supported_commands[0] =
1645                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7
1646                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6
1647                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4
1648                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08);        // bit 3 = Octet 18, bit 3
1649                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1650             }
1651 #ifdef ENABLE_CLASSIC
1652             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1653                 if (packet[5] == 0){
1654                     hci_stack->synchronous_flow_control_enabled = 1;
1655                 }
1656             }
1657 #endif
1658             break;
1659 
1660         case HCI_EVENT_COMMAND_STATUS:
1661             // get num cmd packets - limit to 1 to reduce complexity
1662             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
1663             break;
1664 
1665         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1666             int offset = 3;
1667             for (i=0; i<packet[2];i++){
1668                 handle = little_endian_read_16(packet, offset);
1669                 offset += 2;
1670                 uint16_t num_packets = little_endian_read_16(packet, offset);
1671                 offset += 2;
1672 
1673                 conn = hci_connection_for_handle(handle);
1674                 if (!conn){
1675                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1676                     continue;
1677                 }
1678 
1679                 if (conn->address_type == BD_ADDR_TYPE_SCO){
1680 #ifdef ENABLE_CLASSIC
1681                     if (conn->num_sco_packets_sent >= num_packets){
1682                         conn->num_sco_packets_sent -= num_packets;
1683                     } else {
1684                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1685                         conn->num_sco_packets_sent = 0;
1686                     }
1687                     hci_notify_if_sco_can_send_now();
1688 #endif
1689                 } else {
1690                     if (conn->num_acl_packets_sent >= num_packets){
1691                         conn->num_acl_packets_sent -= num_packets;
1692                     } else {
1693                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
1694                         conn->num_acl_packets_sent = 0;
1695                     }
1696                 }
1697                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1698             }
1699             break;
1700         }
1701 
1702 #ifdef ENABLE_CLASSIC
1703         case HCI_EVENT_CONNECTION_REQUEST:
1704             reverse_bd_addr(&packet[2], addr);
1705             // TODO: eval COD 8-10
1706             link_type = packet[11];
1707             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1708             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
1709             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1710             if (!conn) {
1711                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1712             }
1713             if (!conn) {
1714                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1715                 hci_stack->decline_reason = 0x0d;
1716                 bd_addr_copy(hci_stack->decline_addr, addr);
1717                 break;
1718             }
1719             conn->role  = HCI_ROLE_SLAVE;
1720             conn->state = RECEIVED_CONNECTION_REQUEST;
1721             // store info about eSCO
1722             if (link_type == 0x02){
1723                 conn->remote_supported_feature_eSCO = 1;
1724             }
1725             hci_run();
1726             break;
1727 
1728         case HCI_EVENT_CONNECTION_COMPLETE:
1729             // Connection management
1730             reverse_bd_addr(&packet[5], addr);
1731             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1732             addr_type = BD_ADDR_TYPE_CLASSIC;
1733             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1734             if (conn) {
1735                 if (!packet[2]){
1736                     conn->state = OPEN;
1737                     conn->con_handle = little_endian_read_16(packet, 3);
1738                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1739 
1740                     // restart timer
1741                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1742                     btstack_run_loop_add_timer(&conn->timeout);
1743 
1744                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1745 
1746                     hci_emit_nr_connections_changed();
1747                 } else {
1748                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1749                     uint8_t status = packet[2];
1750                     bd_addr_t bd_address;
1751                     memcpy(&bd_address, conn->address, 6);
1752 
1753                     // connection failed, remove entry
1754                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1755                     btstack_memory_hci_connection_free( conn );
1756 
1757                     // notify client if dedicated bonding
1758                     if (notify_dedicated_bonding_failed){
1759                         log_info("hci notify_dedicated_bonding_failed");
1760                         hci_emit_dedicated_bonding_result(bd_address, status);
1761                     }
1762 
1763                     // if authentication error, also delete link key
1764                     if (packet[2] == 0x05) {
1765                         gap_drop_link_key_for_bd_addr(addr);
1766                     }
1767                 }
1768             }
1769             break;
1770 
1771         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1772             reverse_bd_addr(&packet[5], addr);
1773             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1774             if (packet[2]){
1775                 // connection failed
1776                 break;
1777             }
1778             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1779             if (!conn) {
1780                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1781             }
1782             if (!conn) {
1783                 break;
1784             }
1785             conn->state = OPEN;
1786             conn->con_handle = little_endian_read_16(packet, 3);
1787 
1788 #ifdef ENABLE_SCO_OVER_HCI
1789             // update SCO
1790             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
1791                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1792             }
1793 #endif
1794             break;
1795 
1796         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1797             handle = little_endian_read_16(packet, 3);
1798             conn = hci_connection_for_handle(handle);
1799             if (!conn) break;
1800             if (!packet[2]){
1801                 uint8_t * features = &packet[5];
1802                 if (features[6] & (1 << 3)){
1803                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1804                 }
1805                 if (features[3] & (1<<7)){
1806                     conn->remote_supported_feature_eSCO = 1;
1807                 }
1808             }
1809             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1810             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
1811             if (conn->bonding_flags & BONDING_DEDICATED){
1812                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1813             }
1814             break;
1815 
1816         case HCI_EVENT_LINK_KEY_REQUEST:
1817             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1818             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1819             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1820             if (hci_stack->bondable && !hci_stack->link_key_db) break;
1821             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1822             hci_run();
1823             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1824             return;
1825 
1826         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1827             reverse_bd_addr(&packet[2], addr);
1828             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1829             if (!conn) break;
1830             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1831             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1832             // Change Connection Encryption keeps link key type
1833             if (link_key_type != CHANGED_COMBINATION_KEY){
1834                 conn->link_key_type = link_key_type;
1835             }
1836             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
1837             // still forward event to allow dismiss of pairing dialog
1838             break;
1839         }
1840 
1841         case HCI_EVENT_PIN_CODE_REQUEST:
1842             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1843             // non-bondable mode: pin code negative reply will be sent
1844             if (!hci_stack->bondable){
1845                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1846                 hci_run();
1847                 return;
1848             }
1849             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1850             if (!hci_stack->link_key_db) break;
1851             hci_event_pin_code_request_get_bd_addr(packet, addr);
1852             hci_stack->link_key_db->delete_link_key(addr);
1853             break;
1854 
1855         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1856             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1857             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1858             break;
1859 
1860         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
1861             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1862             if (!hci_stack->ssp_auto_accept) break;
1863             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1864             break;
1865 
1866         case HCI_EVENT_USER_PASSKEY_REQUEST:
1867             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1868             if (!hci_stack->ssp_auto_accept) break;
1869             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1870             break;
1871 #endif
1872 
1873         case HCI_EVENT_ENCRYPTION_CHANGE:
1874             handle = little_endian_read_16(packet, 3);
1875             conn = hci_connection_for_handle(handle);
1876             if (!conn) break;
1877             if (packet[2] == 0) {
1878                 if (packet[5]){
1879                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1880                 } else {
1881                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1882                 }
1883             }
1884 #ifdef ENABLE_CLASSIC
1885             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1886 #endif
1887             break;
1888 
1889 #ifdef ENABLE_CLASSIC
1890         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1891             handle = little_endian_read_16(packet, 3);
1892             conn = hci_connection_for_handle(handle);
1893             if (!conn) break;
1894 
1895             // dedicated bonding: send result and disconnect
1896             if (conn->bonding_flags & BONDING_DEDICATED){
1897                 conn->bonding_flags &= ~BONDING_DEDICATED;
1898                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1899                 conn->bonding_status = packet[2];
1900                 break;
1901             }
1902 
1903             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1904                 // link key sufficient for requested security
1905                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1906                 break;
1907             }
1908             // not enough
1909             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1910             break;
1911 #endif
1912 
1913         // HCI_EVENT_DISCONNECTION_COMPLETE
1914         // has been split, to first notify stack before shutting connection down
1915         // see end of function, too.
1916         case HCI_EVENT_DISCONNECTION_COMPLETE:
1917             if (packet[2]) break;   // status != 0
1918             handle = little_endian_read_16(packet, 3);
1919             // drop outgoing ACL fragments if it is for closed connection
1920             if (hci_stack->acl_fragmentation_total_size > 0) {
1921                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
1922                     log_info("hci: drop fragmented ACL data for closed connection");
1923                      hci_stack->acl_fragmentation_total_size = 0;
1924                      hci_stack->acl_fragmentation_pos = 0;
1925                 }
1926             }
1927 
1928             // re-enable advertisements for le connections if active
1929             conn = hci_connection_for_handle(handle);
1930             if (!conn) break;
1931 #ifdef ENABLE_BLE
1932 #ifdef ENABLE_LE_PERIPHERAL
1933             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
1934                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
1935             }
1936 #endif
1937 #endif
1938             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1939             break;
1940 
1941         case HCI_EVENT_HARDWARE_ERROR:
1942             log_error("Hardware Error: 0x%02x", packet[2]);
1943             if (hci_stack->hardware_error_callback){
1944                 (*hci_stack->hardware_error_callback)(packet[2]);
1945             } else {
1946                 // if no special requests, just reboot stack
1947                 hci_power_control_off();
1948                 hci_power_control_on();
1949             }
1950             break;
1951 
1952 #ifdef ENABLE_CLASSIC
1953         case HCI_EVENT_ROLE_CHANGE:
1954             if (packet[2]) break;   // status != 0
1955             handle = little_endian_read_16(packet, 3);
1956             conn = hci_connection_for_handle(handle);
1957             if (!conn) break;       // no conn
1958             conn->role = packet[9];
1959             break;
1960 #endif
1961 
1962         case HCI_EVENT_TRANSPORT_PACKET_SENT:
1963             // release packet buffer only for asynchronous transport and if there are not further fragements
1964             if (hci_transport_synchronous()) {
1965                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
1966                 return; // instead of break: to avoid re-entering hci_run()
1967             }
1968             if (hci_stack->acl_fragmentation_total_size) break;
1969             hci_release_packet_buffer();
1970 
1971             // L2CAP receives this event via the hci_emit_event below
1972 
1973 #ifdef ENABLE_CLASSIC
1974             // For SCO, we do the can_send_now_check here
1975             hci_notify_if_sco_can_send_now();
1976 #endif
1977             break;
1978 
1979 #ifdef ENABLE_CLASSIC
1980         case HCI_EVENT_SCO_CAN_SEND_NOW:
1981             // For SCO, we do the can_send_now_check here
1982             hci_notify_if_sco_can_send_now();
1983             return;
1984 #endif
1985 
1986 #ifdef ENABLE_BLE
1987         case HCI_EVENT_LE_META:
1988             switch (packet[2]){
1989 #ifdef ENABLE_LE_CENTRAL
1990                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1991                     // log_info("advertising report received");
1992                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1993                     le_handle_advertisement_report(packet, size);
1994                     break;
1995 #endif
1996                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1997                     // Connection management
1998                     reverse_bd_addr(&packet[8], addr);
1999                     addr_type = (bd_addr_type_t)packet[7];
2000                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2001                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2002 #ifdef ENABLE_LE_CENTRAL
2003                     // if auto-connect, remove from whitelist in both roles
2004                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
2005                         hci_remove_from_whitelist(addr_type, addr);
2006                     }
2007                     // handle error: error is reported only to the initiator -> outgoing connection
2008                     if (packet[3]){
2009                         // outgoing connection establishment is done
2010                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2011                         // remove entry
2012                         if (conn){
2013                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2014                             btstack_memory_hci_connection_free( conn );
2015                         }
2016                         break;
2017                     }
2018 #endif
2019                     // on success, both hosts receive connection complete event
2020                     if (packet[6] == HCI_ROLE_MASTER){
2021 #ifdef ENABLE_LE_CENTRAL
2022                         // if we're master, it was an outgoing connection and we're done with it
2023                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2024 #endif
2025                     } else {
2026 #ifdef ENABLE_LE_PERIPHERAL
2027                         // if we're slave, it was an incoming connection, advertisements have stopped
2028                         hci_stack->le_advertisements_active = 0;
2029                         // try to re-enable them
2030                         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2031 #endif
2032                     }
2033                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2034                     if (!conn){
2035                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2036                     }
2037                     // no memory, sorry.
2038                     if (!conn){
2039                         break;
2040                     }
2041 
2042                     conn->state = OPEN;
2043                     conn->role  = packet[6];
2044                     conn->con_handle = little_endian_read_16(packet, 4);
2045 
2046                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2047 
2048                     // restart timer
2049                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2050                     // btstack_run_loop_add_timer(&conn->timeout);
2051 
2052                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2053 
2054                     hci_emit_nr_connections_changed();
2055                     break;
2056 
2057             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2058 
2059                 default:
2060                     break;
2061             }
2062             break;
2063 #endif
2064         default:
2065             break;
2066     }
2067 
2068     // handle BT initialization
2069     if (hci_stack->state == HCI_STATE_INITIALIZING){
2070         hci_initializing_event_handler(packet, size);
2071     }
2072 
2073     // help with BT sleep
2074     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2075         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2076         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2077         hci_initializing_next_state();
2078     }
2079 
2080     // notify upper stack
2081 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2082 
2083     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2084     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2085         if (!packet[2]){
2086             handle = little_endian_read_16(packet, 3);
2087             hci_connection_t * aConn = hci_connection_for_handle(handle);
2088             if (aConn) {
2089                 uint8_t status = aConn->bonding_status;
2090                 uint16_t flags = aConn->bonding_flags;
2091                 bd_addr_t bd_address;
2092                 memcpy(&bd_address, aConn->address, 6);
2093                 hci_shutdown_connection(aConn);
2094                 // connection struct is gone, don't access anymore
2095                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2096                     hci_emit_dedicated_bonding_result(bd_address, status);
2097                 }
2098             }
2099         }
2100     }
2101 
2102 	// execute main loop
2103 	hci_run();
2104 }
2105 
2106 #ifdef ENABLE_CLASSIC
2107 static void sco_handler(uint8_t * packet, uint16_t size){
2108     if (!hci_stack->sco_packet_handler) return;
2109     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2110 }
2111 #endif
2112 
2113 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2114     hci_dump_packet(packet_type, 1, packet, size);
2115     switch (packet_type) {
2116         case HCI_EVENT_PACKET:
2117             event_handler(packet, size);
2118             break;
2119         case HCI_ACL_DATA_PACKET:
2120             acl_handler(packet, size);
2121             break;
2122 #ifdef ENABLE_CLASSIC
2123         case HCI_SCO_DATA_PACKET:
2124             sco_handler(packet, size);
2125             break;
2126 #endif
2127         default:
2128             break;
2129     }
2130 }
2131 
2132 /**
2133  * @brief Add event packet handler.
2134  */
2135 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2136     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2137 }
2138 
2139 
2140 /** Register HCI packet handlers */
2141 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2142     hci_stack->acl_packet_handler = handler;
2143 }
2144 
2145 #ifdef ENABLE_CLASSIC
2146 /**
2147  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2148  */
2149 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2150     hci_stack->sco_packet_handler = handler;
2151 }
2152 #endif
2153 
2154 static void hci_state_reset(void){
2155     // no connections yet
2156     hci_stack->connections = NULL;
2157 
2158     // keep discoverable/connectable as this has been requested by the client(s)
2159     // hci_stack->discoverable = 0;
2160     // hci_stack->connectable = 0;
2161     // hci_stack->bondable = 1;
2162     // hci_stack->own_addr_type = 0;
2163 
2164     // buffer is free
2165     hci_stack->hci_packet_buffer_reserved = 0;
2166 
2167     // no pending cmds
2168     hci_stack->decline_reason = 0;
2169     hci_stack->new_scan_enable_value = 0xff;
2170 
2171     // LE
2172 #ifdef ENABLE_BLE
2173     memset(hci_stack->le_random_address, 0, 6);
2174     hci_stack->le_random_address_set = 0;
2175 #endif
2176 #ifdef ENABLE_LE_CENTRAL
2177     hci_stack->le_scanning_state = LE_SCAN_IDLE;
2178     hci_stack->le_scan_type = 0xff;
2179     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2180     hci_stack->le_whitelist = 0;
2181     hci_stack->le_whitelist_capacity = 0;
2182 #endif
2183 
2184     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2185     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2186     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2187     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2188     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2189     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2190 }
2191 
2192 #ifdef ENABLE_CLASSIC
2193 /**
2194  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2195  */
2196 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2197     // store and open remote device db
2198     hci_stack->link_key_db = link_key_db;
2199     if (hci_stack->link_key_db) {
2200         hci_stack->link_key_db->open();
2201     }
2202 }
2203 #endif
2204 
2205 void hci_init(const hci_transport_t *transport, const void *config){
2206 
2207 #ifdef HAVE_MALLOC
2208     if (!hci_stack) {
2209         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2210     }
2211 #else
2212     hci_stack = &hci_stack_static;
2213 #endif
2214     memset(hci_stack, 0, sizeof(hci_stack_t));
2215 
2216     // reference to use transport layer implementation
2217     hci_stack->hci_transport = transport;
2218 
2219     // reference to used config
2220     hci_stack->config = config;
2221 
2222     // setup pointer for outgoing packet buffer
2223     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2224 
2225     // max acl payload size defined in config.h
2226     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2227 
2228     // register packet handlers with transport
2229     transport->register_packet_handler(&packet_handler);
2230 
2231     hci_stack->state = HCI_STATE_OFF;
2232 
2233     // class of device
2234     hci_stack->class_of_device = 0x007a020c; // Smartphone
2235 
2236     // bondable by default
2237     hci_stack->bondable = 1;
2238 
2239     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2240     hci_stack->ssp_enable = 1;
2241     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2242     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2243     hci_stack->ssp_auto_accept = 1;
2244 
2245     // voice setting - signed 16 bit pcm data with CVSD over the air
2246     hci_stack->sco_voice_setting = 0x60;
2247 
2248     hci_state_reset();
2249 }
2250 
2251 /**
2252  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2253  */
2254 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2255     hci_stack->chipset = chipset_driver;
2256 
2257     // reset chipset driver - init is also called on power_up
2258     if (hci_stack->chipset && hci_stack->chipset->init){
2259         hci_stack->chipset->init(hci_stack->config);
2260     }
2261 }
2262 
2263 /**
2264  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2265  */
2266 void hci_set_control(const btstack_control_t *hardware_control){
2267     // references to used control implementation
2268     hci_stack->control = hardware_control;
2269     // init with transport config
2270     hardware_control->init(hci_stack->config);
2271 }
2272 
2273 void hci_close(void){
2274     // close remote device db
2275     if (hci_stack->link_key_db) {
2276         hci_stack->link_key_db->close();
2277     }
2278 
2279     btstack_linked_list_iterator_t lit;
2280     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2281     while (btstack_linked_list_iterator_has_next(&lit)){
2282         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2283         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2284         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2285         hci_shutdown_connection(connection);
2286     }
2287 
2288     hci_power_control(HCI_POWER_OFF);
2289 
2290 #ifdef HAVE_MALLOC
2291     free(hci_stack);
2292 #endif
2293     hci_stack = NULL;
2294 }
2295 
2296 #ifdef ENABLE_CLASSIC
2297 void gap_set_class_of_device(uint32_t class_of_device){
2298     hci_stack->class_of_device = class_of_device;
2299 }
2300 
2301 void hci_disable_l2cap_timeout_check(void){
2302     disable_l2cap_timeouts = 1;
2303 }
2304 #endif
2305 
2306 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2307 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2308 void hci_set_bd_addr(bd_addr_t addr){
2309     memcpy(hci_stack->custom_bd_addr, addr, 6);
2310     hci_stack->custom_bd_addr_set = 1;
2311 }
2312 #endif
2313 
2314 // State-Module-Driver overview
2315 // state                    module  low-level
2316 // HCI_STATE_OFF             off      close
2317 // HCI_STATE_INITIALIZING,   on       open
2318 // HCI_STATE_WORKING,        on       open
2319 // HCI_STATE_HALTING,        on       open
2320 // HCI_STATE_SLEEPING,    off/sleep   close
2321 // HCI_STATE_FALLING_ASLEEP  on       open
2322 
2323 static int hci_power_control_on(void){
2324 
2325     // power on
2326     int err = 0;
2327     if (hci_stack->control && hci_stack->control->on){
2328         err = (*hci_stack->control->on)();
2329     }
2330     if (err){
2331         log_error( "POWER_ON failed");
2332         hci_emit_hci_open_failed();
2333         return err;
2334     }
2335 
2336     // int chipset driver
2337     if (hci_stack->chipset && hci_stack->chipset->init){
2338         hci_stack->chipset->init(hci_stack->config);
2339     }
2340 
2341     // init transport
2342     if (hci_stack->hci_transport->init){
2343         hci_stack->hci_transport->init(hci_stack->config);
2344     }
2345 
2346     // open transport
2347     err = hci_stack->hci_transport->open();
2348     if (err){
2349         log_error( "HCI_INIT failed, turning Bluetooth off again");
2350         if (hci_stack->control && hci_stack->control->off){
2351             (*hci_stack->control->off)();
2352         }
2353         hci_emit_hci_open_failed();
2354         return err;
2355     }
2356     return 0;
2357 }
2358 
2359 static void hci_power_control_off(void){
2360 
2361     log_info("hci_power_control_off");
2362 
2363     // close low-level device
2364     hci_stack->hci_transport->close();
2365 
2366     log_info("hci_power_control_off - hci_transport closed");
2367 
2368     // power off
2369     if (hci_stack->control && hci_stack->control->off){
2370         (*hci_stack->control->off)();
2371     }
2372 
2373     log_info("hci_power_control_off - control closed");
2374 
2375     hci_stack->state = HCI_STATE_OFF;
2376 }
2377 
2378 static void hci_power_control_sleep(void){
2379 
2380     log_info("hci_power_control_sleep");
2381 
2382 #if 0
2383     // don't close serial port during sleep
2384 
2385     // close low-level device
2386     hci_stack->hci_transport->close(hci_stack->config);
2387 #endif
2388 
2389     // sleep mode
2390     if (hci_stack->control && hci_stack->control->sleep){
2391         (*hci_stack->control->sleep)();
2392     }
2393 
2394     hci_stack->state = HCI_STATE_SLEEPING;
2395 }
2396 
2397 static int hci_power_control_wake(void){
2398 
2399     log_info("hci_power_control_wake");
2400 
2401     // wake on
2402     if (hci_stack->control && hci_stack->control->wake){
2403         (*hci_stack->control->wake)();
2404     }
2405 
2406 #if 0
2407     // open low-level device
2408     int err = hci_stack->hci_transport->open(hci_stack->config);
2409     if (err){
2410         log_error( "HCI_INIT failed, turning Bluetooth off again");
2411         if (hci_stack->control && hci_stack->control->off){
2412             (*hci_stack->control->off)();
2413         }
2414         hci_emit_hci_open_failed();
2415         return err;
2416     }
2417 #endif
2418 
2419     return 0;
2420 }
2421 
2422 static void hci_power_transition_to_initializing(void){
2423     // set up state machine
2424     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2425     hci_stack->hci_packet_buffer_reserved = 0;
2426     hci_stack->state = HCI_STATE_INITIALIZING;
2427     hci_stack->substate = HCI_INIT_SEND_RESET;
2428 }
2429 
2430 int hci_power_control(HCI_POWER_MODE power_mode){
2431 
2432     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2433 
2434     int err = 0;
2435     switch (hci_stack->state){
2436 
2437         case HCI_STATE_OFF:
2438             switch (power_mode){
2439                 case HCI_POWER_ON:
2440                     err = hci_power_control_on();
2441                     if (err) {
2442                         log_error("hci_power_control_on() error %d", err);
2443                         return err;
2444                     }
2445                     hci_power_transition_to_initializing();
2446                     break;
2447                 case HCI_POWER_OFF:
2448                     // do nothing
2449                     break;
2450                 case HCI_POWER_SLEEP:
2451                     // do nothing (with SLEEP == OFF)
2452                     break;
2453             }
2454             break;
2455 
2456         case HCI_STATE_INITIALIZING:
2457             switch (power_mode){
2458                 case HCI_POWER_ON:
2459                     // do nothing
2460                     break;
2461                 case HCI_POWER_OFF:
2462                     // no connections yet, just turn it off
2463                     hci_power_control_off();
2464                     break;
2465                 case HCI_POWER_SLEEP:
2466                     // no connections yet, just turn it off
2467                     hci_power_control_sleep();
2468                     break;
2469             }
2470             break;
2471 
2472         case HCI_STATE_WORKING:
2473             switch (power_mode){
2474                 case HCI_POWER_ON:
2475                     // do nothing
2476                     break;
2477                 case HCI_POWER_OFF:
2478                     // see hci_run
2479                     hci_stack->state = HCI_STATE_HALTING;
2480                     break;
2481                 case HCI_POWER_SLEEP:
2482                     // see hci_run
2483                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2484                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2485                     break;
2486             }
2487             break;
2488 
2489         case HCI_STATE_HALTING:
2490             switch (power_mode){
2491                 case HCI_POWER_ON:
2492                     hci_power_transition_to_initializing();
2493                     break;
2494                 case HCI_POWER_OFF:
2495                     // do nothing
2496                     break;
2497                 case HCI_POWER_SLEEP:
2498                     // see hci_run
2499                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2500                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2501                     break;
2502             }
2503             break;
2504 
2505         case HCI_STATE_FALLING_ASLEEP:
2506             switch (power_mode){
2507                 case HCI_POWER_ON:
2508 
2509 #ifdef HAVE_PLATFORM_IPHONE_OS
2510                     // nothing to do, if H4 supports power management
2511                     if (btstack_control_iphone_power_management_enabled()){
2512                         hci_stack->state = HCI_STATE_INITIALIZING;
2513                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2514                         break;
2515                     }
2516 #endif
2517                     hci_power_transition_to_initializing();
2518                     break;
2519                 case HCI_POWER_OFF:
2520                     // see hci_run
2521                     hci_stack->state = HCI_STATE_HALTING;
2522                     break;
2523                 case HCI_POWER_SLEEP:
2524                     // do nothing
2525                     break;
2526             }
2527             break;
2528 
2529         case HCI_STATE_SLEEPING:
2530             switch (power_mode){
2531                 case HCI_POWER_ON:
2532 
2533 #ifdef HAVE_PLATFORM_IPHONE_OS
2534                     // nothing to do, if H4 supports power management
2535                     if (btstack_control_iphone_power_management_enabled()){
2536                         hci_stack->state = HCI_STATE_INITIALIZING;
2537                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2538                         hci_update_scan_enable();
2539                         break;
2540                     }
2541 #endif
2542                     err = hci_power_control_wake();
2543                     if (err) return err;
2544                     hci_power_transition_to_initializing();
2545                     break;
2546                 case HCI_POWER_OFF:
2547                     hci_stack->state = HCI_STATE_HALTING;
2548                     break;
2549                 case HCI_POWER_SLEEP:
2550                     // do nothing
2551                     break;
2552             }
2553             break;
2554     }
2555 
2556     // create internal event
2557 	hci_emit_state();
2558 
2559 	// trigger next/first action
2560 	hci_run();
2561 
2562     return 0;
2563 }
2564 
2565 
2566 #ifdef ENABLE_CLASSIC
2567 
2568 static void hci_update_scan_enable(void){
2569     // 2 = page scan, 1 = inq scan
2570     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2571     hci_run();
2572 }
2573 
2574 void gap_discoverable_control(uint8_t enable){
2575     if (enable) enable = 1; // normalize argument
2576 
2577     if (hci_stack->discoverable == enable){
2578         hci_emit_discoverable_enabled(hci_stack->discoverable);
2579         return;
2580     }
2581 
2582     hci_stack->discoverable = enable;
2583     hci_update_scan_enable();
2584 }
2585 
2586 void gap_connectable_control(uint8_t enable){
2587     if (enable) enable = 1; // normalize argument
2588 
2589     // don't emit event
2590     if (hci_stack->connectable == enable) return;
2591 
2592     hci_stack->connectable = enable;
2593     hci_update_scan_enable();
2594 }
2595 #endif
2596 
2597 void gap_local_bd_addr(bd_addr_t address_buffer){
2598     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
2599 }
2600 
2601 static void hci_run(void){
2602 
2603     // log_info("hci_run: entered");
2604     btstack_linked_item_t * it;
2605 
2606     // send continuation fragments first, as they block the prepared packet buffer
2607     if (hci_stack->acl_fragmentation_total_size > 0) {
2608         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2609         hci_connection_t *connection = hci_connection_for_handle(con_handle);
2610         if (connection) {
2611             if (hci_can_send_prepared_acl_packet_now(con_handle)){
2612                 hci_send_acl_packet_fragments(connection);
2613                 return;
2614             }
2615         } else {
2616             // connection gone -> discard further fragments
2617             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
2618             hci_stack->acl_fragmentation_total_size = 0;
2619             hci_stack->acl_fragmentation_pos = 0;
2620         }
2621     }
2622 
2623     if (!hci_can_send_command_packet_now()) return;
2624 
2625     // global/non-connection oriented commands
2626 
2627 #ifdef ENABLE_CLASSIC
2628     // decline incoming connections
2629     if (hci_stack->decline_reason){
2630         uint8_t reason = hci_stack->decline_reason;
2631         hci_stack->decline_reason = 0;
2632         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2633         return;
2634     }
2635 
2636     // send scan enable
2637     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
2638         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
2639         hci_stack->new_scan_enable_value = 0xff;
2640         return;
2641     }
2642 #endif
2643 
2644 #ifdef ENABLE_BLE
2645     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
2646     if ((hci_stack->state == HCI_STATE_WORKING)
2647     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
2648 
2649 #ifdef ENABLE_LE_CENTRAL
2650         // handle le scan
2651         switch(hci_stack->le_scanning_state){
2652             case LE_START_SCAN:
2653                 hci_stack->le_scanning_state = LE_SCANNING;
2654                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
2655                 return;
2656 
2657             case LE_STOP_SCAN:
2658                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
2659                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
2660                 return;
2661             default:
2662                 break;
2663         }
2664         if (hci_stack->le_scan_type != 0xff){
2665             // defaults: active scanning, accept all advertisement packets
2666             int scan_type = hci_stack->le_scan_type;
2667             hci_stack->le_scan_type = 0xff;
2668             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);
2669             return;
2670         }
2671 #endif
2672 #ifdef ENABLE_LE_PERIPHERAL
2673         // le advertisement control
2674         if (hci_stack->le_advertisements_todo){
2675             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
2676         }
2677         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
2678             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
2679             hci_send_cmd(&hci_le_set_advertise_enable, 0);
2680             return;
2681         }
2682         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
2683             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
2684             hci_send_cmd(&hci_le_set_advertising_parameters,
2685                  hci_stack->le_advertisements_interval_min,
2686                  hci_stack->le_advertisements_interval_max,
2687                  hci_stack->le_advertisements_type,
2688                  hci_stack->le_own_addr_type,
2689                  hci_stack->le_advertisements_direct_address_type,
2690                  hci_stack->le_advertisements_direct_address,
2691                  hci_stack->le_advertisements_channel_map,
2692                  hci_stack->le_advertisements_filter_policy);
2693             return;
2694         }
2695         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
2696             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
2697             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, hci_stack->le_advertisements_data);
2698             return;
2699         }
2700         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
2701             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
2702             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len,
2703                 hci_stack->le_scan_response_data);
2704             return;
2705         }
2706         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
2707             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
2708             hci_send_cmd(&hci_le_set_advertise_enable, 1);
2709             return;
2710         }
2711 #endif
2712 
2713 #ifdef ENABLE_LE_CENTRAL
2714         //
2715         // LE Whitelist Management
2716         //
2717 
2718         // check if whitelist needs modification
2719         btstack_linked_list_iterator_t lit;
2720         int modification_pending = 0;
2721         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2722         while (btstack_linked_list_iterator_has_next(&lit)){
2723             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2724             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
2725                 modification_pending = 1;
2726                 break;
2727             }
2728         }
2729 
2730         if (modification_pending){
2731             // stop connnecting if modification pending
2732             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
2733                 hci_send_cmd(&hci_le_create_connection_cancel);
2734                 return;
2735             }
2736 
2737             // add/remove entries
2738             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2739             while (btstack_linked_list_iterator_has_next(&lit)){
2740                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2741                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
2742                     entry->state = LE_WHITELIST_ON_CONTROLLER;
2743                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
2744                     return;
2745 
2746                 }
2747                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
2748                     bd_addr_t address;
2749                     bd_addr_type_t address_type = entry->address_type;
2750                     memcpy(address, entry->address, 6);
2751                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
2752                     btstack_memory_whitelist_entry_free(entry);
2753                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
2754                     return;
2755                 }
2756             }
2757         }
2758 
2759         // start connecting
2760         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
2761             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
2762             bd_addr_t null_addr;
2763             memset(null_addr, 0, 6);
2764             hci_send_cmd(&hci_le_create_connection,
2765                  0x0060,    // scan interval: 60 ms
2766                  0x0030,    // scan interval: 30 ms
2767                  1,         // use whitelist
2768                  0,         // peer address type
2769                  null_addr, // peer bd addr
2770                  hci_stack->le_own_addr_type, // our addr type:
2771                  0x0008,    // conn interval min
2772                  0x0018,    // conn interval max
2773                  0,         // conn latency
2774                  0x0048,    // supervision timeout
2775                  0x0001,    // min ce length
2776                  0x0001     // max ce length
2777                  );
2778             return;
2779         }
2780 #endif
2781     }
2782 #endif
2783 
2784     // send pending HCI commands
2785     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
2786         hci_connection_t * connection = (hci_connection_t *) it;
2787 
2788         switch(connection->state){
2789             case SEND_CREATE_CONNECTION:
2790                 switch(connection->address_type){
2791 #ifdef ENABLE_CLASSIC
2792                     case BD_ADDR_TYPE_CLASSIC:
2793                         log_info("sending hci_create_connection");
2794                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
2795                         break;
2796 #endif
2797                     default:
2798 #ifdef ENABLE_BLE
2799 #ifdef ENABLE_LE_CENTRAL
2800                         log_info("sending hci_le_create_connection");
2801                         hci_send_cmd(&hci_le_create_connection,
2802                                      0x0060,    // scan interval: 60 ms
2803                                      0x0030,    // scan interval: 30 ms
2804                                      0,         // don't use whitelist
2805                                      connection->address_type, // peer address type
2806                                      connection->address,      // peer bd addr
2807                                      hci_stack->le_own_addr_type,  // our addr type:
2808                                      0x0008,    // conn interval min
2809                                      0x0018,    // conn interval max
2810                                      0,         // conn latency
2811                                      0x0048,    // supervision timeout
2812                                      0x0001,    // min ce length
2813                                      0x0001     // max ce length
2814                                      );
2815 
2816                         connection->state = SENT_CREATE_CONNECTION;
2817 #endif
2818 #endif
2819                         break;
2820                 }
2821                 return;
2822 
2823 #ifdef ENABLE_CLASSIC
2824             case RECEIVED_CONNECTION_REQUEST:
2825                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
2826                 connection->state = ACCEPTED_CONNECTION_REQUEST;
2827                 connection->role  = HCI_ROLE_SLAVE;
2828                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
2829                     hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
2830                 }
2831                 return;
2832 #endif
2833 
2834 #ifdef ENABLE_BLE
2835 #ifdef ENABLE_LE_CENTRAL
2836             case SEND_CANCEL_CONNECTION:
2837                 connection->state = SENT_CANCEL_CONNECTION;
2838                 hci_send_cmd(&hci_le_create_connection_cancel);
2839                 return;
2840 #endif
2841 #endif
2842             case SEND_DISCONNECT:
2843                 connection->state = SENT_DISCONNECT;
2844                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
2845                 return;
2846 
2847             default:
2848                 break;
2849         }
2850 
2851 #ifdef ENABLE_CLASSIC
2852         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
2853             log_info("responding to link key request");
2854             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
2855             link_key_t link_key;
2856             link_key_type_t link_key_type;
2857             if ( hci_stack->link_key_db
2858               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
2859               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
2860                connection->link_key_type = link_key_type;
2861                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
2862             } else {
2863                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
2864             }
2865             return;
2866         }
2867 
2868         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
2869             log_info("denying to pin request");
2870             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
2871             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
2872             return;
2873         }
2874 
2875         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
2876             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
2877             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
2878             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
2879                 // tweak authentication requirements
2880                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
2881                 if (connection->bonding_flags & BONDING_DEDICATED){
2882                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
2883                 }
2884                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
2885                     authreq |= 1;
2886                 }
2887                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
2888             } else {
2889                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
2890             }
2891             return;
2892         }
2893 
2894         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
2895             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
2896             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
2897             return;
2898         }
2899 
2900         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
2901             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
2902             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
2903             return;
2904         }
2905 
2906         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
2907             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
2908             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
2909             return;
2910         }
2911 
2912         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
2913             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
2914             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
2915             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
2916             return;
2917         }
2918 
2919         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
2920             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
2921             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
2922             return;
2923         }
2924 
2925         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
2926             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
2927             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
2928             return;
2929         }
2930 #endif
2931 
2932         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
2933             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
2934             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
2935             return;
2936         }
2937 
2938 #ifdef ENABLE_BLE
2939         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2940             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2941 
2942             uint16_t connection_interval_min = connection->le_conn_interval_min;
2943             connection->le_conn_interval_min = 0;
2944             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2945                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2946                 0x0000, 0xffff);
2947         }
2948 #endif
2949     }
2950 
2951     hci_connection_t * connection;
2952     switch (hci_stack->state){
2953         case HCI_STATE_INITIALIZING:
2954             hci_initializing_run();
2955             break;
2956 
2957         case HCI_STATE_HALTING:
2958 
2959             log_info("HCI_STATE_HALTING");
2960 
2961             // free whitelist entries
2962 #ifdef ENABLE_BLE
2963 #ifdef ENABLE_LE_CENTRAL
2964             {
2965                 btstack_linked_list_iterator_t lit;
2966                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2967                 while (btstack_linked_list_iterator_has_next(&lit)){
2968                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2969                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
2970                     btstack_memory_whitelist_entry_free(entry);
2971                 }
2972             }
2973 #endif
2974 #endif
2975             // close all open connections
2976             connection =  (hci_connection_t *) hci_stack->connections;
2977             if (connection){
2978                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
2979                 if (!hci_can_send_command_packet_now()) return;
2980 
2981                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
2982 
2983                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
2984                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
2985 
2986                 // ... which would be ignored anyway as we shutdown (free) the connection now
2987                 hci_shutdown_connection(connection);
2988 
2989                 // finally, send the disconnect command
2990                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
2991                 return;
2992             }
2993             log_info("HCI_STATE_HALTING, calling off");
2994 
2995             // switch mode
2996             hci_power_control_off();
2997 
2998             log_info("HCI_STATE_HALTING, emitting state");
2999             hci_emit_state();
3000             log_info("HCI_STATE_HALTING, done");
3001             break;
3002 
3003         case HCI_STATE_FALLING_ASLEEP:
3004             switch(hci_stack->substate) {
3005                 case HCI_FALLING_ASLEEP_DISCONNECT:
3006                     log_info("HCI_STATE_FALLING_ASLEEP");
3007                     // close all open connections
3008                     connection =  (hci_connection_t *) hci_stack->connections;
3009 
3010 #ifdef HAVE_PLATFORM_IPHONE_OS
3011                     // don't close connections, if H4 supports power management
3012                     if (btstack_control_iphone_power_management_enabled()){
3013                         connection = NULL;
3014                     }
3015 #endif
3016                     if (connection){
3017 
3018                         // send disconnect
3019                         if (!hci_can_send_command_packet_now()) return;
3020 
3021                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3022                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3023 
3024                         // send disconnected event right away - causes higher layer connections to get closed, too.
3025                         hci_shutdown_connection(connection);
3026                         return;
3027                     }
3028 
3029                     if (hci_classic_supported()){
3030                         // disable page and inquiry scan
3031                         if (!hci_can_send_command_packet_now()) return;
3032 
3033                         log_info("HCI_STATE_HALTING, disabling inq scans");
3034                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3035 
3036                         // continue in next sub state
3037                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3038                         break;
3039                     }
3040                     // no break - fall through for ble-only chips
3041 
3042                 case HCI_FALLING_ASLEEP_COMPLETE:
3043                     log_info("HCI_STATE_HALTING, calling sleep");
3044 #ifdef HAVE_PLATFORM_IPHONE_OS
3045                     // don't actually go to sleep, if H4 supports power management
3046                     if (btstack_control_iphone_power_management_enabled()){
3047                         // SLEEP MODE reached
3048                         hci_stack->state = HCI_STATE_SLEEPING;
3049                         hci_emit_state();
3050                         break;
3051                     }
3052 #endif
3053                     // switch mode
3054                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3055                     hci_emit_state();
3056                     break;
3057 
3058                 default:
3059                     break;
3060             }
3061             break;
3062 
3063         default:
3064             break;
3065     }
3066 }
3067 
3068 int hci_send_cmd_packet(uint8_t *packet, int size){
3069     // house-keeping
3070 
3071     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3072         hci_stack->loopback_mode = packet[3];
3073     }
3074 
3075 #ifdef ENABLE_CLASSIC
3076     bd_addr_t addr;
3077     hci_connection_t * conn;
3078 
3079     // create_connection?
3080     if (IS_COMMAND(packet, hci_create_connection)){
3081         reverse_bd_addr(&packet[3], addr);
3082         log_info("Create_connection to %s", bd_addr_to_str(addr));
3083 
3084         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3085         if (!conn){
3086             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3087             if (!conn){
3088                 // notify client that alloc failed
3089                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3090                 return 0; // don't sent packet to controller
3091             }
3092             conn->state = SEND_CREATE_CONNECTION;
3093         }
3094         log_info("conn state %u", conn->state);
3095         switch (conn->state){
3096             // if connection active exists
3097             case OPEN:
3098                 // and OPEN, emit connection complete command, don't send to controller
3099                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3100                 return 0;
3101             case SEND_CREATE_CONNECTION:
3102                 // connection created by hci, e.g. dedicated bonding
3103                 break;
3104             default:
3105                 // otherwise, just ignore as it is already in the open process
3106                 return 0;
3107         }
3108         conn->state = SENT_CREATE_CONNECTION;
3109     }
3110 
3111     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3112         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3113     }
3114     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3115         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3116     }
3117 
3118     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3119         if (hci_stack->link_key_db){
3120             reverse_bd_addr(&packet[3], addr);
3121             hci_stack->link_key_db->delete_link_key(addr);
3122         }
3123     }
3124 
3125     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3126     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3127         reverse_bd_addr(&packet[3], addr);
3128         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3129         if (conn){
3130             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3131         }
3132     }
3133 
3134     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3135     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3136     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3137     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3138         reverse_bd_addr(&packet[3], addr);
3139         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3140         if (conn){
3141             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3142         }
3143     }
3144 
3145 #ifdef ENABLE_SCO_OVER_HCI
3146     // setup_synchronous_connection? Voice setting at offset 22
3147     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3148         // TODO: compare to current setting if sco connection already active
3149         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3150     }
3151     // accept_synchronus_connection? Voice setting at offset 18
3152     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3153         // TODO: compare to current setting if sco connection already active
3154         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3155     }
3156 #endif
3157 #endif
3158 
3159 #ifdef ENABLE_BLE
3160 #ifdef ENABLE_LE_PERIPHERAL
3161     if (IS_COMMAND(packet, hci_le_set_random_address)){
3162         hci_stack->le_random_address_set = 1;
3163         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3164     }
3165     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3166         hci_stack->le_advertisements_active = packet[3];
3167     }
3168 #endif
3169 #ifdef ENABLE_LE_CENTRAL
3170     if (IS_COMMAND(packet, hci_le_create_connection)){
3171         // white list used?
3172         uint8_t initiator_filter_policy = packet[7];
3173         switch (initiator_filter_policy){
3174             case 0:
3175                 // whitelist not used
3176                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3177                 break;
3178             case 1:
3179                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3180                 break;
3181             default:
3182                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3183                 break;
3184         }
3185     }
3186     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3187         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3188     }
3189 #endif
3190 #endif
3191 
3192     hci_stack->num_cmd_packets--;
3193 
3194     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3195     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3196 
3197     // release packet buffer for synchronous transport implementations
3198     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
3199         hci_stack->hci_packet_buffer_reserved = 0;
3200     }
3201 
3202     return err;
3203 }
3204 
3205 // disconnect because of security block
3206 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3207     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3208     if (!connection) return;
3209     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3210 }
3211 
3212 
3213 // Configure Secure Simple Pairing
3214 
3215 #ifdef ENABLE_CLASSIC
3216 
3217 // enable will enable SSP during init
3218 void gap_ssp_set_enable(int enable){
3219     hci_stack->ssp_enable = enable;
3220 }
3221 
3222 static int hci_local_ssp_activated(void){
3223     return gap_ssp_supported() && hci_stack->ssp_enable;
3224 }
3225 
3226 // if set, BTstack will respond to io capability request using authentication requirement
3227 void gap_ssp_set_io_capability(int io_capability){
3228     hci_stack->ssp_io_capability = io_capability;
3229 }
3230 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3231     hci_stack->ssp_authentication_requirement = authentication_requirement;
3232 }
3233 
3234 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3235 void gap_ssp_set_auto_accept(int auto_accept){
3236     hci_stack->ssp_auto_accept = auto_accept;
3237 }
3238 #endif
3239 
3240 // va_list part of hci_send_cmd
3241 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3242     if (!hci_can_send_command_packet_now()){
3243         log_error("hci_send_cmd called but cannot send packet now");
3244         return 0;
3245     }
3246 
3247     // for HCI INITIALIZATION
3248     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3249     hci_stack->last_cmd_opcode = cmd->opcode;
3250 
3251     hci_reserve_packet_buffer();
3252     uint8_t * packet = hci_stack->hci_packet_buffer;
3253     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3254     return hci_send_cmd_packet(packet, size);
3255 }
3256 
3257 /**
3258  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3259  */
3260 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3261     va_list argptr;
3262     va_start(argptr, cmd);
3263     int res = hci_send_cmd_va_arg(cmd, argptr);
3264     va_end(argptr);
3265     return res;
3266 }
3267 
3268 // Create various non-HCI events.
3269 // TODO: generalize, use table similar to hci_create_command
3270 
3271 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3272     // dump packet
3273     if (dump) {
3274         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3275     }
3276 
3277     // dispatch to all event handlers
3278     btstack_linked_list_iterator_t it;
3279     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3280     while (btstack_linked_list_iterator_has_next(&it)){
3281         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3282         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3283     }
3284 }
3285 
3286 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3287     if (!hci_stack->acl_packet_handler) return;
3288     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3289 }
3290 
3291 #ifdef ENABLE_CLASSIC
3292 static void hci_notify_if_sco_can_send_now(void){
3293     // notify SCO sender if waiting
3294     if (!hci_stack->sco_waiting_for_can_send_now) return;
3295     if (hci_can_send_sco_packet_now()){
3296         hci_stack->sco_waiting_for_can_send_now = 0;
3297         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3298         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3299         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3300     }
3301 }
3302 #endif
3303 
3304 void hci_emit_state(void){
3305     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3306     uint8_t event[3];
3307     event[0] = BTSTACK_EVENT_STATE;
3308     event[1] = sizeof(event) - 2;
3309     event[2] = hci_stack->state;
3310     hci_emit_event(event, sizeof(event), 1);
3311 }
3312 
3313 #ifdef ENABLE_CLASSIC
3314 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3315     uint8_t event[13];
3316     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3317     event[1] = sizeof(event) - 2;
3318     event[2] = status;
3319     little_endian_store_16(event, 3, con_handle);
3320     reverse_bd_addr(address, &event[5]);
3321     event[11] = 1; // ACL connection
3322     event[12] = 0; // encryption disabled
3323     hci_emit_event(event, sizeof(event), 1);
3324 }
3325 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3326     if (disable_l2cap_timeouts) return;
3327     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3328     uint8_t event[4];
3329     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3330     event[1] = sizeof(event) - 2;
3331     little_endian_store_16(event, 2, conn->con_handle);
3332     hci_emit_event(event, sizeof(event), 1);
3333 }
3334 #endif
3335 
3336 #ifdef ENABLE_BLE
3337 #ifdef ENABLE_LE_CENTRAL
3338 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3339     uint8_t event[21];
3340     event[0] = HCI_EVENT_LE_META;
3341     event[1] = sizeof(event) - 2;
3342     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
3343     event[3] = status;
3344     little_endian_store_16(event, 4, con_handle);
3345     event[6] = 0; // TODO: role
3346     event[7] = address_type;
3347     reverse_bd_addr(address, &event[8]);
3348     little_endian_store_16(event, 14, 0); // interval
3349     little_endian_store_16(event, 16, 0); // latency
3350     little_endian_store_16(event, 18, 0); // supervision timeout
3351     event[20] = 0; // master clock accuracy
3352     hci_emit_event(event, sizeof(event), 1);
3353 }
3354 #endif
3355 #endif
3356 
3357 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
3358     uint8_t event[6];
3359     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
3360     event[1] = sizeof(event) - 2;
3361     event[2] = 0; // status = OK
3362     little_endian_store_16(event, 3, con_handle);
3363     event[5] = reason;
3364     hci_emit_event(event, sizeof(event), 1);
3365 }
3366 
3367 static void hci_emit_nr_connections_changed(void){
3368     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
3369     uint8_t event[3];
3370     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3371     event[1] = sizeof(event) - 2;
3372     event[2] = nr_hci_connections();
3373     hci_emit_event(event, sizeof(event), 1);
3374 }
3375 
3376 static void hci_emit_hci_open_failed(void){
3377     log_info("BTSTACK_EVENT_POWERON_FAILED");
3378     uint8_t event[2];
3379     event[0] = BTSTACK_EVENT_POWERON_FAILED;
3380     event[1] = sizeof(event) - 2;
3381     hci_emit_event(event, sizeof(event), 1);
3382 }
3383 
3384 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
3385     log_info("hci_emit_dedicated_bonding_result %u ", status);
3386     uint8_t event[9];
3387     int pos = 0;
3388     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
3389     event[pos++] = sizeof(event) - 2;
3390     event[pos++] = status;
3391     reverse_bd_addr(address, &event[pos]);
3392     hci_emit_event(event, sizeof(event), 1);
3393 }
3394 
3395 
3396 #ifdef ENABLE_CLASSIC
3397 
3398 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3399     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3400     uint8_t event[5];
3401     int pos = 0;
3402     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3403     event[pos++] = sizeof(event) - 2;
3404     little_endian_store_16(event, 2, con_handle);
3405     pos += 2;
3406     event[pos++] = level;
3407     hci_emit_event(event, sizeof(event), 1);
3408 }
3409 
3410 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
3411     if (!connection) return LEVEL_0;
3412     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
3413     return gap_security_level_for_link_key_type(connection->link_key_type);
3414 }
3415 
3416 static void hci_emit_discoverable_enabled(uint8_t enabled){
3417     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
3418     uint8_t event[3];
3419     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
3420     event[1] = sizeof(event) - 2;
3421     event[2] = enabled;
3422     hci_emit_event(event, sizeof(event), 1);
3423 }
3424 
3425 #ifdef ENABLE_CLASSIC
3426 // query if remote side supports eSCO
3427 int hci_remote_esco_supported(hci_con_handle_t con_handle){
3428     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3429     if (!connection) return 0;
3430     return connection->remote_supported_feature_eSCO;
3431 }
3432 
3433 // query if remote side supports SSP
3434 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
3435     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3436     if (!connection) return 0;
3437     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
3438 }
3439 
3440 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
3441     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3442 }
3443 #endif
3444 
3445 // GAP API
3446 /**
3447  * @bbrief enable/disable bonding. default is enabled
3448  * @praram enabled
3449  */
3450 void gap_set_bondable_mode(int enable){
3451     hci_stack->bondable = enable ? 1 : 0;
3452 }
3453 /**
3454  * @brief Get bondable mode.
3455  * @return 1 if bondable
3456  */
3457 int gap_get_bondable_mode(void){
3458     return hci_stack->bondable;
3459 }
3460 
3461 /**
3462  * @brief map link keys to security levels
3463  */
3464 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
3465     switch (link_key_type){
3466         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
3467             return LEVEL_4;
3468         case COMBINATION_KEY:
3469         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
3470             return LEVEL_3;
3471         default:
3472             return LEVEL_2;
3473     }
3474 }
3475 
3476 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
3477     log_info("gap_mitm_protection_required_for_security_level %u", level);
3478     return level > LEVEL_2;
3479 }
3480 
3481 /**
3482  * @brief get current security level
3483  */
3484 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
3485     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3486     if (!connection) return LEVEL_0;
3487     return gap_security_level_for_connection(connection);
3488 }
3489 
3490 /**
3491  * @brief request connection to device to
3492  * @result GAP_AUTHENTICATION_RESULT
3493  */
3494 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
3495     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3496     if (!connection){
3497         hci_emit_security_level(con_handle, LEVEL_0);
3498         return;
3499     }
3500     gap_security_level_t current_level = gap_security_level(con_handle);
3501     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
3502     if (current_level >= requested_level){
3503         hci_emit_security_level(con_handle, current_level);
3504         return;
3505     }
3506 
3507     connection->requested_security_level = requested_level;
3508 
3509 #if 0
3510     // sending encryption request without a link key results in an error.
3511     // TODO: figure out how to use it properly
3512 
3513     // would enabling ecnryption suffice (>= LEVEL_2)?
3514     if (hci_stack->link_key_db){
3515         link_key_type_t link_key_type;
3516         link_key_t      link_key;
3517         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3518             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3519                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3520                 return;
3521             }
3522         }
3523     }
3524 #endif
3525 
3526     // try to authenticate connection
3527     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3528     hci_run();
3529 }
3530 
3531 /**
3532  * @brief start dedicated bonding with device. disconnect after bonding
3533  * @param device
3534  * @param request MITM protection
3535  * @result GAP_DEDICATED_BONDING_COMPLETE
3536  */
3537 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3538 
3539     // create connection state machine
3540     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3541 
3542     if (!connection){
3543         return BTSTACK_MEMORY_ALLOC_FAILED;
3544     }
3545 
3546     // delete linkn key
3547     gap_drop_link_key_for_bd_addr(device);
3548 
3549     // configure LEVEL_2/3, dedicated bonding
3550     connection->state = SEND_CREATE_CONNECTION;
3551     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
3552     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
3553     connection->bonding_flags = BONDING_DEDICATED;
3554 
3555     // wait for GAP Security Result and send GAP Dedicated Bonding complete
3556 
3557     // handle: connnection failure (connection complete != ok)
3558     // handle: authentication failure
3559     // handle: disconnect on done
3560 
3561     hci_run();
3562 
3563     return 0;
3564 }
3565 #endif
3566 
3567 void gap_set_local_name(const char * local_name){
3568     hci_stack->local_name = local_name;
3569 }
3570 
3571 
3572 #ifdef ENABLE_BLE
3573 
3574 #ifdef ENABLE_LE_CENTRAL
3575 void gap_start_scan(void){
3576     if (hci_stack->le_scanning_state == LE_SCANNING) return;
3577     hci_stack->le_scanning_state = LE_START_SCAN;
3578     hci_run();
3579 }
3580 
3581 void gap_stop_scan(void){
3582     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return;
3583     hci_stack->le_scanning_state = LE_STOP_SCAN;
3584     hci_run();
3585 }
3586 
3587 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
3588     hci_stack->le_scan_type     = scan_type;
3589     hci_stack->le_scan_interval = scan_interval;
3590     hci_stack->le_scan_window   = scan_window;
3591     hci_run();
3592 }
3593 
3594 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
3595     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3596     if (!conn){
3597         log_info("gap_connect: no connection exists yet, creating context");
3598         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3599         if (!conn){
3600             // notify client that alloc failed
3601             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3602             log_info("gap_connect: failed to alloc hci_connection_t");
3603             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
3604         }
3605         conn->state = SEND_CREATE_CONNECTION;
3606         log_info("gap_connect: send create connection next");
3607         hci_run();
3608         return 0;
3609     }
3610 
3611     if (!hci_is_le_connection(conn) ||
3612         conn->state == SEND_CREATE_CONNECTION ||
3613         conn->state == SENT_CREATE_CONNECTION) {
3614         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
3615         log_error("gap_connect: classic connection or connect is already being created");
3616         return GATT_CLIENT_IN_WRONG_STATE;
3617     }
3618 
3619     log_info("gap_connect: context exists with state %u", conn->state);
3620     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
3621     hci_run();
3622     return 0;
3623 }
3624 
3625 // @assumption: only a single outgoing LE Connection exists
3626 static hci_connection_t * gap_get_outgoing_connection(void){
3627     btstack_linked_item_t *it;
3628     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3629         hci_connection_t * conn = (hci_connection_t *) it;
3630         if (!hci_is_le_connection(conn)) continue;
3631         switch (conn->state){
3632             case SEND_CREATE_CONNECTION:
3633             case SENT_CREATE_CONNECTION:
3634                 return conn;
3635             default:
3636                 break;
3637         };
3638     }
3639     return NULL;
3640 }
3641 
3642 uint8_t gap_connect_cancel(void){
3643     hci_connection_t * conn = gap_get_outgoing_connection();
3644     if (!conn) return 0;
3645     switch (conn->state){
3646         case SEND_CREATE_CONNECTION:
3647             // skip sending create connection and emit event instead
3648             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
3649             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
3650             btstack_memory_hci_connection_free( conn );
3651             break;
3652         case SENT_CREATE_CONNECTION:
3653             // request to send cancel connection
3654             conn->state = SEND_CANCEL_CONNECTION;
3655             hci_run();
3656             break;
3657         default:
3658             break;
3659     }
3660     return 0;
3661 }
3662 #endif
3663 
3664 /**
3665  * @brief Updates the connection parameters for a given LE connection
3666  * @param handle
3667  * @param conn_interval_min (unit: 1.25ms)
3668  * @param conn_interval_max (unit: 1.25ms)
3669  * @param conn_latency
3670  * @param supervision_timeout (unit: 10ms)
3671  * @returns 0 if ok
3672  */
3673 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3674     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3675     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3676     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3677     connection->le_conn_interval_min = conn_interval_min;
3678     connection->le_conn_interval_max = conn_interval_max;
3679     connection->le_conn_latency = conn_latency;
3680     connection->le_supervision_timeout = supervision_timeout;
3681     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
3682     hci_run();
3683     return 0;
3684 }
3685 
3686 /**
3687  * @brief Request an update of the connection parameter for a given LE connection
3688  * @param handle
3689  * @param conn_interval_min (unit: 1.25ms)
3690  * @param conn_interval_max (unit: 1.25ms)
3691  * @param conn_latency
3692  * @param supervision_timeout (unit: 10ms)
3693  * @returns 0 if ok
3694  */
3695 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3696     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3697     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3698     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3699     connection->le_conn_interval_min = conn_interval_min;
3700     connection->le_conn_interval_max = conn_interval_max;
3701     connection->le_conn_latency = conn_latency;
3702     connection->le_supervision_timeout = supervision_timeout;
3703     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
3704     hci_run();
3705     return 0;
3706 }
3707 
3708 #ifdef ENABLE_LE_PERIPHERAL
3709 
3710 static void gap_advertisments_changed(void){
3711     // disable advertisements before updating adv, scan data, or adv params
3712     if (hci_stack->le_advertisements_active){
3713         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
3714     }
3715     hci_run();
3716 }
3717 
3718 /**
3719  * @brief Set Advertisement Data
3720  * @param advertising_data_length
3721  * @param advertising_data (max 31 octets)
3722  * @note data is not copied, pointer has to stay valid
3723  */
3724 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
3725     hci_stack->le_advertisements_data_len = advertising_data_length;
3726     hci_stack->le_advertisements_data = advertising_data;
3727     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3728     gap_advertisments_changed();
3729 }
3730 
3731 /**
3732  * @brief Set Scan Response Data
3733  * @param advertising_data_length
3734  * @param advertising_data (max 31 octets)
3735  * @note data is not copied, pointer has to stay valid
3736  */
3737 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
3738     hci_stack->le_scan_response_data_len = scan_response_data_length;
3739     hci_stack->le_scan_response_data = scan_response_data;
3740     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3741     gap_advertisments_changed();
3742 }
3743 
3744 /**
3745  * @brief Set Advertisement Parameters
3746  * @param adv_int_min
3747  * @param adv_int_max
3748  * @param adv_type
3749  * @param direct_address_type
3750  * @param direct_address
3751  * @param channel_map
3752  * @param filter_policy
3753  *
3754  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
3755  */
3756  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
3757     uint8_t direct_address_typ, bd_addr_t direct_address,
3758     uint8_t channel_map, uint8_t filter_policy) {
3759 
3760     hci_stack->le_advertisements_interval_min = adv_int_min;
3761     hci_stack->le_advertisements_interval_max = adv_int_max;
3762     hci_stack->le_advertisements_type = adv_type;
3763     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
3764     hci_stack->le_advertisements_channel_map = channel_map;
3765     hci_stack->le_advertisements_filter_policy = filter_policy;
3766     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
3767 
3768     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3769     gap_advertisments_changed();
3770  }
3771 
3772 /**
3773  * @brief Enable/Disable Advertisements
3774  * @param enabled
3775  */
3776 void gap_advertisements_enable(int enabled){
3777     hci_stack->le_advertisements_enabled = enabled;
3778     if (enabled && !hci_stack->le_advertisements_active){
3779         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
3780     }
3781     if (!enabled && hci_stack->le_advertisements_active){
3782         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
3783     }
3784     hci_run();
3785 }
3786 
3787 #endif
3788 
3789 void hci_le_set_own_address_type(uint8_t own_address_type){
3790     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
3791     if (own_address_type == hci_stack->le_own_addr_type) return;
3792     hci_stack->le_own_addr_type = own_address_type;
3793 
3794 #ifdef ENABLE_LE_PERIPHERAL
3795     // update advertisement parameters, too
3796     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3797     gap_advertisments_changed();
3798 #endif
3799 #ifdef ENABLE_LE_CENTRAL
3800     // note: we don't update scan parameters or modify ongoing connection attempts
3801 #endif
3802 }
3803 
3804 #endif
3805 
3806 uint8_t gap_disconnect(hci_con_handle_t handle){
3807     hci_connection_t * conn = hci_connection_for_handle(handle);
3808     if (!conn){
3809         hci_emit_disconnection_complete(handle, 0);
3810         return 0;
3811     }
3812     conn->state = SEND_DISCONNECT;
3813     hci_run();
3814     return 0;
3815 }
3816 
3817 /**
3818  * @brief Get connection type
3819  * @param con_handle
3820  * @result connection_type
3821  */
3822 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
3823     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
3824     if (!conn) return GAP_CONNECTION_INVALID;
3825     switch (conn->address_type){
3826         case BD_ADDR_TYPE_LE_PUBLIC:
3827         case BD_ADDR_TYPE_LE_RANDOM:
3828             return GAP_CONNECTION_LE;
3829         case BD_ADDR_TYPE_SCO:
3830             return GAP_CONNECTION_SCO;
3831         case BD_ADDR_TYPE_CLASSIC:
3832             return GAP_CONNECTION_ACL;
3833         default:
3834             return GAP_CONNECTION_INVALID;
3835     }
3836 }
3837 
3838 #ifdef ENABLE_BLE
3839 
3840 #ifdef ENABLE_LE_CENTRAL
3841 /**
3842  * @brief Auto Connection Establishment - Start Connecting to device
3843  * @param address_typ
3844  * @param address
3845  * @returns 0 if ok
3846  */
3847 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
3848     // check capacity
3849     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
3850     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3851     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
3852     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
3853     entry->address_type = address_type;
3854     memcpy(entry->address, address, 6);
3855     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
3856     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
3857     hci_run();
3858     return 0;
3859 }
3860 
3861 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
3862     btstack_linked_list_iterator_t it;
3863     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3864     while (btstack_linked_list_iterator_has_next(&it)){
3865         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3866         if (entry->address_type != address_type) continue;
3867         if (memcmp(entry->address, address, 6) != 0) continue;
3868         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3869             // remove from controller if already present
3870             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3871             continue;
3872         }
3873         // direclty remove entry from whitelist
3874         btstack_linked_list_iterator_remove(&it);
3875         btstack_memory_whitelist_entry_free(entry);
3876     }
3877 }
3878 
3879 /**
3880  * @brief Auto Connection Establishment - Stop Connecting to device
3881  * @param address_typ
3882  * @param address
3883  * @returns 0 if ok
3884  */
3885 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
3886     hci_remove_from_whitelist(address_type, address);
3887     hci_run();
3888     return 0;
3889 }
3890 
3891 /**
3892  * @brief Auto Connection Establishment - Stop everything
3893  * @note  Convenience function to stop all active auto connection attempts
3894  */
3895 void gap_auto_connection_stop_all(void){
3896     btstack_linked_list_iterator_t it;
3897     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3898     while (btstack_linked_list_iterator_has_next(&it)){
3899         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3900         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3901             // remove from controller if already present
3902             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3903             continue;
3904         }
3905         // directly remove entry from whitelist
3906         btstack_linked_list_iterator_remove(&it);
3907         btstack_memory_whitelist_entry_free(entry);
3908     }
3909     hci_run();
3910 }
3911 #endif
3912 #endif
3913 
3914 #ifdef ENABLE_CLASSIC
3915 /**
3916  * @brief Set Extended Inquiry Response data
3917  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
3918  * @note has to be done before stack starts up
3919  */
3920 void gap_set_extended_inquiry_response(const uint8_t * data){
3921     hci_stack->eir_data = data;
3922 }
3923 
3924 /**
3925  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
3926  * @param inquriy_mode see bluetooth_defines.h
3927  */
3928 void hci_set_inquiry_mode(inquiry_mode_t mode){
3929     hci_stack->inquiry_mode = mode;
3930 }
3931 
3932 /**
3933  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
3934  */
3935 void hci_set_sco_voice_setting(uint16_t voice_setting){
3936     hci_stack->sco_voice_setting = voice_setting;
3937 }
3938 
3939 /**
3940  * @brief Get SCO Voice Setting
3941  * @return current voice setting
3942  */
3943 uint16_t hci_get_sco_voice_setting(void){
3944     return hci_stack->sco_voice_setting;
3945 }
3946 
3947 /** @brief Get SCO packet length for current SCO Voice setting
3948  *  @note  Using SCO packets of the exact length is required for USB transfer
3949  *  @return Length of SCO packets in bytes (not audio frames)
3950  */
3951 int hci_get_sco_packet_length(void){
3952     // see Core Spec for H2 USB Transfer.
3953     if (hci_stack->sco_voice_setting & 0x0020) return 51;
3954     return 27;
3955 }
3956 #endif
3957 
3958 /**
3959  * @brief Set callback for Bluetooth Hardware Error
3960  */
3961 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
3962     hci_stack->hardware_error_callback = fn;
3963 }
3964 
3965 void hci_disconnect_all(void){
3966     btstack_linked_list_iterator_t it;
3967     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
3968     while (btstack_linked_list_iterator_has_next(&it)){
3969         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
3970         if (con->state == SENT_DISCONNECT) continue;
3971         con->state = SEND_DISCONNECT;
3972     }
3973     hci_run();
3974 }
3975 
3976 uint16_t hci_get_manufacturer(void){
3977     return hci_stack->manufacturer;
3978 }
3979