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