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