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