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