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