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