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