xref: /btstack/src/hci.c (revision cd542ed65d36fb7445555d207944f0eddc5aef4a)
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 #define __BTSTACK_FILE__ "hci.c"
39 
40 /*
41  *  hci.c
42  *
43  *  Created by Matthias Ringwald on 4/29/09.
44  *
45  */
46 
47 #include "btstack_config.h"
48 
49 
50 #ifdef ENABLE_CLASSIC
51 #ifdef HAVE_EMBEDDED_TICK
52 #include "btstack_run_loop_embedded.h"
53 #endif
54 #endif
55 
56 #ifdef HAVE_PLATFORM_IPHONE_OS
57 #include "../port/ios/src/btstack_control_iphone.h"
58 #endif
59 
60 #ifdef ENABLE_BLE
61 #include "gap.h"
62 #endif
63 
64 #include <stdarg.h>
65 #include <string.h>
66 #include <stdio.h>
67 #include <inttypes.h>
68 
69 #include "btstack_debug.h"
70 #include "btstack_event.h"
71 #include "btstack_linked_list.h"
72 #include "btstack_memory.h"
73 #include "bluetooth_company_id.h"
74 #include "bluetooth_data_types.h"
75 #include "gap.h"
76 #include "hci.h"
77 #include "hci_cmd.h"
78 #include "hci_dump.h"
79 #include "ad_parser.h"
80 
81 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
82 #ifndef HCI_HOST_ACL_PACKET_NUM
83 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM"
84 #endif
85 #ifndef HCI_HOST_ACL_PACKET_LEN
86 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN"
87 #endif
88 #ifndef HCI_HOST_SCO_PACKET_NUM
89 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM"
90 #endif
91 #ifndef HCI_HOST_SCO_PACKET_LEN
92 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN"
93 #endif
94 #endif
95 
96 #define HCI_CONNECTION_TIMEOUT_MS 10000
97 #define HCI_RESET_RESEND_TIMEOUT_MS 200
98 
99 // Names are arbitrarily shortened to 32 bytes if not requested otherwise
100 #ifndef GAP_INQUIRY_MAX_NAME_LEN
101 #define GAP_INQUIRY_MAX_NAME_LEN 32
102 #endif
103 
104 // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
105 #define GAP_INQUIRY_DURATION_MIN 0x01
106 #define GAP_INQUIRY_DURATION_MAX 0x30
107 #define GAP_INQUIRY_STATE_ACTIVE 0x80
108 #define GAP_INQUIRY_STATE_IDLE 0
109 #define GAP_INQUIRY_STATE_W2_CANCEL 0x81
110 #define GAP_INQUIRY_STATE_W4_CANCELLED 0x82
111 
112 // GAP Remote Name Request
113 #define GAP_REMOTE_NAME_STATE_IDLE 0
114 #define GAP_REMOTE_NAME_STATE_W2_SEND 1
115 #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
116 
117 // GAP Pairing
118 #define GAP_PAIRING_STATE_IDLE                       0
119 #define GAP_PAIRING_STATE_SEND_PIN                   1
120 #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
121 #define GAP_PAIRING_STATE_SEND_PASSKEY               3
122 #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
123 #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
124 #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
125 
126 
127 // prototypes
128 #ifdef ENABLE_CLASSIC
129 static void hci_update_scan_enable(void);
130 static void hci_emit_discoverable_enabled(uint8_t enabled);
131 static int  hci_local_ssp_activated(void);
132 static int  hci_remote_ssp_supported(hci_con_handle_t con_handle);
133 static void hci_notify_if_sco_can_send_now(void);
134 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
135 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
136 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
137 static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
138 static void hci_connection_timestamp(hci_connection_t *connection);
139 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
140 static void gap_inquiry_explode(uint8_t * packet);
141 #endif
142 
143 static int  hci_power_control_on(void);
144 static void hci_power_control_off(void);
145 static void hci_state_reset(void);
146 static void hci_emit_transport_packet_sent(void);
147 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
148 static void hci_emit_nr_connections_changed(void);
149 static void hci_emit_hci_open_failed(void);
150 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
151 static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
152 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
153 static void hci_run(void);
154 static int  hci_is_le_connection(hci_connection_t * connection);
155 static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
156 
157 #ifdef ENABLE_BLE
158 #ifdef ENABLE_LE_CENTRAL
159 // called from test/ble_client/advertising_data_parser.c
160 void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
161 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address);
162 static hci_connection_t * gap_get_outgoing_connection(void);
163 #endif
164 #endif
165 
166 // the STACK is here
167 #ifndef HAVE_MALLOC
168 static hci_stack_t   hci_stack_static;
169 #endif
170 static hci_stack_t * hci_stack = NULL;
171 
172 #ifdef ENABLE_CLASSIC
173 // default name
174 static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
175 
176 // test helper
177 static uint8_t disable_l2cap_timeouts = 0;
178 #endif
179 
180 /**
181  * create connection for given address
182  *
183  * @return connection OR NULL, if no memory left
184  */
185 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
186     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
187     hci_connection_t * conn = btstack_memory_hci_connection_get();
188     if (!conn) return NULL;
189     bd_addr_copy(conn->address, addr);
190     conn->address_type = addr_type;
191     conn->con_handle = 0xffff;
192     conn->authentication_flags = AUTH_FLAGS_NONE;
193     conn->bonding_flags = 0;
194     conn->requested_security_level = LEVEL_0;
195 #ifdef ENABLE_CLASSIC
196     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
197     btstack_run_loop_set_timer_context(&conn->timeout, conn);
198     hci_connection_timestamp(conn);
199 #endif
200     conn->acl_recombination_length = 0;
201     conn->acl_recombination_pos = 0;
202     conn->num_acl_packets_sent = 0;
203     conn->num_sco_packets_sent = 0;
204     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
205     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
206     return conn;
207 }
208 
209 
210 /**
211  * get le connection parameter range
212 *
213  * @return le connection parameter range struct
214  */
215 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
216     *range = hci_stack->le_connection_parameter_range;
217 }
218 
219 /**
220  * set le connection parameter range
221  *
222  */
223 
224 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
225     hci_stack->le_connection_parameter_range = *range;
226 }
227 
228 /**
229  * @brief Test if connection parameters are inside in existing rage
230  * @param conn_interval_min (unit: 1.25ms)
231  * @param conn_interval_max (unit: 1.25ms)
232  * @param conn_latency
233  * @param supervision_timeout (unit: 10ms)
234  * @returns 1 if included
235  */
236 int gap_connection_parameter_range_included(le_connection_parameter_range_t * existing_range, uint16_t le_conn_interval_min, uint16_t le_conn_interval_max, uint16_t le_conn_latency, uint16_t le_supervision_timeout){
237     if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
238     if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
239 
240     if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
241     if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
242 
243     if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
244     if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
245 
246     return 1;
247 }
248 
249 /**
250  * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
251  * @note: default: 1
252  * @param max_peripheral_connections
253  */
254 #ifdef ENABLE_LE_PERIPHERAL
255 void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
256     hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
257 }
258 #endif
259 
260 /**
261  * get hci connections iterator
262  *
263  * @return hci connections iterator
264  */
265 
266 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
267     btstack_linked_list_iterator_init(it, &hci_stack->connections);
268 }
269 
270 /**
271  * get connection for a given handle
272  *
273  * @return connection OR NULL, if not found
274  */
275 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
276     btstack_linked_list_iterator_t it;
277     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
278     while (btstack_linked_list_iterator_has_next(&it)){
279         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
280         if ( item->con_handle == con_handle ) {
281             return item;
282         }
283     }
284     return NULL;
285 }
286 
287 /**
288  * get connection for given address
289  *
290  * @return connection OR NULL, if not found
291  */
292 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t  addr, bd_addr_type_t addr_type){
293     btstack_linked_list_iterator_t it;
294     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
295     while (btstack_linked_list_iterator_has_next(&it)){
296         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
297         if (connection->address_type != addr_type)  continue;
298         if (memcmp(addr, connection->address, 6) != 0) continue;
299         return connection;
300     }
301     return NULL;
302 }
303 
304 
305 #ifdef ENABLE_CLASSIC
306 
307 #ifdef ENABLE_SCO_OVER_HCI
308 static int hci_number_sco_connections(void){
309     int connections = 0;
310     btstack_linked_list_iterator_t it;
311     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
312     while (btstack_linked_list_iterator_has_next(&it)){
313         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
314         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
315         connections++;
316     }
317     return connections;
318 }
319 #endif
320 
321 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
322     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
323 #ifdef HAVE_EMBEDDED_TICK
324     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
325         // connections might be timed out
326         hci_emit_l2cap_check_timeout(connection);
327     }
328 #else
329     if (btstack_run_loop_get_time_ms() > connection->timestamp + HCI_CONNECTION_TIMEOUT_MS){
330         // connections might be timed out
331         hci_emit_l2cap_check_timeout(connection);
332     }
333 #endif
334 }
335 
336 static void hci_connection_timestamp(hci_connection_t *connection){
337 #ifdef HAVE_EMBEDDED_TICK
338     connection->timestamp = btstack_run_loop_embedded_get_ticks();
339 #else
340     connection->timestamp = btstack_run_loop_get_time_ms();
341 #endif
342 }
343 
344 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
345     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
346 }
347 
348 
349 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
350     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
351 }
352 
353 /**
354  * add authentication flags and reset timer
355  * @note: assumes classic connection
356  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
357  */
358 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
359     bd_addr_t addr;
360     reverse_bd_addr(bd_addr, addr);
361     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
362     if (conn) {
363         connectionSetAuthenticationFlags(conn, flags);
364         hci_connection_timestamp(conn);
365     }
366 }
367 
368 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
369     hci_connection_t * conn = hci_connection_for_handle(handle);
370     if (!conn) return 0;
371     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
372     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
373     return 0;
374 }
375 
376 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
377     if (!hci_stack->link_key_db) return;
378     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
379     hci_stack->link_key_db->delete_link_key(addr);
380 }
381 
382 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
383     if (!hci_stack->link_key_db) return;
384     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
385     hci_stack->link_key_db->put_link_key(addr, link_key, type);
386 }
387 
388 void gap_delete_all_link_keys(void){
389     bd_addr_t  addr;
390     link_key_t link_key;
391     link_key_type_t type;
392     btstack_link_key_iterator_t it;
393     int ok = gap_link_key_iterator_init(&it);
394     if (!ok) {
395         log_error("could not initialize iterator");
396         return;
397     }
398     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
399         gap_drop_link_key_for_bd_addr(addr);
400     }
401     gap_link_key_iterator_done(&it);
402 }
403 
404 int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
405     if (!hci_stack->link_key_db) return 0;
406     if (!hci_stack->link_key_db->iterator_init) return 0;
407     return hci_stack->link_key_db->iterator_init(it);
408 }
409 int gap_link_key_iterator_get_next(btstack_link_key_iterator_t * it, bd_addr_t bd_addr, link_key_t link_key, link_key_type_t * type){
410     if (!hci_stack->link_key_db) return 0;
411     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
412 }
413 void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
414     if (!hci_stack->link_key_db) return;
415     hci_stack->link_key_db->iterator_done(it);
416 }
417 #endif
418 
419 static int hci_is_le_connection(hci_connection_t * connection){
420     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
421     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
422 }
423 
424 /**
425  * count connections
426  */
427 static int nr_hci_connections(void){
428     int count = 0;
429     btstack_linked_item_t *it;
430     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
431     return count;
432 }
433 
434 static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
435 
436     unsigned int num_packets_sent_classic = 0;
437     unsigned int num_packets_sent_le = 0;
438 
439     btstack_linked_item_t *it;
440     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
441         hci_connection_t * connection = (hci_connection_t *) it;
442         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
443             num_packets_sent_classic += connection->num_acl_packets_sent;
444         } else {
445             num_packets_sent_le += connection->num_acl_packets_sent;
446         }
447     }
448     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
449     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
450     int free_slots_le = 0;
451 
452     if (free_slots_classic < 0){
453         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);
454         return 0;
455     }
456 
457     if (hci_stack->le_acl_packets_total_num){
458         // if we have LE slots, they are used
459         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
460         if (free_slots_le < 0){
461             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);
462             return 0;
463         }
464     } else {
465         // otherwise, classic slots are used for LE, too
466         free_slots_classic -= num_packets_sent_le;
467         if (free_slots_classic < 0){
468             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);
469             return 0;
470         }
471     }
472 
473     switch (address_type){
474         case BD_ADDR_TYPE_UNKNOWN:
475             log_error("hci_number_free_acl_slots: unknown address type");
476             return 0;
477 
478         case BD_ADDR_TYPE_CLASSIC:
479             return free_slots_classic;
480 
481         default:
482            if (hci_stack->le_acl_packets_total_num){
483                return free_slots_le;
484            }
485            return free_slots_classic;
486     }
487 }
488 
489 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
490     // get connection type
491     hci_connection_t * connection = hci_connection_for_handle(con_handle);
492     if (!connection){
493         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
494         return 0;
495     }
496     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
497 }
498 
499 #ifdef ENABLE_CLASSIC
500 static int hci_number_free_sco_slots(void){
501     unsigned int num_sco_packets_sent  = 0;
502     btstack_linked_item_t *it;
503     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
504         hci_connection_t * connection = (hci_connection_t *) it;
505         num_sco_packets_sent += connection->num_sco_packets_sent;
506     }
507     if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
508         log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
509         return 0;
510     }
511     // log_info("hci_number_free_sco_slots u", handle, num_sco_packets_sent);
512     return hci_stack->sco_packets_total_num - num_sco_packets_sent;
513 }
514 #endif
515 
516 // only used to send HCI Host Number Completed Packets
517 static int hci_can_send_comand_packet_transport(void){
518     if (hci_stack->hci_packet_buffer_reserved) return 0;
519 
520     // check for async hci transport implementations
521     if (hci_stack->hci_transport->can_send_packet_now){
522         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
523             return 0;
524         }
525     }
526     return 1;
527 }
528 
529 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
530 int hci_can_send_command_packet_now(void){
531     if (hci_can_send_comand_packet_transport() == 0) return 0;
532     return hci_stack->num_cmd_packets > 0;
533 }
534 
535 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
536     // check for async hci transport implementations
537     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
538     return hci_stack->hci_transport->can_send_packet_now(packet_type);
539 }
540 
541 static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
542     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
543     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
544 }
545 
546 int hci_can_send_acl_le_packet_now(void){
547     if (hci_stack->hci_packet_buffer_reserved) return 0;
548     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
549 }
550 
551 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
552     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
553     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
554 }
555 
556 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
557     if (hci_stack->hci_packet_buffer_reserved) return 0;
558     return hci_can_send_prepared_acl_packet_now(con_handle);
559 }
560 
561 #ifdef ENABLE_CLASSIC
562 int hci_can_send_acl_classic_packet_now(void){
563     if (hci_stack->hci_packet_buffer_reserved) return 0;
564     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_CLASSIC);
565 }
566 
567 int hci_can_send_prepared_sco_packet_now(void){
568     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
569     if (!hci_stack->synchronous_flow_control_enabled) return 1;
570     return hci_number_free_sco_slots() > 0;
571 }
572 
573 int hci_can_send_sco_packet_now(void){
574     if (hci_stack->hci_packet_buffer_reserved) return 0;
575     return hci_can_send_prepared_sco_packet_now();
576 }
577 
578 void hci_request_sco_can_send_now_event(void){
579     hci_stack->sco_waiting_for_can_send_now = 1;
580     hci_notify_if_sco_can_send_now();
581 }
582 #endif
583 
584 // used for internal checks in l2cap.c
585 int hci_is_packet_buffer_reserved(void){
586     return hci_stack->hci_packet_buffer_reserved;
587 }
588 
589 // reserves outgoing packet buffer. @returns 1 if successful
590 int hci_reserve_packet_buffer(void){
591     if (hci_stack->hci_packet_buffer_reserved) {
592         log_error("hci_reserve_packet_buffer called but buffer already reserved");
593         return 0;
594     }
595     hci_stack->hci_packet_buffer_reserved = 1;
596     return 1;
597 }
598 
599 void hci_release_packet_buffer(void){
600     hci_stack->hci_packet_buffer_reserved = 0;
601 }
602 
603 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
604 static int hci_transport_synchronous(void){
605     return hci_stack->hci_transport->can_send_packet_now == NULL;
606 }
607 
608 static int hci_send_acl_packet_fragments(hci_connection_t *connection){
609 
610     // 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);
611 
612     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
613     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
614     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
615         max_acl_data_packet_length = hci_stack->le_data_packets_length;
616     }
617 
618     // testing: reduce buffer to minimum
619     // max_acl_data_packet_length = 52;
620 
621     log_debug("hci_send_acl_packet_fragments entered");
622 
623     int err;
624     // multiple packets could be send on a synchronous HCI transport
625     while (1){
626 
627         log_debug("hci_send_acl_packet_fragments loop entered");
628 
629         // get current data
630         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
631         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
632         int more_fragments = 0;
633 
634         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
635         if (current_acl_data_packet_length > max_acl_data_packet_length){
636             more_fragments = 1;
637             current_acl_data_packet_length = max_acl_data_packet_length;
638         }
639 
640         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
641         if (acl_header_pos > 0){
642             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
643             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
644             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
645         }
646 
647         // update header len
648         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
649 
650         // count packet
651         connection->num_acl_packets_sent++;
652         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", more_fragments);
653 
654         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
655         if (more_fragments){
656             // update start of next fragment to send
657             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
658         } else {
659             // done
660             hci_stack->acl_fragmentation_pos = 0;
661             hci_stack->acl_fragmentation_total_size = 0;
662         }
663 
664         // send packet
665         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
666         const int size = current_acl_data_packet_length + 4;
667         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
668         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
669 
670         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", more_fragments);
671 
672         // done yet?
673         if (!more_fragments) break;
674 
675         // can send more?
676         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
677     }
678 
679     log_debug("hci_send_acl_packet_fragments loop over");
680 
681     // release buffer now for synchronous transport
682     if (hci_transport_synchronous()){
683         hci_release_packet_buffer();
684         hci_emit_transport_packet_sent();
685     }
686 
687     return err;
688 }
689 
690 // pre: caller has reserved the packet buffer
691 int hci_send_acl_packet_buffer(int size){
692 
693     // log_info("hci_send_acl_packet_buffer size %u", size);
694 
695     if (!hci_stack->hci_packet_buffer_reserved) {
696         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
697         return 0;
698     }
699 
700     uint8_t * packet = hci_stack->hci_packet_buffer;
701     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
702 
703     // check for free places on Bluetooth module
704     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
705         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
706         hci_release_packet_buffer();
707         hci_emit_transport_packet_sent();
708         return BTSTACK_ACL_BUFFERS_FULL;
709     }
710 
711     hci_connection_t *connection = hci_connection_for_handle( con_handle);
712     if (!connection) {
713         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
714         hci_release_packet_buffer();
715         hci_emit_transport_packet_sent();
716         return 0;
717     }
718 
719 #ifdef ENABLE_CLASSIC
720     hci_connection_timestamp(connection);
721 #endif
722 
723     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
724 
725     // setup data
726     hci_stack->acl_fragmentation_total_size = size;
727     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
728 
729     return hci_send_acl_packet_fragments(connection);
730 }
731 
732 #ifdef ENABLE_CLASSIC
733 // pre: caller has reserved the packet buffer
734 int hci_send_sco_packet_buffer(int size){
735 
736     // log_info("hci_send_acl_packet_buffer size %u", size);
737 
738     if (!hci_stack->hci_packet_buffer_reserved) {
739         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
740         return 0;
741     }
742 
743     uint8_t * packet = hci_stack->hci_packet_buffer;
744 
745     // skip checks in loopback mode
746     if (!hci_stack->loopback_mode){
747         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
748 
749         // check for free places on Bluetooth module
750         if (!hci_can_send_prepared_sco_packet_now()) {
751             log_error("hci_send_sco_packet_buffer called but no free ACL buffers on controller");
752             hci_release_packet_buffer();
753             hci_emit_transport_packet_sent();
754             return BTSTACK_ACL_BUFFERS_FULL;
755         }
756 
757         // track send packet in connection struct
758         hci_connection_t *connection = hci_connection_for_handle( con_handle);
759         if (!connection) {
760             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
761             hci_release_packet_buffer();
762             hci_emit_transport_packet_sent();
763             return 0;
764         }
765         connection->num_sco_packets_sent++;
766     }
767 
768     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
769     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
770 
771     if (hci_transport_synchronous()){
772         hci_release_packet_buffer();
773         hci_emit_transport_packet_sent();
774     }
775 
776     return err;
777 }
778 #endif
779 
780 static void acl_handler(uint8_t *packet, int size){
781 
782     // log_info("acl_handler: size %u", size);
783 
784     // get info
785     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
786     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
787     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
788     uint16_t acl_length         = READ_ACL_LENGTH(packet);
789 
790     // ignore non-registered handle
791     if (!conn){
792         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
793         return;
794     }
795 
796     // assert packet is complete
797     if (acl_length + 4 != size){
798         log_error("hci.c: acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
799         return;
800     }
801 
802 #ifdef ENABLE_CLASSIC
803     // update idle timestamp
804     hci_connection_timestamp(conn);
805 #endif
806 
807 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
808     hci_stack->host_completed_packets = 1;
809     conn->num_packets_completed++;
810 #endif
811 
812     // handle different packet types
813     switch (acl_flags & 0x03) {
814 
815         case 0x01: // continuation fragment
816 
817             // sanity checks
818             if (conn->acl_recombination_pos == 0) {
819                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
820                 return;
821             }
822             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
823                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
824                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
825                 conn->acl_recombination_pos = 0;
826                 return;
827             }
828 
829             // append fragment payload (header already stored)
830             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
831             conn->acl_recombination_pos += acl_length;
832 
833             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
834             //        conn->acl_recombination_pos, conn->acl_recombination_length);
835 
836             // forward complete L2CAP packet if complete.
837             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
838                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
839                 // reset recombination buffer
840                 conn->acl_recombination_length = 0;
841                 conn->acl_recombination_pos = 0;
842             }
843             break;
844 
845         case 0x02: { // first fragment
846 
847             // sanity check
848             if (conn->acl_recombination_pos) {
849                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
850                 conn->acl_recombination_pos = 0;
851             }
852 
853             // peek into L2CAP packet!
854             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
855 
856             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
857 
858             // compare fragment size to L2CAP packet size
859             if (acl_length >= l2cap_length + 4){
860                 // forward fragment as L2CAP packet
861                 hci_emit_acl_packet(packet, acl_length + 4);
862             } else {
863 
864                 if (acl_length > HCI_ACL_BUFFER_SIZE){
865                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
866                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
867                     return;
868                 }
869 
870                 // store first fragment and tweak acl length for complete package
871                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
872                 conn->acl_recombination_pos    = acl_length + 4;
873                 conn->acl_recombination_length = l2cap_length;
874                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
875             }
876             break;
877 
878         }
879         default:
880             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
881             return;
882     }
883 
884     // execute main loop
885     hci_run();
886 }
887 
888 static void hci_shutdown_connection(hci_connection_t *conn){
889     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
890 
891 #ifdef ENABLE_CLASSIC
892 #ifdef ENABLE_SCO_OVER_HCI
893     int addr_type = conn->address_type;
894 #endif
895 #endif
896 
897     btstack_run_loop_remove_timer(&conn->timeout);
898 
899     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
900     btstack_memory_hci_connection_free( conn );
901 
902     // now it's gone
903     hci_emit_nr_connections_changed();
904 
905 #ifdef ENABLE_CLASSIC
906 #ifdef ENABLE_SCO_OVER_HCI
907     // update SCO
908     if (addr_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
909         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
910     }
911 #endif
912 #endif
913 }
914 
915 #ifdef ENABLE_CLASSIC
916 
917 static const uint16_t packet_type_sizes[] = {
918     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
919     HCI_ACL_DH1_SIZE, 0, 0, 0,
920     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
921     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
922 };
923 static const uint8_t  packet_type_feature_requirement_bit[] = {
924      0, // 3 slot packets
925      1, // 5 slot packets
926     25, // EDR 2 mpbs
927     26, // EDR 3 mbps
928     39, // 3 slot EDR packts
929     40, // 5 slot EDR packet
930 };
931 static const uint16_t packet_type_feature_packet_mask[] = {
932     0x0f00, // 3 slot packets
933     0xf000, // 5 slot packets
934     0x1102, // EDR 2 mpbs
935     0x2204, // EDR 3 mbps
936     0x0300, // 3 slot EDR packts
937     0x3000, // 5 slot EDR packet
938 };
939 
940 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
941     // enable packet types based on size
942     uint16_t packet_types = 0;
943     unsigned int i;
944     for (i=0;i<16;i++){
945         if (packet_type_sizes[i] == 0) continue;
946         if (packet_type_sizes[i] <= buffer_size){
947             packet_types |= 1 << i;
948         }
949     }
950     // disable packet types due to missing local supported features
951     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
952         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
953         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
954         if (feature_set) continue;
955         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
956         packet_types &= ~packet_type_feature_packet_mask[i];
957     }
958     // flip bits for "may not be used"
959     packet_types ^= 0x3306;
960     return packet_types;
961 }
962 
963 uint16_t hci_usable_acl_packet_types(void){
964     return hci_stack->packet_types;
965 }
966 #endif
967 
968 uint8_t* hci_get_outgoing_packet_buffer(void){
969     // hci packet buffer is >= acl data packet length
970     return hci_stack->hci_packet_buffer;
971 }
972 
973 uint16_t hci_max_acl_data_packet_length(void){
974     return hci_stack->acl_data_packet_length;
975 }
976 
977 #ifdef ENABLE_CLASSIC
978 int hci_extended_sco_link_supported(void){
979     // No. 31, byte 3, bit 7
980     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
981 }
982 #endif
983 
984 int hci_non_flushable_packet_boundary_flag_supported(void){
985     // No. 54, byte 6, bit 6
986     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
987 }
988 
989 static int gap_ssp_supported(void){
990     // No. 51, byte 6, bit 3
991     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
992 }
993 
994 static int hci_classic_supported(void){
995 #ifdef ENABLE_CLASSIC
996     // No. 37, byte 4, bit 5, = No BR/EDR Support
997     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
998 #else
999     return 0;
1000 #endif
1001 }
1002 
1003 static int hci_le_supported(void){
1004 #ifdef ENABLE_BLE
1005     // No. 37, byte 4, bit 6 = LE Supported (Controller)
1006     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
1007 #else
1008     return 0;
1009 #endif
1010 }
1011 
1012 #ifdef ENABLE_BLE
1013 
1014 /**
1015  * @brief Get addr type and address used for LE in Advertisements, Scan Responses,
1016  */
1017 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
1018     *addr_type = hci_stack->le_own_addr_type;
1019     if (hci_stack->le_own_addr_type){
1020         memcpy(addr, hci_stack->le_random_address, 6);
1021     } else {
1022         memcpy(addr, hci_stack->local_bd_addr, 6);
1023     }
1024 }
1025 
1026 #ifdef ENABLE_LE_CENTRAL
1027 void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
1028 
1029     int offset = 3;
1030     int num_reports = packet[offset];
1031     offset += 1;
1032 
1033     int i;
1034     // log_info("HCI: handle adv report with num reports: %d", num_reports);
1035     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1036     for (i=0; i<num_reports && offset < size;i++){
1037         uint8_t data_length = btstack_min( packet[offset + 8], LE_ADVERTISING_DATA_SIZE);
1038         uint8_t event_size = 10 + data_length;
1039         int pos = 0;
1040         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1041         event[pos++] = event_size;
1042         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
1043         offset += 8;
1044         pos += 8;
1045         event[pos++] = packet[offset + 1 + data_length]; // rssi
1046         event[pos++] = packet[offset++]; //data_length;
1047         memcpy(&event[pos], &packet[offset], data_length);
1048         pos += data_length;
1049         offset += data_length + 1; // rssi
1050         hci_emit_event(event, pos, 1);
1051     }
1052 }
1053 #endif
1054 #endif
1055 
1056 #ifdef ENABLE_BLE
1057 #ifdef ENABLE_LE_PERIPHERAL
1058 static void hci_reenable_advertisements_if_needed(void){
1059     if (!hci_stack->le_advertisements_active && hci_stack->le_advertisements_enabled){
1060         // get number of active le slave connections
1061         int num_slave_connections = 0;
1062         btstack_linked_list_iterator_t it;
1063         btstack_linked_list_iterator_init(&it, &hci_stack->connections);
1064         while (btstack_linked_list_iterator_has_next(&it)){
1065             hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
1066             log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con));
1067             if (con->state != OPEN) continue;
1068             if (con->role  != HCI_ROLE_SLAVE) continue;
1069             if (!hci_is_le_connection(con)) continue;
1070             num_slave_connections++;
1071         }
1072         log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections);
1073         if (num_slave_connections < hci_stack->le_max_number_peripheral_connections){
1074             hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
1075         }
1076     }
1077 }
1078 #endif
1079 #endif
1080 
1081 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1082 
1083 static uint32_t hci_transport_uart_get_main_baud_rate(void){
1084     if (!hci_stack->config) return 0;
1085     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1086     // Limit baud rate for Broadcom chipsets to 3 mbps
1087     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION && baud_rate > 3000000){
1088         baud_rate = 3000000;
1089     }
1090     return baud_rate;
1091 }
1092 
1093 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
1094     UNUSED(ds);
1095 
1096     switch (hci_stack->substate){
1097         case HCI_INIT_W4_SEND_RESET:
1098             log_info("Resend HCI Reset");
1099             hci_stack->substate = HCI_INIT_SEND_RESET;
1100             hci_stack->num_cmd_packets = 1;
1101             hci_run();
1102             break;
1103         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
1104             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
1105             if (hci_stack->hci_transport->reset_link){
1106                 hci_stack->hci_transport->reset_link();
1107             }
1108             // no break - explicit fallthrough to HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT
1109         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1110             log_info("Resend HCI Reset - CSR Warm Boot");
1111             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1112             hci_stack->num_cmd_packets = 1;
1113             hci_run();
1114             break;
1115         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1116             if (hci_stack->hci_transport->set_baudrate){
1117                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1118                 log_info("Local baud rate change to %"PRIu32"(timeout handler)", baud_rate);
1119                 hci_stack->hci_transport->set_baudrate(baud_rate);
1120             }
1121             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
1122             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1123                 if (hci_stack->hci_transport->reset_link){
1124                     log_info("Link Reset");
1125                     hci_stack->hci_transport->reset_link();
1126                 }
1127                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1128                 hci_run();
1129             }
1130             break;
1131         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1132             // otherwise continue
1133             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1134             hci_send_cmd(&hci_read_local_supported_commands);
1135             break;
1136         default:
1137             break;
1138     }
1139 }
1140 #endif
1141 
1142 static void hci_initializing_next_state(void){
1143     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
1144 }
1145 
1146 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_PERIPHERAL)
1147 static void hci_replace_bd_addr_placeholder(uint8_t * data, uint16_t size){
1148     const int bd_addr_string_len = 17;
1149     int i = 0;
1150     while (i < size - bd_addr_string_len){
1151         if (memcmp(&data[i], "00:00:00:00:00:00", bd_addr_string_len)) {
1152             i++;
1153             continue;
1154         }
1155         // set real address
1156         memcpy(&data[i], bd_addr_to_str(hci_stack->local_bd_addr), bd_addr_string_len);
1157         i += bd_addr_string_len;
1158     }
1159 }
1160 #endif
1161 
1162 // assumption: hci_can_send_command_packet_now() == true
1163 static void hci_initializing_run(void){
1164     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
1165     switch (hci_stack->substate){
1166         case HCI_INIT_SEND_RESET:
1167             hci_state_reset();
1168 
1169 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1170             // prepare reset if command complete not received in 100ms
1171             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1172             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1173             btstack_run_loop_add_timer(&hci_stack->timeout);
1174 #endif
1175             // send command
1176             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1177             hci_send_cmd(&hci_reset);
1178             break;
1179         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
1180             hci_send_cmd(&hci_read_local_version_information);
1181             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
1182             break;
1183         case HCI_INIT_SEND_READ_LOCAL_NAME:
1184             hci_send_cmd(&hci_read_local_name);
1185             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1186             break;
1187 
1188 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1189         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1190             hci_state_reset();
1191             // prepare reset if command complete not received in 100ms
1192             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1193             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1194             btstack_run_loop_add_timer(&hci_stack->timeout);
1195             // send command
1196             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1197             hci_send_cmd(&hci_reset);
1198             break;
1199         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
1200             hci_state_reset();
1201             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
1202             hci_send_cmd(&hci_reset);
1203             break;
1204         case HCI_INIT_SEND_BAUD_CHANGE: {
1205             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1206             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1207             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1208             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1209             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1210             // STLC25000D: baudrate change happens within 0.5 s after command was send,
1211             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
1212             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1213                 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1214                 btstack_run_loop_add_timer(&hci_stack->timeout);
1215             }
1216             break;
1217         }
1218         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1219             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1220             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1221             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1222             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1223             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1224             break;
1225         }
1226         case HCI_INIT_CUSTOM_INIT:
1227             // Custom initialization
1228             if (hci_stack->chipset && hci_stack->chipset->next_command){
1229                 int valid_cmd = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
1230                 if (valid_cmd){
1231                     int size = 3 + hci_stack->hci_packet_buffer[2];
1232                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1233                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
1234                     switch (valid_cmd) {
1235                         case BTSTACK_CHIPSET_VALID_COMMAND:
1236                             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1237                             break;
1238                         case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
1239                             // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1240                             log_info("CSR Warm Boot");
1241                             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1242                             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1243                             btstack_run_loop_add_timer(&hci_stack->timeout);
1244                             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO
1245                                 && hci_stack->config
1246                                 && hci_stack->chipset
1247                                 // && hci_stack->chipset->set_baudrate_command -- there's no such command
1248                                 && hci_stack->hci_transport->set_baudrate
1249                                 && hci_transport_uart_get_main_baud_rate()){
1250                                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1251                             } else {
1252                                hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1253                             }
1254                             break;
1255                         default:
1256                             // should not get here
1257                             break;
1258                     }
1259                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1260                     break;
1261                 }
1262                 log_info("Init script done");
1263 
1264                 // Init script download on Broadcom chipsets causes:
1265                 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION
1266                 ||  hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA){
1267 
1268                     // - baud rate to reset, restore UART baud rate if needed
1269                     int need_baud_change = hci_stack->config
1270                         && hci_stack->chipset
1271                         && hci_stack->chipset->set_baudrate_command
1272                         && hci_stack->hci_transport->set_baudrate
1273                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1274                     if (need_baud_change) {
1275                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1276                         log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate);
1277                         hci_stack->hci_transport->set_baudrate(baud_rate);
1278                     }
1279 
1280                     // - RTS will raise during update, but manual RTS/CTS in WICED port on RedBear Duo cannot handle this
1281                     //   -> Work around: wait a few milliseconds here.
1282                     log_info("BCM delay after init script");
1283                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1284                     btstack_run_loop_set_timer(&hci_stack->timeout, 10);
1285                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1286                     btstack_run_loop_add_timer(&hci_stack->timeout);
1287                     break;
1288                 }
1289             }
1290             // otherwise continue
1291             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1292             hci_send_cmd(&hci_read_local_supported_commands);
1293             break;
1294         case HCI_INIT_SET_BD_ADDR:
1295             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1296             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1297             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1298             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1299             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1300             break;
1301 #endif
1302 
1303         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
1304             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
1305             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1306             hci_send_cmd(&hci_read_local_supported_commands);
1307             break;
1308         case HCI_INIT_READ_BD_ADDR:
1309             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
1310             hci_send_cmd(&hci_read_bd_addr);
1311             break;
1312         case HCI_INIT_READ_BUFFER_SIZE:
1313             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
1314             hci_send_cmd(&hci_read_buffer_size);
1315             break;
1316         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
1317             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
1318             hci_send_cmd(&hci_read_local_supported_features);
1319             break;
1320 
1321 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
1322         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
1323             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
1324             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
1325             break;
1326         case HCI_INIT_HOST_BUFFER_SIZE:
1327             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
1328             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
1329                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
1330             break;
1331 #endif
1332 
1333         case HCI_INIT_SET_EVENT_MASK:
1334             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
1335             if (hci_le_supported()){
1336                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1337             } else {
1338                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1339                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1340             }
1341             break;
1342 
1343 #ifdef ENABLE_CLASSIC
1344         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1345             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
1346             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1347             break;
1348         case HCI_INIT_WRITE_PAGE_TIMEOUT:
1349             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
1350             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
1351             break;
1352         case HCI_INIT_WRITE_DEFAULT_LINK_POLICY_SETTING:
1353             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_LINK_POLICY_SETTING;
1354             hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings);
1355             break;
1356         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
1357             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
1358             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1359             break;
1360         case HCI_INIT_WRITE_LOCAL_NAME: {
1361             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
1362             hci_reserve_packet_buffer();
1363             uint8_t * packet = hci_stack->hci_packet_buffer;
1364             // construct HCI Command and send
1365             uint16_t opcode = hci_write_local_name.opcode;
1366             hci_stack->last_cmd_opcode = opcode;
1367             packet[0] = opcode & 0xff;
1368             packet[1] = opcode >> 8;
1369             packet[2] = DEVICE_NAME_LEN;
1370             memset(&packet[3], 0, DEVICE_NAME_LEN);
1371             memcpy(&packet[3], hci_stack->local_name, strlen(hci_stack->local_name));
1372             // expand '00:00:00:00:00:00' in name with bd_addr
1373             hci_replace_bd_addr_placeholder(&packet[3], DEVICE_NAME_LEN);
1374             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
1375             break;
1376         }
1377         case HCI_INIT_WRITE_EIR_DATA: {
1378             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
1379             hci_reserve_packet_buffer();
1380             uint8_t * packet = hci_stack->hci_packet_buffer;
1381             // construct HCI Command and send
1382             uint16_t opcode = hci_write_extended_inquiry_response.opcode;
1383             hci_stack->last_cmd_opcode = opcode;
1384             packet[0] = opcode & 0xff;
1385             packet[1] = opcode >> 8;
1386             packet[2] = 1 + 240;
1387             packet[3] = 0;  // FEC not required
1388             if (hci_stack->eir_data){
1389                 memcpy(&packet[4], hci_stack->eir_data, 240);
1390             } else {
1391                 memset(&packet[4], 0, 240);
1392                 int name_len = strlen(hci_stack->local_name);
1393                 packet[4] = name_len + 1;
1394                 packet[5] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
1395                 memcpy(&packet[6], hci_stack->local_name, name_len);
1396             }
1397             // expand '00:00:00:00:00:00' in name with bd_addr
1398             hci_replace_bd_addr_placeholder(&packet[4], 240);
1399             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + 240);
1400             break;
1401         }
1402         case HCI_INIT_WRITE_INQUIRY_MODE:
1403             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
1404             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1405             break;
1406         case HCI_INIT_WRITE_SCAN_ENABLE:
1407             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1408             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
1409             break;
1410         // only sent if ENABLE_SCO_OVER_HCI is defined
1411         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1412             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1413             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1414             break;
1415         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1416             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1417             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1418             break;
1419         // only sent if ENABLE_SCO_OVER_HCI and manufacturer is Broadcom
1420         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1421             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1422             log_info("BCM: Route SCO data via HCI transport");
1423             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
1424             break;
1425 
1426 #endif
1427 #ifdef ENABLE_BLE
1428         // LE INIT
1429         case HCI_INIT_LE_READ_BUFFER_SIZE:
1430             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
1431             hci_send_cmd(&hci_le_read_buffer_size);
1432             break;
1433         case HCI_INIT_LE_SET_EVENT_MASK:
1434             hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
1435             hci_send_cmd(&hci_le_set_event_mask, 0x1FF, 0x0);
1436             break;
1437         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
1438             // LE Supported Host = 1, Simultaneous Host = 0
1439             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
1440             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1441             break;
1442 #endif
1443 
1444 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1445         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
1446             hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
1447             hci_send_cmd(&hci_le_read_maximum_data_length);
1448             break;
1449         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
1450             hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
1451             hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1452             break;
1453 #endif
1454 
1455 #ifdef ENABLE_LE_CENTRAL
1456         case HCI_INIT_READ_WHITE_LIST_SIZE:
1457             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
1458             hci_send_cmd(&hci_le_read_white_list_size);
1459             break;
1460         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1461             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, own address type, accept all advs
1462             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1463             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, hci_stack->le_own_addr_type, 0);
1464             break;
1465 #endif
1466         default:
1467             return;
1468     }
1469 }
1470 
1471 static void hci_init_done(void){
1472     // done. tell the app
1473     log_info("hci_init_done -> HCI_STATE_WORKING");
1474     hci_stack->state = HCI_STATE_WORKING;
1475     hci_emit_state();
1476     hci_run();
1477 }
1478 
1479 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
1480 
1481     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
1482 
1483     uint8_t command_completed = 0;
1484 
1485     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1486         uint16_t opcode = little_endian_read_16(packet,3);
1487         if (opcode == hci_stack->last_cmd_opcode){
1488             command_completed = 1;
1489             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
1490         } else {
1491             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
1492         }
1493     }
1494 
1495     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
1496         uint8_t  status = packet[2];
1497         uint16_t opcode = little_endian_read_16(packet,4);
1498         if (opcode == hci_stack->last_cmd_opcode){
1499             if (status){
1500                 command_completed = 1;
1501                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
1502             } else {
1503                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
1504             }
1505         } else {
1506             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1507         }
1508     }
1509 
1510 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1511 
1512     // Vendor == CSR
1513     if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1514         // TODO: track actual command
1515         command_completed = 1;
1516     }
1517 
1518     // Vendor == Toshiba
1519     if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1520         // TODO: track actual command
1521         command_completed = 1;
1522         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
1523         hci_stack->num_cmd_packets = 1;
1524     }
1525 
1526     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1527     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1528     //
1529     // HCI Reset
1530     // Timeout 100 ms
1531     // HCI Reset
1532     // Command Complete Reset
1533     // HCI Read Local Version Information
1534     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1535     // hang...
1536     //
1537     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1538     if (!command_completed
1539             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1540             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
1541 
1542         uint16_t opcode = little_endian_read_16(packet,3);
1543         if (opcode == hci_reset.opcode){
1544             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1545             return;
1546         }
1547     }
1548 
1549     // CSR & H5
1550     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1551     if (!command_completed
1552             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1553             && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){
1554 
1555         uint16_t opcode = little_endian_read_16(packet,3);
1556         if (opcode == hci_reset.opcode){
1557             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1558             return;
1559         }
1560     }
1561 
1562     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
1563     // fix: Correct substate and behave as command below
1564     if (command_completed){
1565         switch (hci_stack->substate){
1566             case HCI_INIT_SEND_RESET:
1567                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1568                 break;
1569             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1570                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1571                 break;
1572             default:
1573                 break;
1574         }
1575     }
1576 
1577 #endif
1578 
1579     if (!command_completed) return;
1580 
1581     int need_baud_change = 0;
1582     int need_addr_change = 0;
1583 
1584 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1585     need_baud_change = hci_stack->config
1586                         && hci_stack->chipset
1587                         && hci_stack->chipset->set_baudrate_command
1588                         && hci_stack->hci_transport->set_baudrate
1589                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1590 
1591     need_addr_change = hci_stack->custom_bd_addr_set
1592                         && hci_stack->chipset
1593                         && hci_stack->chipset->set_bd_addr_command;
1594 #endif
1595 
1596     switch(hci_stack->substate){
1597 
1598 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1599         case HCI_INIT_SEND_RESET:
1600             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
1601             // fix: just correct substate and behave as command below
1602             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1603             btstack_run_loop_remove_timer(&hci_stack->timeout);
1604             break;
1605         case HCI_INIT_W4_SEND_RESET:
1606             btstack_run_loop_remove_timer(&hci_stack->timeout);
1607             break;
1608         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
1609             log_info("Received local name, need baud change %d", need_baud_change);
1610             if (need_baud_change){
1611                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
1612                 return;
1613             }
1614             // skip baud change
1615             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1616             return;
1617         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1618             // for STLC2500D, baud rate change already happened.
1619             // for others, baud rate gets changed now
1620             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
1621                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1622                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1623                 hci_stack->hci_transport->set_baudrate(baud_rate);
1624             }
1625             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1626             return;
1627         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1628             btstack_run_loop_remove_timer(&hci_stack->timeout);
1629             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1630             return;
1631         case HCI_INIT_W4_CUSTOM_INIT:
1632             // repeat custom init
1633             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1634             return;
1635 #else
1636         case HCI_INIT_W4_SEND_RESET:
1637             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1638             return ;
1639 #endif
1640 
1641         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1642             if (need_baud_change &&
1643               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
1644                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
1645                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1646                 return;
1647             }
1648             if (need_addr_change){
1649                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1650                 return;
1651             }
1652             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1653             return;
1654 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1655         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
1656             if (need_baud_change){
1657                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1658                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1659                 hci_stack->hci_transport->set_baudrate(baud_rate);
1660             }
1661             if (need_addr_change){
1662                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1663                 return;
1664             }
1665             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1666             return;
1667         case HCI_INIT_W4_SET_BD_ADDR:
1668             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
1669             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
1670             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
1671                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
1672                 return;
1673             }
1674             // skipping st warm boot
1675             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1676             return;
1677         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
1678             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1679             return;
1680 #endif
1681         case HCI_INIT_W4_READ_BD_ADDR:
1682             // only read buffer size if supported
1683             if (hci_stack->local_supported_commands[0] & 0x01) {
1684                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
1685                 return;
1686             }
1687             // skipping read buffer size
1688             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1689             return;
1690         case HCI_INIT_W4_SET_EVENT_MASK:
1691             // skip Classic init commands for LE only chipsets
1692             if (!hci_classic_supported()){
1693 #ifdef ENABLE_BLE
1694                 if (hci_le_supported()){
1695                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
1696                     return;
1697                 }
1698 #endif
1699                 log_error("Neither BR/EDR nor LE supported");
1700                 hci_init_done();
1701                 return;
1702             }
1703             if (!gap_ssp_supported()){
1704                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
1705                 return;
1706             }
1707             break;
1708 #ifdef ENABLE_BLE
1709         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1710             // skip write le host if not supported (e.g. on LE only EM9301)
1711             if (hci_stack->local_supported_commands[0] & 0x02) break;
1712             hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1713             return;
1714 
1715 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1716         case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED:
1717             log_info("Supported commands %x", hci_stack->local_supported_commands[0] & 0x30);
1718             if ((hci_stack->local_supported_commands[0] & 0x30) == 0x30){
1719                 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1720                 return;
1721             }
1722             // explicit fall through to reduce repetitions
1723 
1724 #ifdef ENABLE_LE_CENTRAL
1725             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1726 #else
1727             hci_init_done();
1728 #endif
1729             return;
1730 #endif  /* ENABLE_LE_DATA_LENGTH_EXTENSION */
1731 
1732 #endif  /* ENABLE_BLE */
1733 
1734 #ifdef ENABLE_SCO_OVER_HCI
1735         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1736             // skip write synchronous flow control if not supported
1737             if (hci_stack->local_supported_commands[0] & 0x04) break;
1738             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1739             // explicit fall through to reduce repetitions
1740 
1741         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1742             // skip write default erroneous data reporting if not supported
1743             if (hci_stack->local_supported_commands[0] & 0x08) break;
1744             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1745             // explicit fall through to reduce repetitions
1746 
1747         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1748             // skip bcm set sco pcm config on non-Broadcom chipsets
1749             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break;
1750             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1751             // explicit fall through to reduce repetitions
1752 
1753         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1754             if (!hci_le_supported()){
1755                 // SKIP LE init for Classic only configuration
1756                 hci_init_done();
1757                 return;
1758             }
1759             break;
1760 
1761 #else /* !ENABLE_SCO_OVER_HCI */
1762 
1763         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1764 #ifdef ENABLE_BLE
1765             if (hci_le_supported()){
1766                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
1767                 return;
1768             }
1769 #endif
1770             // SKIP LE init for Classic only configuration
1771             hci_init_done();
1772             return;
1773 #endif /* ENABLE_SCO_OVER_HCI */
1774 
1775 // avoid compile error due to duplicate cases: HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT == HCI_INIT_DONE-1
1776 #if defined(ENABLE_BLE) || defined(ENABLE_LE_DATA_LENGTH_EXTENSION) || defined(ENABLE_LE_CENTRAL)
1777         // Response to command before init done state -> init done
1778         case (HCI_INIT_DONE-1):
1779             hci_init_done();
1780             return;
1781 #endif
1782 
1783         default:
1784             break;
1785     }
1786     hci_initializing_next_state();
1787 }
1788 
1789 static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){
1790     log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address));
1791     bd_addr_t bd_address;
1792     memcpy(&bd_address, conn->address, 6);
1793 
1794 #ifdef ENABLE_CLASSIC
1795     // cache needed data
1796     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1797 #endif
1798 
1799     // connection failed, remove entry
1800     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1801     btstack_memory_hci_connection_free( conn );
1802 
1803 #ifdef ENABLE_CLASSIC
1804     // notify client if dedicated bonding
1805     if (notify_dedicated_bonding_failed){
1806         log_info("hci notify_dedicated_bonding_failed");
1807         hci_emit_dedicated_bonding_result(bd_address, status);
1808     }
1809 
1810     // if authentication error, also delete link key
1811     if (status == ERROR_CODE_AUTHENTICATION_FAILURE) {
1812         gap_drop_link_key_for_bd_addr(bd_address);
1813     }
1814 #endif
1815 }
1816 
1817 static void event_handler(uint8_t *packet, int size){
1818 
1819     uint16_t event_length = packet[1];
1820 
1821     // assert packet is complete
1822     if (size != event_length + 2){
1823         log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
1824         return;
1825     }
1826 
1827     bd_addr_t addr;
1828     bd_addr_type_t addr_type;
1829     hci_con_handle_t handle;
1830     hci_connection_t * conn;
1831     int i;
1832     int create_connection_cmd;
1833 
1834 #ifdef ENABLE_CLASSIC
1835     uint8_t link_type;
1836 #endif
1837 
1838     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
1839 
1840     switch (hci_event_packet_get_type(packet)) {
1841 
1842         case HCI_EVENT_COMMAND_COMPLETE:
1843             // get num cmd packets - limit to 1 to reduce complexity
1844             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
1845 
1846             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
1847                 if (packet[5]) break;
1848                 // terminate, name 248 chars
1849                 packet[6+248] = 0;
1850                 log_info("local name: %s", &packet[6]);
1851             }
1852             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1853                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1854                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1855                     uint16_t acl_len = little_endian_read_16(packet, 6);
1856                     uint16_t sco_len = packet[8];
1857 
1858                     // determine usable ACL/SCO payload size
1859                     hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
1860                     hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
1861 
1862                     hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1863                     hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1864 
1865                     log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
1866                              acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1867                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1868                 }
1869             }
1870 #ifdef ENABLE_BLE
1871             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1872                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1873                 hci_stack->le_acl_packets_total_num  = packet[8];
1874                 // determine usable ACL payload size
1875                 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1876                     hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1877                 }
1878                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1879             }
1880 #endif
1881 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1882             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_maximum_data_length)){
1883                 hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
1884                 hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
1885                 log_info("hci_le_read_maximum_data_length: tx octets %u, tx time %u us", hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1886             }
1887 #endif
1888 #ifdef ENABLE_LE_CENTRAL
1889             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1890                 hci_stack->le_whitelist_capacity = packet[6];
1891                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1892             }
1893 #endif
1894             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1895                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1896 				hci_stack->local_bd_addr);
1897                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1898                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1899 #ifdef ENABLE_CLASSIC
1900                 if (hci_stack->link_key_db){
1901                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1902                 }
1903 #endif
1904             }
1905 #ifdef ENABLE_CLASSIC
1906             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1907                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1908             }
1909             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_inquiry_cancel)){
1910                 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
1911                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1912                     uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1913                     hci_emit_event(event, sizeof(event), 1);
1914                 }
1915             }
1916 #endif
1917 
1918             // Note: HCI init checks
1919             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1920                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1921 
1922 #ifdef ENABLE_CLASSIC
1923                 // determine usable ACL packet types based on host buffer size and supported features
1924                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1925                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
1926 #endif
1927                 // Classic/LE
1928                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1929             }
1930             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1931                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1932                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1933                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1934                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1935                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1936                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1937             }
1938             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1939                 hci_stack->local_supported_commands[0] =
1940                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7 / Read Buffer Size
1941                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6 / Write Le Host Supported
1942                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4 / Write Synchronous Flow Control Enable
1943                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08)      |  // bit 3 = Octet 18, bit 3 / Write Default Erroneous Data Reporting
1944                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x01) << 4 |  // bit 4 = Octet 34, bit 0 / LE Write Suggested Default Data Length
1945                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x08) << 2 |  // bit 5 = Octet 35, bit 3 / LE Read Maximum Data Length
1946                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x20) << 1;   // bit 6 = Octet 35, bit 5 / LE Set Default PHY
1947                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1948             }
1949 #ifdef ENABLE_CLASSIC
1950             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1951                 if (packet[5] == 0){
1952                     hci_stack->synchronous_flow_control_enabled = 1;
1953                 }
1954             }
1955 #endif
1956             break;
1957 
1958         case HCI_EVENT_COMMAND_STATUS:
1959             // get num cmd packets - limit to 1 to reduce complexity
1960             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
1961 
1962             // check command status to detected failed outgoing connections
1963             create_connection_cmd = 0;
1964 #ifdef ENABLE_CLASSIC
1965             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
1966                 create_connection_cmd = 1;
1967             }
1968 #endif
1969 #ifdef ENABLE_LE_CENTRAL
1970             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_le_create_connection)){
1971                 create_connection_cmd = 1;
1972             }
1973 #endif
1974             if (create_connection_cmd) {
1975                 uint8_t status = hci_event_command_status_get_status(packet);
1976                 conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, hci_stack->outgoing_addr_type);
1977                 log_info("command status (create connection), status %x, connection %p, addr %s, type %x", status, conn, bd_addr_to_str(hci_stack->outgoing_addr), hci_stack->outgoing_addr_type);
1978 
1979                 // reset outgoing address info
1980                 memset(hci_stack->outgoing_addr, 0, 6);
1981                 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN;
1982 
1983                 // error => outgoing connection failed
1984                 if ((conn != NULL) && (status != 0)){
1985                     hci_handle_connection_failed(conn, status);
1986                 }
1987             }
1988             break;
1989 
1990         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1991             int offset = 3;
1992             for (i=0; i<packet[2];i++){
1993                 handle = little_endian_read_16(packet, offset) & 0x0fff;
1994                 offset += 2;
1995                 uint16_t num_packets = little_endian_read_16(packet, offset);
1996                 offset += 2;
1997 
1998                 conn = hci_connection_for_handle(handle);
1999                 if (!conn){
2000                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
2001                     continue;
2002                 }
2003 
2004                 if (conn->address_type == BD_ADDR_TYPE_SCO){
2005 #ifdef ENABLE_CLASSIC
2006                     if (conn->num_sco_packets_sent >= num_packets){
2007                         conn->num_sco_packets_sent -= num_packets;
2008                     } else {
2009                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
2010                         conn->num_sco_packets_sent = 0;
2011                     }
2012                     hci_notify_if_sco_can_send_now();
2013 #endif
2014                 } else {
2015                     if (conn->num_acl_packets_sent >= num_packets){
2016                         conn->num_acl_packets_sent -= num_packets;
2017                     } else {
2018                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
2019                         conn->num_acl_packets_sent = 0;
2020                     }
2021                 }
2022                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
2023             }
2024             break;
2025         }
2026 
2027 #ifdef ENABLE_CLASSIC
2028         case HCI_EVENT_INQUIRY_COMPLETE:
2029             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
2030                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
2031                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
2032                 hci_emit_event(event, sizeof(event), 1);
2033             }
2034             break;
2035         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
2036             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
2037                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
2038             }
2039             break;
2040         case HCI_EVENT_CONNECTION_REQUEST:
2041             reverse_bd_addr(&packet[2], addr);
2042             // TODO: eval COD 8-10
2043             link_type = packet[11];
2044             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
2045             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
2046             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2047             if (!conn) {
2048                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2049             }
2050             if (!conn) {
2051                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
2052                 hci_stack->decline_reason = 0x0d;
2053                 bd_addr_copy(hci_stack->decline_addr, addr);
2054                 break;
2055             }
2056             conn->role  = HCI_ROLE_SLAVE;
2057             conn->state = RECEIVED_CONNECTION_REQUEST;
2058             // store info about eSCO
2059             if (link_type == 0x02){
2060                 conn->remote_supported_feature_eSCO = 1;
2061             }
2062             hci_run();
2063             break;
2064 
2065         case HCI_EVENT_CONNECTION_COMPLETE:
2066             // Connection management
2067             reverse_bd_addr(&packet[5], addr);
2068             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2069             addr_type = BD_ADDR_TYPE_CLASSIC;
2070             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2071             if (conn) {
2072                 if (!packet[2]){
2073                     conn->state = OPEN;
2074                     conn->con_handle = little_endian_read_16(packet, 3);
2075                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
2076 
2077                     // restart timer
2078                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2079                     btstack_run_loop_add_timer(&conn->timeout);
2080 
2081                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2082 
2083                     hci_emit_nr_connections_changed();
2084                 } else {
2085                     // connection failed
2086                     hci_handle_connection_failed(conn, packet[2]);
2087                 }
2088             }
2089             break;
2090 
2091         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
2092             reverse_bd_addr(&packet[5], addr);
2093             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
2094             if (packet[2]){
2095                 // connection failed
2096                 break;
2097             }
2098             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2099             if (!conn) {
2100                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
2101             }
2102             if (!conn) {
2103                 break;
2104             }
2105             conn->state = OPEN;
2106             conn->con_handle = little_endian_read_16(packet, 3);
2107 
2108 #ifdef ENABLE_SCO_OVER_HCI
2109             // update SCO
2110             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
2111                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
2112             }
2113 #endif
2114             break;
2115 
2116         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2117             handle = little_endian_read_16(packet, 3);
2118             conn = hci_connection_for_handle(handle);
2119             if (!conn) break;
2120             if (!packet[2]){
2121                 uint8_t * features = &packet[5];
2122                 if (features[6] & (1 << 3)){
2123                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
2124                 }
2125                 if (features[3] & (1<<7)){
2126                     conn->remote_supported_feature_eSCO = 1;
2127                 }
2128             }
2129             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2130             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
2131             if (conn->bonding_flags & BONDING_DEDICATED){
2132                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2133             }
2134             break;
2135 
2136         case HCI_EVENT_LINK_KEY_REQUEST:
2137             log_info("HCI_EVENT_LINK_KEY_REQUEST");
2138             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
2139             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
2140             if (hci_stack->bondable && !hci_stack->link_key_db) break;
2141             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
2142             hci_run();
2143             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
2144             return;
2145 
2146         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2147             reverse_bd_addr(&packet[2], addr);
2148             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2149             if (!conn) break;
2150             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
2151             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2152             // Change Connection Encryption keeps link key type
2153             if (link_key_type != CHANGED_COMBINATION_KEY){
2154                 conn->link_key_type = link_key_type;
2155             }
2156             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2157             // still forward event to allow dismiss of pairing dialog
2158             break;
2159         }
2160 
2161         case HCI_EVENT_PIN_CODE_REQUEST:
2162             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
2163             // non-bondable mode: pin code negative reply will be sent
2164             if (!hci_stack->bondable){
2165                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
2166                 hci_run();
2167                 return;
2168             }
2169             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
2170             if (!hci_stack->link_key_db) break;
2171             hci_event_pin_code_request_get_bd_addr(packet, addr);
2172             hci_stack->link_key_db->delete_link_key(addr);
2173             break;
2174 
2175         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2176             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
2177             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
2178             break;
2179 
2180         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2181             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2182             if (!hci_stack->ssp_auto_accept) break;
2183             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
2184             break;
2185 
2186         case HCI_EVENT_USER_PASSKEY_REQUEST:
2187             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2188             if (!hci_stack->ssp_auto_accept) break;
2189             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
2190             break;
2191         case HCI_EVENT_MODE_CHANGE:
2192             handle = hci_event_mode_change_get_handle(packet);
2193             conn = hci_connection_for_handle(handle);
2194             if (!conn) break;
2195             conn->connection_mode = hci_event_mode_change_get_mode(packet);
2196             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
2197             break;
2198 #endif
2199 
2200         case HCI_EVENT_ENCRYPTION_CHANGE:
2201             handle = little_endian_read_16(packet, 3);
2202             conn = hci_connection_for_handle(handle);
2203             if (!conn) break;
2204             if (packet[2] == 0) {
2205                 if (packet[5]){
2206                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
2207                 } else {
2208                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
2209                 }
2210             }
2211 #ifdef ENABLE_CLASSIC
2212             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2213 #endif
2214             break;
2215 
2216 #ifdef ENABLE_CLASSIC
2217         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2218             handle = little_endian_read_16(packet, 3);
2219             conn = hci_connection_for_handle(handle);
2220             if (!conn) break;
2221 
2222             // dedicated bonding: send result and disconnect
2223             if (conn->bonding_flags & BONDING_DEDICATED){
2224                 conn->bonding_flags &= ~BONDING_DEDICATED;
2225                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2226                 conn->bonding_status = packet[2];
2227                 break;
2228             }
2229 
2230             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
2231                 // link key sufficient for requested security
2232                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2233                 break;
2234             }
2235             // not enough
2236             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2237             break;
2238 #endif
2239 
2240         // HCI_EVENT_DISCONNECTION_COMPLETE
2241         // has been split, to first notify stack before shutting connection down
2242         // see end of function, too.
2243         case HCI_EVENT_DISCONNECTION_COMPLETE:
2244             if (packet[2]) break;   // status != 0
2245             handle = little_endian_read_16(packet, 3);
2246             // drop outgoing ACL fragments if it is for closed connection
2247             if (hci_stack->acl_fragmentation_total_size > 0) {
2248                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
2249                     log_info("hci: drop fragmented ACL data for closed connection");
2250                      hci_stack->acl_fragmentation_total_size = 0;
2251                      hci_stack->acl_fragmentation_pos = 0;
2252                 }
2253             }
2254 
2255             // re-enable advertisements for le connections if active
2256             conn = hci_connection_for_handle(handle);
2257             if (!conn) break;
2258             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2259 #ifdef ENABLE_BLE
2260 #ifdef ENABLE_LE_PERIPHERAL
2261             if (hci_is_le_connection(conn)){
2262                 hci_reenable_advertisements_if_needed();
2263             }
2264 #endif
2265 #endif
2266             break;
2267 
2268         case HCI_EVENT_HARDWARE_ERROR:
2269             log_error("Hardware Error: 0x%02x", packet[2]);
2270             if (hci_stack->hardware_error_callback){
2271                 (*hci_stack->hardware_error_callback)(packet[2]);
2272             } else {
2273                 // if no special requests, just reboot stack
2274                 hci_power_control_off();
2275                 hci_power_control_on();
2276             }
2277             break;
2278 
2279 #ifdef ENABLE_CLASSIC
2280         case HCI_EVENT_ROLE_CHANGE:
2281             if (packet[2]) break;   // status != 0
2282             reverse_bd_addr(&packet[3], addr);
2283             addr_type = BD_ADDR_TYPE_CLASSIC;
2284             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2285             if (!conn) break;
2286             conn->role = packet[9];
2287             break;
2288 #endif
2289 
2290         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2291             // release packet buffer only for asynchronous transport and if there are not further fragements
2292             if (hci_transport_synchronous()) {
2293                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2294                 return; // instead of break: to avoid re-entering hci_run()
2295             }
2296             if (hci_stack->acl_fragmentation_total_size) break;
2297             hci_release_packet_buffer();
2298 
2299             // L2CAP receives this event via the hci_emit_event below
2300 
2301 #ifdef ENABLE_CLASSIC
2302             // For SCO, we do the can_send_now_check here
2303             hci_notify_if_sco_can_send_now();
2304 #endif
2305             break;
2306 
2307 #ifdef ENABLE_CLASSIC
2308         case HCI_EVENT_SCO_CAN_SEND_NOW:
2309             // For SCO, we do the can_send_now_check here
2310             hci_notify_if_sco_can_send_now();
2311             return;
2312 
2313         // explode inquriy results for easier consumption
2314         case HCI_EVENT_INQUIRY_RESULT:
2315         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
2316         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
2317             gap_inquiry_explode(packet);
2318             break;
2319 #endif
2320 
2321 #ifdef ENABLE_BLE
2322         case HCI_EVENT_LE_META:
2323             switch (packet[2]){
2324 #ifdef ENABLE_LE_CENTRAL
2325                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
2326                     // log_info("advertising report received");
2327                     if (!hci_stack->le_scanning_enabled) break;
2328                     le_handle_advertisement_report(packet, size);
2329                     break;
2330 #endif
2331                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
2332                     // Connection management
2333                     reverse_bd_addr(&packet[8], addr);
2334                     addr_type = (bd_addr_type_t)packet[7];
2335                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2336                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2337 
2338 #ifdef ENABLE_LE_CENTRAL
2339                     // if auto-connect, remove from whitelist in both roles
2340                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
2341                         hci_remove_from_whitelist(addr_type, addr);
2342                     }
2343                     // handle error: error is reported only to the initiator -> outgoing connection
2344                     if (packet[3]){
2345 
2346                         // handle cancelled outgoing connection
2347                         // "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2348                         //  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2349                         //  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2350                         if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2351                             conn = gap_get_outgoing_connection();
2352                         }
2353 
2354                         // outgoing connection establishment is done
2355                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2356                         // remove entry
2357                         if (conn){
2358                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2359                             btstack_memory_hci_connection_free( conn );
2360                         }
2361                         break;
2362                     }
2363 #endif
2364                     // on success, both hosts receive connection complete event
2365                     if (packet[6] == HCI_ROLE_MASTER){
2366 #ifdef ENABLE_LE_CENTRAL
2367                         // if we're master, it was an outgoing connection and we're done with it
2368                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2369 #endif
2370                     } else {
2371 #ifdef ENABLE_LE_PERIPHERAL
2372                         // if we're slave, it was an incoming connection, advertisements have stopped
2373                         hci_stack->le_advertisements_active = 0;
2374 #endif
2375                     }
2376                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2377                     if (!conn){
2378                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2379                     }
2380                     // no memory, sorry.
2381                     if (!conn){
2382                         break;
2383                     }
2384 
2385                     conn->state = OPEN;
2386                     conn->role  = packet[6];
2387                     conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
2388                     conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
2389 
2390 #ifdef ENABLE_LE_PERIPHERAL
2391                     if (packet[6] == HCI_ROLE_SLAVE){
2392                         hci_reenable_advertisements_if_needed();
2393                     }
2394 #endif
2395 
2396                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2397 
2398                     // restart timer
2399                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2400                     // btstack_run_loop_add_timer(&conn->timeout);
2401 
2402                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2403 
2404                     hci_emit_nr_connections_changed();
2405                     break;
2406 
2407                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2408                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
2409                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
2410                     conn = hci_connection_for_handle(handle);
2411                     if (!conn) break;
2412                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
2413                     break;
2414 
2415                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
2416                     // connection
2417                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
2418                     conn = hci_connection_for_handle(handle);
2419                     if (conn) {
2420                         // read arguments
2421                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
2422                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
2423                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
2424                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
2425 
2426                         // validate against current connection parameter range
2427                         le_connection_parameter_range_t existing_range;
2428                         gap_get_connection_parameter_range(&existing_range);
2429                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
2430                         if (update_parameter){
2431                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
2432                             conn->le_conn_interval_min = le_conn_interval_min;
2433                             conn->le_conn_interval_max = le_conn_interval_max;
2434                             conn->le_conn_latency = le_conn_latency;
2435                             conn->le_supervision_timeout = le_supervision_timeout;
2436                         } else {
2437                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2438                         }
2439                     }
2440                     break;
2441                 default:
2442                     break;
2443             }
2444             break;
2445 #endif
2446         case HCI_EVENT_VENDOR_SPECIFIC:
2447             // Vendor specific commands often create vendor specific event instead of num completed packets
2448             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
2449             switch (hci_stack->manufacturer){
2450                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
2451                     hci_stack->num_cmd_packets = 1;
2452                     break;
2453                 default:
2454                     break;
2455             }
2456             break;
2457         default:
2458             break;
2459     }
2460 
2461     // handle BT initialization
2462     if (hci_stack->state == HCI_STATE_INITIALIZING){
2463         hci_initializing_event_handler(packet, size);
2464     }
2465 
2466     // help with BT sleep
2467     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2468         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2469         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2470         hci_initializing_next_state();
2471     }
2472 
2473     // notify upper stack
2474 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2475 
2476     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2477     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2478         if (!packet[2]){
2479             handle = little_endian_read_16(packet, 3);
2480             hci_connection_t * aConn = hci_connection_for_handle(handle);
2481             if (aConn) {
2482                 uint8_t status = aConn->bonding_status;
2483                 uint16_t flags = aConn->bonding_flags;
2484                 bd_addr_t bd_address;
2485                 memcpy(&bd_address, aConn->address, 6);
2486                 hci_shutdown_connection(aConn);
2487                 // connection struct is gone, don't access anymore
2488                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2489                     hci_emit_dedicated_bonding_result(bd_address, status);
2490                 }
2491             }
2492         }
2493     }
2494 
2495 	// execute main loop
2496 	hci_run();
2497 }
2498 
2499 #ifdef ENABLE_CLASSIC
2500 static void sco_handler(uint8_t * packet, uint16_t size){
2501     if (!hci_stack->sco_packet_handler) return;
2502     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2503 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2504     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2505     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
2506     if (conn){
2507         conn->num_packets_completed++;
2508         hci_stack->host_completed_packets = 1;
2509         hci_run();
2510     }
2511 #endif
2512 }
2513 #endif
2514 
2515 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2516     hci_dump_packet(packet_type, 1, packet, size);
2517     switch (packet_type) {
2518         case HCI_EVENT_PACKET:
2519             event_handler(packet, size);
2520             break;
2521         case HCI_ACL_DATA_PACKET:
2522             acl_handler(packet, size);
2523             break;
2524 #ifdef ENABLE_CLASSIC
2525         case HCI_SCO_DATA_PACKET:
2526             sco_handler(packet, size);
2527             break;
2528 #endif
2529         default:
2530             break;
2531     }
2532 }
2533 
2534 /**
2535  * @brief Add event packet handler.
2536  */
2537 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2538     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2539 }
2540 
2541 
2542 /** Register HCI packet handlers */
2543 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2544     hci_stack->acl_packet_handler = handler;
2545 }
2546 
2547 #ifdef ENABLE_CLASSIC
2548 /**
2549  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2550  */
2551 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2552     hci_stack->sco_packet_handler = handler;
2553 }
2554 #endif
2555 
2556 static void hci_state_reset(void){
2557     // no connections yet
2558     hci_stack->connections = NULL;
2559 
2560     // keep discoverable/connectable as this has been requested by the client(s)
2561     // hci_stack->discoverable = 0;
2562     // hci_stack->connectable = 0;
2563     // hci_stack->bondable = 1;
2564     // hci_stack->own_addr_type = 0;
2565 
2566     // buffer is free
2567     hci_stack->hci_packet_buffer_reserved = 0;
2568 
2569     // no pending cmds
2570     hci_stack->decline_reason = 0;
2571     hci_stack->new_scan_enable_value = 0xff;
2572 
2573     // LE
2574 #ifdef ENABLE_BLE
2575     memset(hci_stack->le_random_address, 0, 6);
2576     hci_stack->le_random_address_set = 0;
2577 #endif
2578 #ifdef ENABLE_LE_CENTRAL
2579     hci_stack->le_scanning_active  = 0;
2580     hci_stack->le_scan_type = 0xff;
2581     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2582     hci_stack->le_whitelist = 0;
2583     hci_stack->le_whitelist_capacity = 0;
2584 #endif
2585 }
2586 
2587 #ifdef ENABLE_CLASSIC
2588 /**
2589  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2590  */
2591 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2592     // store and open remote device db
2593     hci_stack->link_key_db = link_key_db;
2594     if (hci_stack->link_key_db) {
2595         hci_stack->link_key_db->open();
2596     }
2597 }
2598 #endif
2599 
2600 void hci_init(const hci_transport_t *transport, const void *config){
2601 
2602 #ifdef HAVE_MALLOC
2603     if (!hci_stack) {
2604         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2605     }
2606 #else
2607     hci_stack = &hci_stack_static;
2608 #endif
2609     memset(hci_stack, 0, sizeof(hci_stack_t));
2610 
2611     // reference to use transport layer implementation
2612     hci_stack->hci_transport = transport;
2613 
2614     // reference to used config
2615     hci_stack->config = config;
2616 
2617     // setup pointer for outgoing packet buffer
2618     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2619 
2620     // max acl payload size defined in config.h
2621     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2622 
2623     // register packet handlers with transport
2624     transport->register_packet_handler(&packet_handler);
2625 
2626     hci_stack->state = HCI_STATE_OFF;
2627 
2628     // class of device
2629     hci_stack->class_of_device = 0x007a020c; // Smartphone
2630 
2631     // bondable by default
2632     hci_stack->bondable = 1;
2633 
2634 #ifdef ENABLE_CLASSIC
2635     // classic name
2636     hci_stack->local_name = default_classic_name;
2637 
2638     // Master slave policy
2639     hci_stack->master_slave_policy = 1;
2640 #endif
2641 
2642     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2643     hci_stack->ssp_enable = 1;
2644     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2645     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2646     hci_stack->ssp_auto_accept = 1;
2647 
2648     // voice setting - signed 16 bit pcm data with CVSD over the air
2649     hci_stack->sco_voice_setting = 0x60;
2650 
2651 #ifdef ENABLE_LE_CENTRAL
2652     // connection parameter to use for outgoing connections
2653     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
2654     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
2655     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
2656     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
2657     hci_stack->le_connection_latency      = 4;         // 4
2658     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
2659     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
2660     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
2661 #endif
2662 
2663 #ifdef ENABLE_LE_PERIPHERAL
2664     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
2665 #endif
2666 
2667     // connection parameter range used to answer connection parameter update requests in l2cap
2668     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2669     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2670     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2671     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2672     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2673     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2674 
2675     hci_state_reset();
2676 }
2677 
2678 /**
2679  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2680  */
2681 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2682     hci_stack->chipset = chipset_driver;
2683 
2684     // reset chipset driver - init is also called on power_up
2685     if (hci_stack->chipset && hci_stack->chipset->init){
2686         hci_stack->chipset->init(hci_stack->config);
2687     }
2688 }
2689 
2690 /**
2691  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2692  */
2693 void hci_set_control(const btstack_control_t *hardware_control){
2694     // references to used control implementation
2695     hci_stack->control = hardware_control;
2696     // init with transport config
2697     hardware_control->init(hci_stack->config);
2698 }
2699 
2700 void hci_close(void){
2701     // close remote device db
2702     if (hci_stack->link_key_db) {
2703         hci_stack->link_key_db->close();
2704     }
2705 
2706     btstack_linked_list_iterator_t lit;
2707     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2708     while (btstack_linked_list_iterator_has_next(&lit)){
2709         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2710         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2711         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2712         hci_shutdown_connection(connection);
2713     }
2714 
2715     hci_power_control(HCI_POWER_OFF);
2716 
2717 #ifdef HAVE_MALLOC
2718     free(hci_stack);
2719 #endif
2720     hci_stack = NULL;
2721 }
2722 
2723 #ifdef ENABLE_CLASSIC
2724 void gap_set_class_of_device(uint32_t class_of_device){
2725     hci_stack->class_of_device = class_of_device;
2726 }
2727 
2728 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
2729     hci_stack->default_link_policy_settings = default_link_policy_settings;
2730 }
2731 
2732 void hci_disable_l2cap_timeout_check(void){
2733     disable_l2cap_timeouts = 1;
2734 }
2735 #endif
2736 
2737 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2738 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2739 void hci_set_bd_addr(bd_addr_t addr){
2740     memcpy(hci_stack->custom_bd_addr, addr, 6);
2741     hci_stack->custom_bd_addr_set = 1;
2742 }
2743 #endif
2744 
2745 // State-Module-Driver overview
2746 // state                    module  low-level
2747 // HCI_STATE_OFF             off      close
2748 // HCI_STATE_INITIALIZING,   on       open
2749 // HCI_STATE_WORKING,        on       open
2750 // HCI_STATE_HALTING,        on       open
2751 // HCI_STATE_SLEEPING,    off/sleep   close
2752 // HCI_STATE_FALLING_ASLEEP  on       open
2753 
2754 static int hci_power_control_on(void){
2755 
2756     // power on
2757     int err = 0;
2758     if (hci_stack->control && hci_stack->control->on){
2759         err = (*hci_stack->control->on)();
2760     }
2761     if (err){
2762         log_error( "POWER_ON failed");
2763         hci_emit_hci_open_failed();
2764         return err;
2765     }
2766 
2767     // int chipset driver
2768     if (hci_stack->chipset && hci_stack->chipset->init){
2769         hci_stack->chipset->init(hci_stack->config);
2770     }
2771 
2772     // init transport
2773     if (hci_stack->hci_transport->init){
2774         hci_stack->hci_transport->init(hci_stack->config);
2775     }
2776 
2777     // open transport
2778     err = hci_stack->hci_transport->open();
2779     if (err){
2780         log_error( "HCI_INIT failed, turning Bluetooth off again");
2781         if (hci_stack->control && hci_stack->control->off){
2782             (*hci_stack->control->off)();
2783         }
2784         hci_emit_hci_open_failed();
2785         return err;
2786     }
2787     return 0;
2788 }
2789 
2790 static void hci_power_control_off(void){
2791 
2792     log_info("hci_power_control_off");
2793 
2794     // close low-level device
2795     hci_stack->hci_transport->close();
2796 
2797     log_info("hci_power_control_off - hci_transport closed");
2798 
2799     // power off
2800     if (hci_stack->control && hci_stack->control->off){
2801         (*hci_stack->control->off)();
2802     }
2803 
2804     log_info("hci_power_control_off - control closed");
2805 
2806     hci_stack->state = HCI_STATE_OFF;
2807 }
2808 
2809 static void hci_power_control_sleep(void){
2810 
2811     log_info("hci_power_control_sleep");
2812 
2813 #if 0
2814     // don't close serial port during sleep
2815 
2816     // close low-level device
2817     hci_stack->hci_transport->close(hci_stack->config);
2818 #endif
2819 
2820     // sleep mode
2821     if (hci_stack->control && hci_stack->control->sleep){
2822         (*hci_stack->control->sleep)();
2823     }
2824 
2825     hci_stack->state = HCI_STATE_SLEEPING;
2826 }
2827 
2828 static int hci_power_control_wake(void){
2829 
2830     log_info("hci_power_control_wake");
2831 
2832     // wake on
2833     if (hci_stack->control && hci_stack->control->wake){
2834         (*hci_stack->control->wake)();
2835     }
2836 
2837 #if 0
2838     // open low-level device
2839     int err = hci_stack->hci_transport->open(hci_stack->config);
2840     if (err){
2841         log_error( "HCI_INIT failed, turning Bluetooth off again");
2842         if (hci_stack->control && hci_stack->control->off){
2843             (*hci_stack->control->off)();
2844         }
2845         hci_emit_hci_open_failed();
2846         return err;
2847     }
2848 #endif
2849 
2850     return 0;
2851 }
2852 
2853 static void hci_power_transition_to_initializing(void){
2854     // set up state machine
2855     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2856     hci_stack->hci_packet_buffer_reserved = 0;
2857     hci_stack->state = HCI_STATE_INITIALIZING;
2858     hci_stack->substate = HCI_INIT_SEND_RESET;
2859 }
2860 
2861 int hci_power_control(HCI_POWER_MODE power_mode){
2862 
2863     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2864 
2865     int err = 0;
2866     switch (hci_stack->state){
2867 
2868         case HCI_STATE_OFF:
2869             switch (power_mode){
2870                 case HCI_POWER_ON:
2871                     err = hci_power_control_on();
2872                     if (err) {
2873                         log_error("hci_power_control_on() error %d", err);
2874                         return err;
2875                     }
2876                     hci_power_transition_to_initializing();
2877                     break;
2878                 case HCI_POWER_OFF:
2879                     // do nothing
2880                     break;
2881                 case HCI_POWER_SLEEP:
2882                     // do nothing (with SLEEP == OFF)
2883                     break;
2884             }
2885             break;
2886 
2887         case HCI_STATE_INITIALIZING:
2888             switch (power_mode){
2889                 case HCI_POWER_ON:
2890                     // do nothing
2891                     break;
2892                 case HCI_POWER_OFF:
2893                     // no connections yet, just turn it off
2894                     hci_power_control_off();
2895                     break;
2896                 case HCI_POWER_SLEEP:
2897                     // no connections yet, just turn it off
2898                     hci_power_control_sleep();
2899                     break;
2900             }
2901             break;
2902 
2903         case HCI_STATE_WORKING:
2904             switch (power_mode){
2905                 case HCI_POWER_ON:
2906                     // do nothing
2907                     break;
2908                 case HCI_POWER_OFF:
2909                     // see hci_run
2910                     hci_stack->state = HCI_STATE_HALTING;
2911                     break;
2912                 case HCI_POWER_SLEEP:
2913                     // see hci_run
2914                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2915                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2916                     break;
2917             }
2918             break;
2919 
2920         case HCI_STATE_HALTING:
2921             switch (power_mode){
2922                 case HCI_POWER_ON:
2923                     hci_power_transition_to_initializing();
2924                     break;
2925                 case HCI_POWER_OFF:
2926                     // do nothing
2927                     break;
2928                 case HCI_POWER_SLEEP:
2929                     // see hci_run
2930                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2931                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2932                     break;
2933             }
2934             break;
2935 
2936         case HCI_STATE_FALLING_ASLEEP:
2937             switch (power_mode){
2938                 case HCI_POWER_ON:
2939 
2940 #ifdef HAVE_PLATFORM_IPHONE_OS
2941                     // nothing to do, if H4 supports power management
2942                     if (btstack_control_iphone_power_management_enabled()){
2943                         hci_stack->state = HCI_STATE_INITIALIZING;
2944                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2945                         break;
2946                     }
2947 #endif
2948                     hci_power_transition_to_initializing();
2949                     break;
2950                 case HCI_POWER_OFF:
2951                     // see hci_run
2952                     hci_stack->state = HCI_STATE_HALTING;
2953                     break;
2954                 case HCI_POWER_SLEEP:
2955                     // do nothing
2956                     break;
2957             }
2958             break;
2959 
2960         case HCI_STATE_SLEEPING:
2961             switch (power_mode){
2962                 case HCI_POWER_ON:
2963 
2964 #ifdef HAVE_PLATFORM_IPHONE_OS
2965                     // nothing to do, if H4 supports power management
2966                     if (btstack_control_iphone_power_management_enabled()){
2967                         hci_stack->state = HCI_STATE_INITIALIZING;
2968                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2969                         hci_update_scan_enable();
2970                         break;
2971                     }
2972 #endif
2973                     err = hci_power_control_wake();
2974                     if (err) return err;
2975                     hci_power_transition_to_initializing();
2976                     break;
2977                 case HCI_POWER_OFF:
2978                     hci_stack->state = HCI_STATE_HALTING;
2979                     break;
2980                 case HCI_POWER_SLEEP:
2981                     // do nothing
2982                     break;
2983             }
2984             break;
2985     }
2986 
2987     // create internal event
2988 	hci_emit_state();
2989 
2990 	// trigger next/first action
2991 	hci_run();
2992 
2993     return 0;
2994 }
2995 
2996 
2997 #ifdef ENABLE_CLASSIC
2998 
2999 static void hci_update_scan_enable(void){
3000     // 2 = page scan, 1 = inq scan
3001     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
3002     hci_run();
3003 }
3004 
3005 void gap_discoverable_control(uint8_t enable){
3006     if (enable) enable = 1; // normalize argument
3007 
3008     if (hci_stack->discoverable == enable){
3009         hci_emit_discoverable_enabled(hci_stack->discoverable);
3010         return;
3011     }
3012 
3013     hci_stack->discoverable = enable;
3014     hci_update_scan_enable();
3015 }
3016 
3017 void gap_connectable_control(uint8_t enable){
3018     if (enable) enable = 1; // normalize argument
3019 
3020     // don't emit event
3021     if (hci_stack->connectable == enable) return;
3022 
3023     hci_stack->connectable = enable;
3024     hci_update_scan_enable();
3025 }
3026 #endif
3027 
3028 void gap_local_bd_addr(bd_addr_t address_buffer){
3029     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
3030 }
3031 
3032 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3033 static void hci_host_num_completed_packets(void){
3034 
3035     // create packet manually as arrays are not supported and num_commands should not get reduced
3036     hci_reserve_packet_buffer();
3037     uint8_t * packet = hci_get_outgoing_packet_buffer();
3038 
3039     uint16_t size = 0;
3040     uint16_t num_handles = 0;
3041     packet[size++] = 0x35;
3042     packet[size++] = 0x0c;
3043     size++;  // skip param len
3044     size++;  // skip num handles
3045 
3046     // add { handle, packets } entries
3047     btstack_linked_item_t * it;
3048     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3049         hci_connection_t * connection = (hci_connection_t *) it;
3050         if (connection->num_packets_completed){
3051             little_endian_store_16(packet, size, connection->con_handle);
3052             size += 2;
3053             little_endian_store_16(packet, size, connection->num_packets_completed);
3054             size += 2;
3055             //
3056             num_handles++;
3057             connection->num_packets_completed = 0;
3058         }
3059     }
3060 
3061     packet[2] = size - 3;
3062     packet[3] = num_handles;
3063 
3064     hci_stack->host_completed_packets = 0;
3065 
3066     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3067     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3068 
3069     // release packet buffer for synchronous transport implementations
3070     if (hci_transport_synchronous()){
3071         hci_release_packet_buffer();
3072         hci_emit_transport_packet_sent();
3073     }
3074 }
3075 #endif
3076 
3077 static void hci_run(void){
3078 
3079     // log_info("hci_run: entered");
3080     btstack_linked_item_t * it;
3081 
3082     // send continuation fragments first, as they block the prepared packet buffer
3083     if (hci_stack->acl_fragmentation_total_size > 0) {
3084         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
3085         hci_connection_t *connection = hci_connection_for_handle(con_handle);
3086         if (connection) {
3087             if (hci_can_send_prepared_acl_packet_now(con_handle)){
3088                 hci_send_acl_packet_fragments(connection);
3089                 return;
3090             }
3091         } else {
3092             // connection gone -> discard further fragments
3093             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
3094             hci_stack->acl_fragmentation_total_size = 0;
3095             hci_stack->acl_fragmentation_pos = 0;
3096         }
3097     }
3098 
3099 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3100     // send host num completed packets next as they don't require num_cmd_packets > 0
3101     if (!hci_can_send_comand_packet_transport()) return;
3102     if (hci_stack->host_completed_packets){
3103         hci_host_num_completed_packets();
3104         return;
3105     }
3106 #endif
3107 
3108     if (!hci_can_send_command_packet_now()) return;
3109 
3110     // global/non-connection oriented commands
3111 
3112 #ifdef ENABLE_CLASSIC
3113     // decline incoming connections
3114     if (hci_stack->decline_reason){
3115         uint8_t reason = hci_stack->decline_reason;
3116         hci_stack->decline_reason = 0;
3117         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
3118         return;
3119     }
3120     // send scan enable
3121     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
3122         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
3123         hci_stack->new_scan_enable_value = 0xff;
3124         return;
3125     }
3126     // start/stop inquiry
3127     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX){
3128         uint8_t duration = hci_stack->inquiry_state;
3129         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3130         hci_send_cmd(&hci_inquiry, GAP_IAC_GENERAL_INQUIRY, duration, 0);
3131         return;
3132     }
3133     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
3134         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
3135         hci_send_cmd(&hci_inquiry_cancel);
3136         return;
3137     }
3138     // remote name request
3139     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
3140         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
3141         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
3142             hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
3143         return;
3144     }
3145     // pairing
3146     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
3147         uint8_t state = hci_stack->gap_pairing_state;
3148         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
3149         switch (state){
3150             case GAP_PAIRING_STATE_SEND_PIN:
3151                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, strlen(hci_stack->gap_pairing_input.gap_pairing_pin), hci_stack->gap_pairing_input.gap_pairing_pin);
3152                 break;
3153             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
3154                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
3155                 break;
3156             case GAP_PAIRING_STATE_SEND_PASSKEY:
3157                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
3158                 break;
3159             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
3160                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
3161                 break;
3162             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
3163                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
3164                 break;
3165             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
3166                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
3167                 break;
3168             default:
3169                 break;
3170         }
3171         return;
3172     }
3173 #endif
3174 
3175 #ifdef ENABLE_BLE
3176     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
3177     if ((hci_stack->state == HCI_STATE_WORKING)
3178     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
3179 
3180 #ifdef ENABLE_LE_CENTRAL
3181         // handle le scan
3182         if ((hci_stack->le_scanning_enabled != hci_stack->le_scanning_active)){
3183             hci_stack->le_scanning_active = hci_stack->le_scanning_enabled;
3184             hci_send_cmd(&hci_le_set_scan_enable, hci_stack->le_scanning_enabled, 0);
3185             return;
3186         }
3187         if (hci_stack->le_scan_type != 0xff){
3188             // defaults: active scanning, accept all advertisement packets
3189             int scan_type = hci_stack->le_scan_type;
3190             hci_stack->le_scan_type = 0xff;
3191             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);
3192             return;
3193         }
3194 #endif
3195 #ifdef ENABLE_LE_PERIPHERAL
3196         // le advertisement control
3197         if (hci_stack->le_advertisements_todo){
3198             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
3199         }
3200         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
3201             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
3202             hci_send_cmd(&hci_le_set_advertise_enable, 0);
3203             return;
3204         }
3205         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
3206             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3207             hci_send_cmd(&hci_le_set_advertising_parameters,
3208                  hci_stack->le_advertisements_interval_min,
3209                  hci_stack->le_advertisements_interval_max,
3210                  hci_stack->le_advertisements_type,
3211                  hci_stack->le_own_addr_type,
3212                  hci_stack->le_advertisements_direct_address_type,
3213                  hci_stack->le_advertisements_direct_address,
3214                  hci_stack->le_advertisements_channel_map,
3215                  hci_stack->le_advertisements_filter_policy);
3216             return;
3217         }
3218         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3219             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3220             uint8_t adv_data_clean[31];
3221             memset(adv_data_clean, 0, sizeof(adv_data_clean));
3222             memcpy(adv_data_clean, hci_stack->le_advertisements_data, hci_stack->le_advertisements_data_len);
3223             hci_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len);
3224             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3225             return;
3226         }
3227         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3228             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3229             uint8_t scan_data_clean[31];
3230             memset(scan_data_clean, 0, sizeof(scan_data_clean));
3231             memcpy(scan_data_clean, hci_stack->le_scan_response_data, hci_stack->le_scan_response_data_len);
3232             hci_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len);
3233             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, hci_stack->le_scan_response_data);
3234             return;
3235         }
3236         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
3237             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
3238             hci_send_cmd(&hci_le_set_advertise_enable, 1);
3239             return;
3240         }
3241 #endif
3242 
3243 #ifdef ENABLE_LE_CENTRAL
3244         //
3245         // LE Whitelist Management
3246         //
3247 
3248         // check if whitelist needs modification
3249         btstack_linked_list_iterator_t lit;
3250         int modification_pending = 0;
3251         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3252         while (btstack_linked_list_iterator_has_next(&lit)){
3253             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3254             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3255                 modification_pending = 1;
3256                 break;
3257             }
3258         }
3259 
3260         if (modification_pending){
3261             // stop connnecting if modification pending
3262             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
3263                 hci_send_cmd(&hci_le_create_connection_cancel);
3264                 return;
3265             }
3266 
3267             // add/remove entries
3268             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3269             while (btstack_linked_list_iterator_has_next(&lit)){
3270                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3271                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
3272                     entry->state = LE_WHITELIST_ON_CONTROLLER;
3273                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3274                     return;
3275 
3276                 }
3277                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
3278                     bd_addr_t address;
3279                     bd_addr_type_t address_type = entry->address_type;
3280                     memcpy(address, entry->address, 6);
3281                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3282                     btstack_memory_whitelist_entry_free(entry);
3283                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
3284                     return;
3285                 }
3286             }
3287         }
3288 
3289         // start connecting
3290         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
3291             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
3292             bd_addr_t null_addr;
3293             memset(null_addr, 0, 6);
3294             hci_send_cmd(&hci_le_create_connection,
3295                 hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
3296                 hci_stack->le_connection_scan_window,    // scan interval: 30 ms
3297                  1,         // use whitelist
3298                  0,         // peer address type
3299                  null_addr, // peer bd addr
3300                  hci_stack->le_own_addr_type, // our addr type:
3301                  hci_stack->le_connection_interval_min,    // conn interval min
3302                  hci_stack->le_connection_interval_max,    // conn interval max
3303                  hci_stack->le_connection_latency,         // conn latency
3304                  hci_stack->le_supervision_timeout,        // conn latency
3305                  hci_stack->le_minimum_ce_length,          // min ce length
3306                  hci_stack->le_maximum_ce_length           // max ce length
3307                 );
3308             return;
3309         }
3310 #endif
3311     }
3312 #endif
3313 
3314     // send pending HCI commands
3315     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3316         hci_connection_t * connection = (hci_connection_t *) it;
3317 
3318         switch(connection->state){
3319             case SEND_CREATE_CONNECTION:
3320                 switch(connection->address_type){
3321 #ifdef ENABLE_CLASSIC
3322                     case BD_ADDR_TYPE_CLASSIC:
3323                         log_info("sending hci_create_connection");
3324                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
3325                         break;
3326 #endif
3327                     default:
3328 #ifdef ENABLE_BLE
3329 #ifdef ENABLE_LE_CENTRAL
3330                         // track outgoing connection
3331                         hci_stack->outgoing_addr_type = connection->address_type;
3332                         memcpy(hci_stack->outgoing_addr, connection->address, 6);
3333                         log_info("sending hci_le_create_connection");
3334                         hci_send_cmd(&hci_le_create_connection,
3335                              hci_stack->le_connection_scan_interval,    // conn scan interval
3336                              hci_stack->le_connection_scan_window,      // conn scan windows
3337                              0,         // don't use whitelist
3338                              connection->address_type, // peer address type
3339                              connection->address,      // peer bd addr
3340                              hci_stack->le_own_addr_type, // our addr type:
3341                              hci_stack->le_connection_interval_min,    // conn interval min
3342                              hci_stack->le_connection_interval_max,    // conn interval max
3343                              hci_stack->le_connection_latency,         // conn latency
3344                              hci_stack->le_supervision_timeout,        // conn latency
3345                              hci_stack->le_minimum_ce_length,          // min ce length
3346                              hci_stack->le_maximum_ce_length          // max ce length
3347                              );
3348                         connection->state = SENT_CREATE_CONNECTION;
3349 #endif
3350 #endif
3351                         break;
3352                 }
3353                 return;
3354 
3355 #ifdef ENABLE_CLASSIC
3356             case RECEIVED_CONNECTION_REQUEST:
3357                 connection->role  = HCI_ROLE_SLAVE;
3358                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
3359                     log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
3360                     connection->state = ACCEPTED_CONNECTION_REQUEST;
3361                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
3362                 }
3363                 return;
3364 #endif
3365 
3366 #ifdef ENABLE_BLE
3367 #ifdef ENABLE_LE_CENTRAL
3368             case SEND_CANCEL_CONNECTION:
3369                 connection->state = SENT_CANCEL_CONNECTION;
3370                 hci_send_cmd(&hci_le_create_connection_cancel);
3371                 return;
3372 #endif
3373 #endif
3374             case SEND_DISCONNECT:
3375                 connection->state = SENT_DISCONNECT;
3376                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
3377                 return;
3378 
3379             default:
3380                 break;
3381         }
3382 
3383         // no further commands if connection is about to get shut down
3384         if (connection->state == SENT_DISCONNECT) continue;
3385 
3386 #ifdef ENABLE_CLASSIC
3387         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
3388             log_info("responding to link key request");
3389             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
3390             link_key_t link_key;
3391             link_key_type_t link_key_type;
3392             if ( hci_stack->link_key_db
3393               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
3394               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
3395                connection->link_key_type = link_key_type;
3396                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
3397             } else {
3398                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
3399             }
3400             return;
3401         }
3402 
3403         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
3404             log_info("denying to pin request");
3405             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
3406             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
3407             return;
3408         }
3409 
3410         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
3411             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
3412             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
3413             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3414                 // tweak authentication requirements
3415                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3416                 if (connection->bonding_flags & BONDING_DEDICATED){
3417                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3418                 }
3419                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
3420                     authreq |= 1;
3421                 }
3422                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3423             } else {
3424                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3425             }
3426             return;
3427         }
3428 
3429         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3430             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
3431             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3432             return;
3433         }
3434 
3435         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3436             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
3437             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3438             return;
3439         }
3440 
3441         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
3442             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
3443             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3444             return;
3445         }
3446 
3447         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3448             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
3449             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
3450             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
3451             return;
3452         }
3453 
3454         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
3455             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3456             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3457             return;
3458         }
3459 
3460         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3461             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3462             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3463             return;
3464         }
3465 #endif
3466 
3467         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
3468             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
3469             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
3470             return;
3471         }
3472 
3473 #ifdef ENABLE_CLASSIC
3474         uint16_t sniff_min_interval;
3475         switch (connection->sniff_min_interval){
3476             case 0:
3477                 break;
3478             case 0xffff:
3479                 connection->sniff_min_interval = 0;
3480                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
3481                 return;
3482             default:
3483                 sniff_min_interval = connection->sniff_min_interval;
3484                 connection->sniff_min_interval = 0;
3485                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
3486                 break;
3487         }
3488 #endif
3489 
3490 #ifdef ENABLE_BLE
3491         switch (connection->le_con_parameter_update_state){
3492             // response to L2CAP CON PARAMETER UPDATE REQUEST
3493             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
3494                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3495                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
3496                     connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3497                     0x0000, 0xffff);
3498                 break;
3499             case CON_PARAMETER_UPDATE_REPLY:
3500                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3501                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
3502                     connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3503                     0x0000, 0xffff);
3504                 break;
3505             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
3506                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3507                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
3508                 break;
3509             default:
3510                 break;
3511         }
3512 #endif
3513     }
3514 
3515     hci_connection_t * connection;
3516     switch (hci_stack->state){
3517         case HCI_STATE_INITIALIZING:
3518             hci_initializing_run();
3519             break;
3520 
3521         case HCI_STATE_HALTING:
3522 
3523             log_info("HCI_STATE_HALTING");
3524 
3525             // free whitelist entries
3526 #ifdef ENABLE_BLE
3527 #ifdef ENABLE_LE_CENTRAL
3528             {
3529                 btstack_linked_list_iterator_t lit;
3530                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3531                 while (btstack_linked_list_iterator_has_next(&lit)){
3532                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3533                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3534                     btstack_memory_whitelist_entry_free(entry);
3535                 }
3536             }
3537 #endif
3538 #endif
3539             // close all open connections
3540             connection =  (hci_connection_t *) hci_stack->connections;
3541             if (connection){
3542                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
3543                 if (!hci_can_send_command_packet_now()) return;
3544 
3545                 // check state
3546                 if (connection->state == SENT_DISCONNECT) return;
3547                 connection->state = SENT_DISCONNECT;
3548 
3549                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
3550 
3551                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
3552                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
3553 
3554                 // ... which would be ignored anyway as we shutdown (free) the connection now
3555                 hci_shutdown_connection(connection);
3556 
3557                 // finally, send the disconnect command
3558                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
3559                 return;
3560             }
3561             log_info("HCI_STATE_HALTING, calling off");
3562 
3563             // switch mode
3564             hci_power_control_off();
3565 
3566             log_info("HCI_STATE_HALTING, emitting state");
3567             hci_emit_state();
3568             log_info("HCI_STATE_HALTING, done");
3569             break;
3570 
3571         case HCI_STATE_FALLING_ASLEEP:
3572             switch(hci_stack->substate) {
3573                 case HCI_FALLING_ASLEEP_DISCONNECT:
3574                     log_info("HCI_STATE_FALLING_ASLEEP");
3575                     // close all open connections
3576                     connection =  (hci_connection_t *) hci_stack->connections;
3577 
3578 #ifdef HAVE_PLATFORM_IPHONE_OS
3579                     // don't close connections, if H4 supports power management
3580                     if (btstack_control_iphone_power_management_enabled()){
3581                         connection = NULL;
3582                     }
3583 #endif
3584                     if (connection){
3585 
3586                         // send disconnect
3587                         if (!hci_can_send_command_packet_now()) return;
3588 
3589                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3590                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3591 
3592                         // send disconnected event right away - causes higher layer connections to get closed, too.
3593                         hci_shutdown_connection(connection);
3594                         return;
3595                     }
3596 
3597                     if (hci_classic_supported()){
3598                         // disable page and inquiry scan
3599                         if (!hci_can_send_command_packet_now()) return;
3600 
3601                         log_info("HCI_STATE_HALTING, disabling inq scans");
3602                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3603 
3604                         // continue in next sub state
3605                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3606                         break;
3607                     }
3608                     // no break - fall through for ble-only chips
3609 
3610                 case HCI_FALLING_ASLEEP_COMPLETE:
3611                     log_info("HCI_STATE_HALTING, calling sleep");
3612 #ifdef HAVE_PLATFORM_IPHONE_OS
3613                     // don't actually go to sleep, if H4 supports power management
3614                     if (btstack_control_iphone_power_management_enabled()){
3615                         // SLEEP MODE reached
3616                         hci_stack->state = HCI_STATE_SLEEPING;
3617                         hci_emit_state();
3618                         break;
3619                     }
3620 #endif
3621                     // switch mode
3622                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3623                     hci_emit_state();
3624                     break;
3625 
3626                 default:
3627                     break;
3628             }
3629             break;
3630 
3631         default:
3632             break;
3633     }
3634 }
3635 
3636 int hci_send_cmd_packet(uint8_t *packet, int size){
3637     // house-keeping
3638 
3639     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3640         hci_stack->loopback_mode = packet[3];
3641     }
3642 
3643 #ifdef ENABLE_CLASSIC
3644     bd_addr_t addr;
3645     hci_connection_t * conn;
3646 
3647     // create_connection?
3648     if (IS_COMMAND(packet, hci_create_connection)){
3649         reverse_bd_addr(&packet[3], addr);
3650         log_info("Create_connection to %s", bd_addr_to_str(addr));
3651 
3652         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3653         if (!conn){
3654             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3655             if (!conn){
3656                 // notify client that alloc failed
3657                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3658                 return -1; // packet not sent to controller
3659             }
3660             conn->state = SEND_CREATE_CONNECTION;
3661         }
3662         log_info("conn state %u", conn->state);
3663         switch (conn->state){
3664             // if connection active exists
3665             case OPEN:
3666                 // and OPEN, emit connection complete command
3667                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3668                 return -1; // packet not sent to controller
3669             case SEND_CREATE_CONNECTION:
3670                 // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
3671                 break;
3672             default:
3673                 // otherwise, just ignore as it is already in the open process
3674                 return -1; // packet not sent to controller
3675         }
3676         conn->state = SENT_CREATE_CONNECTION;
3677 
3678         // track outgoing connection
3679         hci_stack->outgoing_addr_type = BD_ADDR_TYPE_CLASSIC;
3680         memcpy(hci_stack->outgoing_addr, addr, 6);
3681     }
3682 
3683     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3684         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3685     }
3686     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3687         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3688     }
3689 
3690     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3691         if (hci_stack->link_key_db){
3692             reverse_bd_addr(&packet[3], addr);
3693             hci_stack->link_key_db->delete_link_key(addr);
3694         }
3695     }
3696 
3697     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3698     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3699         reverse_bd_addr(&packet[3], addr);
3700         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3701         if (conn){
3702             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3703         }
3704     }
3705 
3706     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3707     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3708     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3709     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3710         reverse_bd_addr(&packet[3], addr);
3711         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3712         if (conn){
3713             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3714         }
3715     }
3716 
3717 #ifdef ENABLE_SCO_OVER_HCI
3718     // setup_synchronous_connection? Voice setting at offset 22
3719     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3720         // TODO: compare to current setting if sco connection already active
3721         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3722     }
3723     // accept_synchronus_connection? Voice setting at offset 18
3724     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3725         // TODO: compare to current setting if sco connection already active
3726         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3727     }
3728 #endif
3729 #endif
3730 
3731 #ifdef ENABLE_BLE
3732 #ifdef ENABLE_LE_PERIPHERAL
3733     if (IS_COMMAND(packet, hci_le_set_random_address)){
3734         hci_stack->le_random_address_set = 1;
3735         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3736     }
3737     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3738         hci_stack->le_advertisements_active = packet[3];
3739     }
3740 #endif
3741 #ifdef ENABLE_LE_CENTRAL
3742     if (IS_COMMAND(packet, hci_le_create_connection)){
3743         // white list used?
3744         uint8_t initiator_filter_policy = packet[7];
3745         switch (initiator_filter_policy){
3746             case 0:
3747                 // whitelist not used
3748                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3749                 break;
3750             case 1:
3751                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3752                 break;
3753             default:
3754                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3755                 break;
3756         }
3757     }
3758     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3759         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3760     }
3761 #endif
3762 #endif
3763 
3764     hci_stack->num_cmd_packets--;
3765 
3766     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3767     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3768 }
3769 
3770 // disconnect because of security block
3771 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3772     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3773     if (!connection) return;
3774     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3775 }
3776 
3777 
3778 // Configure Secure Simple Pairing
3779 
3780 #ifdef ENABLE_CLASSIC
3781 
3782 // enable will enable SSP during init
3783 void gap_ssp_set_enable(int enable){
3784     hci_stack->ssp_enable = enable;
3785 }
3786 
3787 static int hci_local_ssp_activated(void){
3788     return gap_ssp_supported() && hci_stack->ssp_enable;
3789 }
3790 
3791 // if set, BTstack will respond to io capability request using authentication requirement
3792 void gap_ssp_set_io_capability(int io_capability){
3793     hci_stack->ssp_io_capability = io_capability;
3794 }
3795 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3796     hci_stack->ssp_authentication_requirement = authentication_requirement;
3797 }
3798 
3799 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3800 void gap_ssp_set_auto_accept(int auto_accept){
3801     hci_stack->ssp_auto_accept = auto_accept;
3802 }
3803 #endif
3804 
3805 // va_list part of hci_send_cmd
3806 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3807     if (!hci_can_send_command_packet_now()){
3808         log_error("hci_send_cmd called but cannot send packet now");
3809         return 0;
3810     }
3811 
3812     // for HCI INITIALIZATION
3813     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3814     hci_stack->last_cmd_opcode = cmd->opcode;
3815 
3816     hci_reserve_packet_buffer();
3817     uint8_t * packet = hci_stack->hci_packet_buffer;
3818     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3819     int err = hci_send_cmd_packet(packet, size);
3820 
3821     // release packet buffer for synchronous transport implementations
3822     if (hci_transport_synchronous()){
3823         hci_release_packet_buffer();
3824         hci_emit_transport_packet_sent();
3825     }
3826 
3827     return err;
3828 }
3829 
3830 /**
3831  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3832  */
3833 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3834     va_list argptr;
3835     va_start(argptr, cmd);
3836     int res = hci_send_cmd_va_arg(cmd, argptr);
3837     va_end(argptr);
3838     return res;
3839 }
3840 
3841 // Create various non-HCI events.
3842 // TODO: generalize, use table similar to hci_create_command
3843 
3844 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3845     // dump packet
3846     if (dump) {
3847         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3848     }
3849 
3850     // dispatch to all event handlers
3851     btstack_linked_list_iterator_t it;
3852     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3853     while (btstack_linked_list_iterator_has_next(&it)){
3854         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3855         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3856     }
3857 }
3858 
3859 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3860     if (!hci_stack->acl_packet_handler) return;
3861     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3862 }
3863 
3864 #ifdef ENABLE_CLASSIC
3865 static void hci_notify_if_sco_can_send_now(void){
3866     // notify SCO sender if waiting
3867     if (!hci_stack->sco_waiting_for_can_send_now) return;
3868     if (hci_can_send_sco_packet_now()){
3869         hci_stack->sco_waiting_for_can_send_now = 0;
3870         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3871         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3872         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3873     }
3874 }
3875 
3876 // parsing end emitting has been merged to reduce code size
3877 static void gap_inquiry_explode(uint8_t * packet){
3878     uint8_t event[19+GAP_INQUIRY_MAX_NAME_LEN];
3879 
3880     uint8_t * eir_data;
3881     ad_context_t context;
3882     const uint8_t * name;
3883     uint8_t         name_len;
3884 
3885     int event_type = hci_event_packet_get_type(packet);
3886     int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1;    // 2 for old event, 1 otherwise
3887     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
3888 
3889     // event[1] is set at the end
3890     int i;
3891     for (i=0; i<num_responses;i++){
3892         memset(event, 0, sizeof(event));
3893         event[0] = GAP_EVENT_INQUIRY_RESULT;
3894         uint8_t event_size = 18;    // if name is not set by EIR
3895 
3896         memcpy(&event[2],  &packet[3 +                                             i*6], 6); // bd_addr
3897         event[8] =          packet[3 + num_responses*(6)                         + i*1];     // page_scan_repetition_mode
3898         memcpy(&event[9],  &packet[3 + num_responses*(6+1+num_reserved_fields)   + i*3], 3); // class of device
3899         memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset
3900 
3901         switch (event_type){
3902             case HCI_EVENT_INQUIRY_RESULT:
3903                 // 14,15,16,17 = 0, size 18
3904                 break;
3905             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3906                 event[14] = 1;
3907                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3908                 // 16,17 = 0, size 18
3909                 break;
3910             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3911                 event[14] = 1;
3912                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3913                 // for EIR packets, there is only one reponse in it
3914                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
3915                 name = NULL;
3916                 // EIR data is 240 bytes in EIR event
3917                 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
3918                     uint8_t data_type    = ad_iterator_get_data_type(&context);
3919                     uint8_t data_size    = ad_iterator_get_data_len(&context);
3920                     const uint8_t * data = ad_iterator_get_data(&context);
3921                     // Prefer Complete Local Name over Shortend Local Name
3922                     switch (data_type){
3923                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
3924                             if (name) continue;
3925                             /* explicit fall-through */
3926                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
3927                             name = data;
3928                             name_len = data_size;
3929                             break;
3930                         default:
3931                             break;
3932                     }
3933                 }
3934                 if (name){
3935                     event[16] = 1;
3936                     // truncate name if needed
3937                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
3938                     event[17] = len;
3939                     memcpy(&event[18], name, len);
3940                     event_size += len;
3941                 }
3942                 break;
3943         }
3944         event[1] = event_size - 2;
3945         hci_emit_event(event, event_size, 1);
3946     }
3947 }
3948 #endif
3949 
3950 void hci_emit_state(void){
3951     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3952     uint8_t event[3];
3953     event[0] = BTSTACK_EVENT_STATE;
3954     event[1] = sizeof(event) - 2;
3955     event[2] = hci_stack->state;
3956     hci_emit_event(event, sizeof(event), 1);
3957 }
3958 
3959 #ifdef ENABLE_CLASSIC
3960 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3961     uint8_t event[13];
3962     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3963     event[1] = sizeof(event) - 2;
3964     event[2] = status;
3965     little_endian_store_16(event, 3, con_handle);
3966     reverse_bd_addr(address, &event[5]);
3967     event[11] = 1; // ACL connection
3968     event[12] = 0; // encryption disabled
3969     hci_emit_event(event, sizeof(event), 1);
3970 }
3971 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3972     if (disable_l2cap_timeouts) return;
3973     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3974     uint8_t event[4];
3975     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3976     event[1] = sizeof(event) - 2;
3977     little_endian_store_16(event, 2, conn->con_handle);
3978     hci_emit_event(event, sizeof(event), 1);
3979 }
3980 #endif
3981 
3982 #ifdef ENABLE_BLE
3983 #ifdef ENABLE_LE_CENTRAL
3984 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3985     uint8_t event[21];
3986     event[0] = HCI_EVENT_LE_META;
3987     event[1] = sizeof(event) - 2;
3988     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
3989     event[3] = status;
3990     little_endian_store_16(event, 4, con_handle);
3991     event[6] = 0; // TODO: role
3992     event[7] = address_type;
3993     reverse_bd_addr(address, &event[8]);
3994     little_endian_store_16(event, 14, 0); // interval
3995     little_endian_store_16(event, 16, 0); // latency
3996     little_endian_store_16(event, 18, 0); // supervision timeout
3997     event[20] = 0; // master clock accuracy
3998     hci_emit_event(event, sizeof(event), 1);
3999 }
4000 #endif
4001 #endif
4002 
4003 static void hci_emit_transport_packet_sent(void){
4004     // notify upper stack that it might be possible to send again
4005     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
4006     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
4007 }
4008 
4009 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
4010     uint8_t event[6];
4011     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
4012     event[1] = sizeof(event) - 2;
4013     event[2] = 0; // status = OK
4014     little_endian_store_16(event, 3, con_handle);
4015     event[5] = reason;
4016     hci_emit_event(event, sizeof(event), 1);
4017 }
4018 
4019 static void hci_emit_nr_connections_changed(void){
4020     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
4021     uint8_t event[3];
4022     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
4023     event[1] = sizeof(event) - 2;
4024     event[2] = nr_hci_connections();
4025     hci_emit_event(event, sizeof(event), 1);
4026 }
4027 
4028 static void hci_emit_hci_open_failed(void){
4029     log_info("BTSTACK_EVENT_POWERON_FAILED");
4030     uint8_t event[2];
4031     event[0] = BTSTACK_EVENT_POWERON_FAILED;
4032     event[1] = sizeof(event) - 2;
4033     hci_emit_event(event, sizeof(event), 1);
4034 }
4035 
4036 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
4037     log_info("hci_emit_dedicated_bonding_result %u ", status);
4038     uint8_t event[9];
4039     int pos = 0;
4040     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
4041     event[pos++] = sizeof(event) - 2;
4042     event[pos++] = status;
4043     reverse_bd_addr(address, &event[pos]);
4044     hci_emit_event(event, sizeof(event), 1);
4045 }
4046 
4047 
4048 #ifdef ENABLE_CLASSIC
4049 
4050 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
4051     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
4052     uint8_t event[5];
4053     int pos = 0;
4054     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
4055     event[pos++] = sizeof(event) - 2;
4056     little_endian_store_16(event, 2, con_handle);
4057     pos += 2;
4058     event[pos++] = level;
4059     hci_emit_event(event, sizeof(event), 1);
4060 }
4061 
4062 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
4063     if (!connection) return LEVEL_0;
4064     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
4065     return gap_security_level_for_link_key_type(connection->link_key_type);
4066 }
4067 
4068 static void hci_emit_discoverable_enabled(uint8_t enabled){
4069     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
4070     uint8_t event[3];
4071     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
4072     event[1] = sizeof(event) - 2;
4073     event[2] = enabled;
4074     hci_emit_event(event, sizeof(event), 1);
4075 }
4076 
4077 #ifdef ENABLE_CLASSIC
4078 // query if remote side supports eSCO
4079 int hci_remote_esco_supported(hci_con_handle_t con_handle){
4080     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4081     if (!connection) return 0;
4082     return connection->remote_supported_feature_eSCO;
4083 }
4084 
4085 // query if remote side supports SSP
4086 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
4087     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4088     if (!connection) return 0;
4089     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
4090 }
4091 
4092 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
4093     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
4094 }
4095 #endif
4096 
4097 // GAP API
4098 /**
4099  * @bbrief enable/disable bonding. default is enabled
4100  * @praram enabled
4101  */
4102 void gap_set_bondable_mode(int enable){
4103     hci_stack->bondable = enable ? 1 : 0;
4104 }
4105 /**
4106  * @brief Get bondable mode.
4107  * @return 1 if bondable
4108  */
4109 int gap_get_bondable_mode(void){
4110     return hci_stack->bondable;
4111 }
4112 
4113 /**
4114  * @brief map link keys to security levels
4115  */
4116 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
4117     switch (link_key_type){
4118         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
4119             return LEVEL_4;
4120         case COMBINATION_KEY:
4121         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
4122             return LEVEL_3;
4123         default:
4124             return LEVEL_2;
4125     }
4126 }
4127 
4128 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
4129     log_info("gap_mitm_protection_required_for_security_level %u", level);
4130     return level > LEVEL_2;
4131 }
4132 
4133 /**
4134  * @brief get current security level
4135  */
4136 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
4137     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4138     if (!connection) return LEVEL_0;
4139     return gap_security_level_for_connection(connection);
4140 }
4141 
4142 /**
4143  * @brief request connection to device to
4144  * @result GAP_AUTHENTICATION_RESULT
4145  */
4146 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
4147     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4148     if (!connection){
4149         hci_emit_security_level(con_handle, LEVEL_0);
4150         return;
4151     }
4152     gap_security_level_t current_level = gap_security_level(con_handle);
4153     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
4154         requested_level, connection->requested_security_level, current_level);
4155 
4156     // assumption: earlier requested security higher than current level => security request is active
4157     if (current_level < connection->requested_security_level){
4158         if (connection->requested_security_level < requested_level){
4159             // increase requested level as new level is higher
4160 
4161             // TODO: handle re-authentication when done
4162 
4163             connection->requested_security_level = requested_level;
4164         }
4165         return;
4166     }
4167 
4168     // no request active, notify if security sufficient
4169     if (requested_level <= current_level){
4170         hci_emit_security_level(con_handle, current_level);
4171         return;
4172     }
4173 
4174     // start pairing to increase security level
4175     connection->requested_security_level = requested_level;
4176 
4177 #if 0
4178     // sending encryption request without a link key results in an error.
4179     // TODO: figure out how to use it properly
4180 
4181     // would enabling ecnryption suffice (>= LEVEL_2)?
4182     if (hci_stack->link_key_db){
4183         link_key_type_t link_key_type;
4184         link_key_t      link_key;
4185         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
4186             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
4187                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4188                 return;
4189             }
4190         }
4191     }
4192 #endif
4193 
4194     // start to authenticate connection
4195     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
4196     hci_run();
4197 }
4198 
4199 /**
4200  * @brief start dedicated bonding with device. disconnect after bonding
4201  * @param device
4202  * @param request MITM protection
4203  * @result GAP_DEDICATED_BONDING_COMPLETE
4204  */
4205 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
4206 
4207     // create connection state machine
4208     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
4209 
4210     if (!connection){
4211         return BTSTACK_MEMORY_ALLOC_FAILED;
4212     }
4213 
4214     // delete linkn key
4215     gap_drop_link_key_for_bd_addr(device);
4216 
4217     // configure LEVEL_2/3, dedicated bonding
4218     connection->state = SEND_CREATE_CONNECTION;
4219     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
4220     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
4221     connection->bonding_flags = BONDING_DEDICATED;
4222 
4223     // wait for GAP Security Result and send GAP Dedicated Bonding complete
4224 
4225     // handle: connnection failure (connection complete != ok)
4226     // handle: authentication failure
4227     // handle: disconnect on done
4228 
4229     hci_run();
4230 
4231     return 0;
4232 }
4233 #endif
4234 
4235 void gap_set_local_name(const char * local_name){
4236     hci_stack->local_name = local_name;
4237 }
4238 
4239 
4240 #ifdef ENABLE_BLE
4241 
4242 #ifdef ENABLE_LE_CENTRAL
4243 void gap_start_scan(void){
4244     hci_stack->le_scanning_enabled = 1;
4245     hci_run();
4246 }
4247 
4248 void gap_stop_scan(void){
4249     hci_stack->le_scanning_enabled = 0;
4250     hci_run();
4251 }
4252 
4253 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
4254     hci_stack->le_scan_type     = scan_type;
4255     hci_stack->le_scan_interval = scan_interval;
4256     hci_stack->le_scan_window   = scan_window;
4257     hci_run();
4258 }
4259 
4260 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
4261     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4262     if (!conn){
4263         log_info("gap_connect: no connection exists yet, creating context");
4264         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
4265         if (!conn){
4266             // notify client that alloc failed
4267             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4268             log_info("gap_connect: failed to alloc hci_connection_t");
4269             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
4270         }
4271         conn->state = SEND_CREATE_CONNECTION;
4272         log_info("gap_connect: send create connection next");
4273         hci_run();
4274         return 0;
4275     }
4276 
4277     if (!hci_is_le_connection(conn) ||
4278         conn->state == SEND_CREATE_CONNECTION ||
4279         conn->state == SENT_CREATE_CONNECTION) {
4280         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
4281         log_error("gap_connect: classic connection or connect is already being created");
4282         return GATT_CLIENT_IN_WRONG_STATE;
4283     }
4284 
4285     log_info("gap_connect: context exists with state %u", conn->state);
4286     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
4287     hci_run();
4288     return 0;
4289 }
4290 
4291 // @assumption: only a single outgoing LE Connection exists
4292 static hci_connection_t * gap_get_outgoing_connection(void){
4293     btstack_linked_item_t *it;
4294     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4295         hci_connection_t * conn = (hci_connection_t *) it;
4296         if (!hci_is_le_connection(conn)) continue;
4297         switch (conn->state){
4298             case SEND_CREATE_CONNECTION:
4299             case SENT_CREATE_CONNECTION:
4300             case SENT_CANCEL_CONNECTION:
4301                 return conn;
4302             default:
4303                 break;
4304         };
4305     }
4306     return NULL;
4307 }
4308 
4309 uint8_t gap_connect_cancel(void){
4310     hci_connection_t * conn = gap_get_outgoing_connection();
4311     if (!conn) return 0;
4312     switch (conn->state){
4313         case SEND_CREATE_CONNECTION:
4314             // skip sending create connection and emit event instead
4315             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
4316             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
4317             btstack_memory_hci_connection_free( conn );
4318             break;
4319         case SENT_CREATE_CONNECTION:
4320             // request to send cancel connection
4321             conn->state = SEND_CANCEL_CONNECTION;
4322             hci_run();
4323             break;
4324         default:
4325             break;
4326     }
4327     return 0;
4328 }
4329 #endif
4330 
4331 #ifdef ENABLE_LE_CENTRAL
4332 /**
4333  * @brief Set connection parameters for outgoing connections
4334  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
4335  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
4336  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
4337  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
4338  * @param conn_latency, default: 4
4339  * @param supervision_timeout (unit: 10ms), default: 720 ms
4340  * @param min_ce_length (unit: 0.625ms), default: 10 ms
4341  * @param max_ce_length (unit: 0.625ms), default: 30 ms
4342  */
4343 
4344 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
4345     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
4346     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
4347     hci_stack->le_connection_scan_interval = conn_scan_interval;
4348     hci_stack->le_connection_scan_window = conn_scan_window;
4349     hci_stack->le_connection_interval_min = conn_interval_min;
4350     hci_stack->le_connection_interval_max = conn_interval_max;
4351     hci_stack->le_connection_latency = conn_latency;
4352     hci_stack->le_supervision_timeout = supervision_timeout;
4353     hci_stack->le_minimum_ce_length = min_ce_length;
4354     hci_stack->le_maximum_ce_length = max_ce_length;
4355 }
4356 #endif
4357 
4358 /**
4359  * @brief Updates the connection parameters for a given LE connection
4360  * @param handle
4361  * @param conn_interval_min (unit: 1.25ms)
4362  * @param conn_interval_max (unit: 1.25ms)
4363  * @param conn_latency
4364  * @param supervision_timeout (unit: 10ms)
4365  * @returns 0 if ok
4366  */
4367 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4368     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4369     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4370     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4371     connection->le_conn_interval_min = conn_interval_min;
4372     connection->le_conn_interval_max = conn_interval_max;
4373     connection->le_conn_latency = conn_latency;
4374     connection->le_supervision_timeout = supervision_timeout;
4375     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
4376     hci_run();
4377     return 0;
4378 }
4379 
4380 /**
4381  * @brief Request an update of the connection parameter for a given LE connection
4382  * @param handle
4383  * @param conn_interval_min (unit: 1.25ms)
4384  * @param conn_interval_max (unit: 1.25ms)
4385  * @param conn_latency
4386  * @param supervision_timeout (unit: 10ms)
4387  * @returns 0 if ok
4388  */
4389 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4390     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4391     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4392     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4393     connection->le_conn_interval_min = conn_interval_min;
4394     connection->le_conn_interval_max = conn_interval_max;
4395     connection->le_conn_latency = conn_latency;
4396     connection->le_supervision_timeout = supervision_timeout;
4397     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
4398     hci_run();
4399     return 0;
4400 }
4401 
4402 #ifdef ENABLE_LE_PERIPHERAL
4403 
4404 static void gap_advertisments_changed(void){
4405     // disable advertisements before updating adv, scan data, or adv params
4406     if (hci_stack->le_advertisements_active){
4407         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
4408     }
4409     hci_run();
4410 }
4411 
4412 /**
4413  * @brief Set Advertisement Data
4414  * @param advertising_data_length
4415  * @param advertising_data (max 31 octets)
4416  * @note data is not copied, pointer has to stay valid
4417  */
4418 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
4419     hci_stack->le_advertisements_data_len = advertising_data_length;
4420     hci_stack->le_advertisements_data = advertising_data;
4421     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4422     gap_advertisments_changed();
4423 }
4424 
4425 /**
4426  * @brief Set Scan Response Data
4427  * @param advertising_data_length
4428  * @param advertising_data (max 31 octets)
4429  * @note data is not copied, pointer has to stay valid
4430  */
4431 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
4432     hci_stack->le_scan_response_data_len = scan_response_data_length;
4433     hci_stack->le_scan_response_data = scan_response_data;
4434     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4435     gap_advertisments_changed();
4436 }
4437 
4438 /**
4439  * @brief Set Advertisement Parameters
4440  * @param adv_int_min
4441  * @param adv_int_max
4442  * @param adv_type
4443  * @param direct_address_type
4444  * @param direct_address
4445  * @param channel_map
4446  * @param filter_policy
4447  *
4448  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
4449  */
4450  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4451     uint8_t direct_address_typ, bd_addr_t direct_address,
4452     uint8_t channel_map, uint8_t filter_policy) {
4453 
4454     hci_stack->le_advertisements_interval_min = adv_int_min;
4455     hci_stack->le_advertisements_interval_max = adv_int_max;
4456     hci_stack->le_advertisements_type = adv_type;
4457     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
4458     hci_stack->le_advertisements_channel_map = channel_map;
4459     hci_stack->le_advertisements_filter_policy = filter_policy;
4460     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
4461 
4462     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4463     gap_advertisments_changed();
4464  }
4465 
4466 /**
4467  * @brief Enable/Disable Advertisements
4468  * @param enabled
4469  */
4470 void gap_advertisements_enable(int enabled){
4471     hci_stack->le_advertisements_enabled = enabled;
4472     if (enabled && !hci_stack->le_advertisements_active){
4473         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
4474     }
4475     if (!enabled && hci_stack->le_advertisements_active){
4476         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
4477     }
4478     hci_run();
4479 }
4480 
4481 #endif
4482 
4483 void hci_le_set_own_address_type(uint8_t own_address_type){
4484     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
4485     if (own_address_type == hci_stack->le_own_addr_type) return;
4486     hci_stack->le_own_addr_type = own_address_type;
4487 
4488 #ifdef ENABLE_LE_PERIPHERAL
4489     // update advertisement parameters, too
4490     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4491     gap_advertisments_changed();
4492 #endif
4493 #ifdef ENABLE_LE_CENTRAL
4494     // note: we don't update scan parameters or modify ongoing connection attempts
4495 #endif
4496 }
4497 
4498 #endif
4499 
4500 uint8_t gap_disconnect(hci_con_handle_t handle){
4501     hci_connection_t * conn = hci_connection_for_handle(handle);
4502     if (!conn){
4503         hci_emit_disconnection_complete(handle, 0);
4504         return 0;
4505     }
4506     // ignore if already disconnected
4507     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
4508         return 0;
4509     }
4510     conn->state = SEND_DISCONNECT;
4511     hci_run();
4512     return 0;
4513 }
4514 
4515 /**
4516  * @brief Get connection type
4517  * @param con_handle
4518  * @result connection_type
4519  */
4520 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
4521     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4522     if (!conn) return GAP_CONNECTION_INVALID;
4523     switch (conn->address_type){
4524         case BD_ADDR_TYPE_LE_PUBLIC:
4525         case BD_ADDR_TYPE_LE_RANDOM:
4526             return GAP_CONNECTION_LE;
4527         case BD_ADDR_TYPE_SCO:
4528             return GAP_CONNECTION_SCO;
4529         case BD_ADDR_TYPE_CLASSIC:
4530             return GAP_CONNECTION_ACL;
4531         default:
4532             return GAP_CONNECTION_INVALID;
4533     }
4534 }
4535 
4536 #ifdef ENABLE_BLE
4537 
4538 #ifdef ENABLE_LE_CENTRAL
4539 /**
4540  * @brief Auto Connection Establishment - Start Connecting to device
4541  * @param address_typ
4542  * @param address
4543  * @returns 0 if ok
4544  */
4545 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
4546     // check capacity
4547     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
4548     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
4549     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
4550     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
4551     entry->address_type = address_type;
4552     memcpy(entry->address, address, 6);
4553     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4554     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
4555     hci_run();
4556     return 0;
4557 }
4558 
4559 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
4560     btstack_linked_list_iterator_t it;
4561     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4562     while (btstack_linked_list_iterator_has_next(&it)){
4563         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4564         if (entry->address_type != address_type) continue;
4565         if (memcmp(entry->address, address, 6) != 0) continue;
4566         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4567             // remove from controller if already present
4568             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4569             continue;
4570         }
4571         // direclty remove entry from whitelist
4572         btstack_linked_list_iterator_remove(&it);
4573         btstack_memory_whitelist_entry_free(entry);
4574     }
4575 }
4576 
4577 /**
4578  * @brief Auto Connection Establishment - Stop Connecting to device
4579  * @param address_typ
4580  * @param address
4581  * @returns 0 if ok
4582  */
4583 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
4584     hci_remove_from_whitelist(address_type, address);
4585     hci_run();
4586     return 0;
4587 }
4588 
4589 /**
4590  * @brief Auto Connection Establishment - Stop everything
4591  * @note  Convenience function to stop all active auto connection attempts
4592  */
4593 void gap_auto_connection_stop_all(void){
4594     btstack_linked_list_iterator_t it;
4595     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4596     while (btstack_linked_list_iterator_has_next(&it)){
4597         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4598         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4599             // remove from controller if already present
4600             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4601             continue;
4602         }
4603         // directly remove entry from whitelist
4604         btstack_linked_list_iterator_remove(&it);
4605         btstack_memory_whitelist_entry_free(entry);
4606     }
4607     hci_run();
4608 }
4609 
4610 uint16_t gap_le_connection_interval(hci_con_handle_t connection_handle){
4611     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4612     if (!conn) return 0;
4613     return conn->le_connection_interval;
4614 }
4615 #endif
4616 #endif
4617 
4618 #ifdef ENABLE_CLASSIC
4619 /**
4620  * @brief Set Extended Inquiry Response data
4621  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
4622  * @note has to be done before stack starts up
4623  */
4624 void gap_set_extended_inquiry_response(const uint8_t * data){
4625     hci_stack->eir_data = data;
4626 }
4627 
4628 /**
4629  * @brief Start GAP Classic Inquiry
4630  * @param duration in 1.28s units
4631  * @return 0 if ok
4632  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
4633  */
4634 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
4635     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
4636     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4637     if (duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN || duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX){
4638         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
4639     }
4640     hci_stack->inquiry_state = duration_in_1280ms_units;
4641     hci_run();
4642     return 0;
4643 }
4644 
4645 /**
4646  * @brief Stop GAP Classic Inquiry
4647  * @returns 0 if ok
4648  */
4649 int gap_inquiry_stop(void){
4650     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX) {
4651         // emit inquiry complete event, before it even started
4652         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
4653         hci_emit_event(event, sizeof(event), 1);
4654         return 0;
4655     }
4656     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
4657     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
4658     hci_run();
4659     return 0;
4660 }
4661 
4662 
4663 /**
4664  * @brief Remote Name Request
4665  * @param addr
4666  * @param page_scan_repetition_mode
4667  * @param clock_offset only used when bit 15 is set
4668  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
4669  */
4670 int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
4671     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4672     memcpy(hci_stack->remote_name_addr, addr, 6);
4673     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
4674     hci_stack->remote_name_clock_offset = clock_offset;
4675     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
4676     hci_run();
4677     return 0;
4678 }
4679 
4680 static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){
4681     hci_stack->gap_pairing_state = state;
4682     memcpy(hci_stack->gap_pairing_addr, addr, 6);
4683     hci_run();
4684     return 0;
4685 }
4686 
4687 /**
4688  * @brief Legacy Pairing Pin Code Response
4689  * @param addr
4690  * @param pin
4691  * @return 0 if ok
4692  */
4693 int gap_pin_code_response(bd_addr_t addr, const char * pin){
4694     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4695     hci_stack->gap_pairing_input.gap_pairing_pin = pin;
4696     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
4697 }
4698 
4699 /**
4700  * @brief Abort Legacy Pairing
4701  * @param addr
4702  * @param pin
4703  * @return 0 if ok
4704  */
4705 int gap_pin_code_negative(bd_addr_t addr){
4706     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4707     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
4708 }
4709 
4710 /**
4711  * @brief SSP Passkey Response
4712  * @param addr
4713  * @param passkey
4714  * @return 0 if ok
4715  */
4716 int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){
4717     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4718     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
4719     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
4720 }
4721 
4722 /**
4723  * @brief Abort SSP Passkey Entry/Pairing
4724  * @param addr
4725  * @param pin
4726  * @return 0 if ok
4727  */
4728 int gap_ssp_passkey_negative(bd_addr_t addr){
4729     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4730     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
4731 }
4732 
4733 /**
4734  * @brief Accept SSP Numeric Comparison
4735  * @param addr
4736  * @param passkey
4737  * @return 0 if ok
4738  */
4739 int gap_ssp_confirmation_response(bd_addr_t addr){
4740     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4741     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
4742 }
4743 
4744 /**
4745  * @brief Abort SSP Numeric Comparison/Pairing
4746  * @param addr
4747  * @param pin
4748  * @return 0 if ok
4749  */
4750 int gap_ssp_confirmation_negative(bd_addr_t addr){
4751     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4752     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
4753 }
4754 
4755 /**
4756  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
4757  * @param inquiry_mode see bluetooth_defines.h
4758  */
4759 void hci_set_inquiry_mode(inquiry_mode_t mode){
4760     hci_stack->inquiry_mode = mode;
4761 }
4762 
4763 /**
4764  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
4765  */
4766 void hci_set_sco_voice_setting(uint16_t voice_setting){
4767     hci_stack->sco_voice_setting = voice_setting;
4768 }
4769 
4770 /**
4771  * @brief Get SCO Voice Setting
4772  * @return current voice setting
4773  */
4774 uint16_t hci_get_sco_voice_setting(void){
4775     return hci_stack->sco_voice_setting;
4776 }
4777 
4778 /** @brief Get SCO packet length for current SCO Voice setting
4779  *  @note  Using SCO packets of the exact length is required for USB transfer
4780  *  @return Length of SCO packets in bytes (not audio frames)
4781  */
4782 int hci_get_sco_packet_length(void){
4783     int sco_packet_length = 0;
4784 
4785 #ifdef ENABLE_CLASSIC
4786 #ifdef ENABLE_SCO_OVER_HCI
4787     // see Core Spec for H2 USB Transfer.
4788 
4789     // CVSD requires twice as much bytes
4790     int multiplier = hci_stack->sco_voice_setting & 0x0020 ? 2 : 1;
4791 
4792     // 3 byte SCO header + 24 bytes per connection
4793     sco_packet_length = 3 + 24 * hci_number_sco_connections() * multiplier;
4794 #endif
4795 #endif
4796     return sco_packet_length;
4797 }
4798 
4799 /**
4800 * @brief Sets the master/slave policy
4801 * @param policy (0: attempt to become master, 1: let connecting device decide)
4802 */
4803 void hci_set_master_slave_policy(uint8_t policy){
4804     hci_stack->master_slave_policy = policy;
4805 }
4806 
4807 #endif
4808 
4809 HCI_STATE hci_get_state(void){
4810     return hci_stack->state;
4811 }
4812 
4813 
4814 /**
4815  * @brief Set callback for Bluetooth Hardware Error
4816  */
4817 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
4818     hci_stack->hardware_error_callback = fn;
4819 }
4820 
4821 void hci_disconnect_all(void){
4822     btstack_linked_list_iterator_t it;
4823     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4824     while (btstack_linked_list_iterator_has_next(&it)){
4825         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4826         if (con->state == SENT_DISCONNECT) continue;
4827         con->state = SEND_DISCONNECT;
4828     }
4829     hci_run();
4830 }
4831 
4832 uint16_t hci_get_manufacturer(void){
4833     return hci_stack->manufacturer;
4834 }
4835 
4836 #ifdef ENABLE_BLE
4837 
4838 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4839     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
4840     if (!hci_con) return NULL;
4841     return &hci_con->sm_connection;
4842 }
4843 
4844 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
4845 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
4846 
4847 int gap_encryption_key_size(hci_con_handle_t con_handle){
4848     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4849     if (!sm_conn) return 0;     // wrong connection
4850     if (!sm_conn->sm_connection_encrypted) return 0;
4851     return sm_conn->sm_actual_encryption_key_size;
4852 }
4853 
4854 int gap_authenticated(hci_con_handle_t con_handle){
4855     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4856     if (!sm_conn) return 0;     // wrong connection
4857     if (!sm_conn->sm_connection_encrypted) return 0; // unencrypted connection cannot be authenticated
4858     return sm_conn->sm_connection_authenticated;
4859 }
4860 
4861 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
4862     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4863     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
4864     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
4865     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
4866     return sm_conn->sm_connection_authorization_state;
4867 }
4868 #endif
4869 
4870 #ifdef ENABLE_CLASSIC
4871 uint8_t gap_sniff_mode_enter(hci_con_handle_t con_handle, uint16_t sniff_min_interval, uint16_t sniff_max_interval, uint16_t sniff_attempt, uint16_t sniff_timeout){
4872     hci_connection_t * conn = hci_connection_for_handle(con_handle);
4873     if (!conn) return GAP_CONNECTION_INVALID;
4874     conn->sniff_min_interval = sniff_min_interval;
4875     conn->sniff_max_interval = sniff_max_interval;
4876     conn->sniff_attempt = sniff_attempt;
4877     conn->sniff_timeout = sniff_timeout;
4878     hci_run();
4879     return 0;
4880 }
4881 
4882 /**
4883  * @brief Exit Sniff mode
4884  * @param con_handle
4885  @ @return 0 if ok
4886  */
4887 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
4888     hci_connection_t * conn = hci_connection_for_handle(con_handle);
4889     if (!conn) return GAP_CONNECTION_INVALID;
4890     conn->sniff_min_interval = 0xffff;
4891     hci_run();
4892     return 0;
4893 }
4894 #endif
4895