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