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