xref: /btstack/src/hci.c (revision f41911ede3e60cbb330bca41e478c066545e76a4)
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 BTSTACK_CHIPSET_VALID_COMMAND:
1148                             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1149                             break;
1150                         case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
1151                             // 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                         default:
1168                             // should not get here
1169                             break;
1170                     }
1171                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1172                     break;
1173                 }
1174                 log_info("Init script done");
1175 
1176                 // Init script download on Broadcom chipsets causes:
1177                 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION){
1178                     // - baud rate to reset, restore UART baud rate if needed
1179                     int need_baud_change = hci_stack->config
1180                         && hci_stack->chipset
1181                         && hci_stack->chipset->set_baudrate_command
1182                         && hci_stack->hci_transport->set_baudrate
1183                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1184                     if (need_baud_change) {
1185                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1186                         log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate);
1187                         hci_stack->hci_transport->set_baudrate(baud_rate);
1188                     }
1189 
1190                     // - RTS will raise during update, but manual RTS/CTS in WICED port on RedBear Duo cannot handle this
1191                     //   -> Work around: wait a few milliseconds here.
1192                     log_info("BCM delay after init script");
1193                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1194                     btstack_run_loop_set_timer(&hci_stack->timeout, 10);
1195                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1196                     btstack_run_loop_add_timer(&hci_stack->timeout);
1197                     break;
1198                 }
1199                         }
1200             // otherwise continue
1201             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1202             hci_send_cmd(&hci_read_local_supported_commands);
1203             break;
1204         case HCI_INIT_SET_BD_ADDR:
1205             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1206             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1207             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1208             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1209             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1210             break;
1211 #endif
1212 
1213         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
1214             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
1215             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1216             hci_send_cmd(&hci_read_local_supported_commands);
1217             break;
1218         case HCI_INIT_READ_BD_ADDR:
1219             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
1220             hci_send_cmd(&hci_read_bd_addr);
1221             break;
1222         case HCI_INIT_READ_BUFFER_SIZE:
1223             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
1224             hci_send_cmd(&hci_read_buffer_size);
1225             break;
1226         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
1227             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
1228             hci_send_cmd(&hci_read_local_supported_features);
1229             break;
1230 
1231 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
1232         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
1233             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
1234             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
1235             break;
1236         case HCI_INIT_HOST_BUFFER_SIZE:
1237             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
1238             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
1239                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
1240             break;
1241 #endif
1242 
1243         case HCI_INIT_SET_EVENT_MASK:
1244             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
1245             if (hci_le_supported()){
1246                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1247             } else {
1248                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1249                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1250             }
1251             break;
1252 
1253 #ifdef ENABLE_CLASSIC
1254         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1255             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
1256             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1257             break;
1258         case HCI_INIT_WRITE_PAGE_TIMEOUT:
1259             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
1260             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
1261             break;
1262         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
1263             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
1264             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1265             break;
1266         case HCI_INIT_WRITE_LOCAL_NAME: {
1267             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
1268             hci_reserve_packet_buffer();
1269             uint8_t * packet = hci_stack->hci_packet_buffer;
1270             // construct HCI Command and send
1271             uint16_t opcode = hci_write_local_name.opcode;
1272             hci_stack->last_cmd_opcode = opcode;
1273             packet[0] = opcode & 0xff;
1274             packet[1] = opcode >> 8;
1275             packet[2] = DEVICE_NAME_LEN;
1276             memset(&packet[3], 0, DEVICE_NAME_LEN);
1277             memcpy(&packet[3], hci_stack->local_name, strlen(hci_stack->local_name));
1278             // expand '00:00:00:00:00:00' in name with bd_addr
1279             hci_replace_bd_addr_placeholder(&packet[3], DEVICE_NAME_LEN);
1280             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
1281             break;
1282         }
1283         case HCI_INIT_WRITE_EIR_DATA: {
1284             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
1285             hci_reserve_packet_buffer();
1286             uint8_t * packet = hci_stack->hci_packet_buffer;
1287             // construct HCI Command and send
1288             uint16_t opcode = hci_write_extended_inquiry_response.opcode;
1289             hci_stack->last_cmd_opcode = opcode;
1290             packet[0] = opcode & 0xff;
1291             packet[1] = opcode >> 8;
1292             packet[2] = 1 + 240;
1293             packet[3] = 0;  // FEC not required
1294             if (hci_stack->eir_data){
1295                 memcpy(&packet[4], hci_stack->eir_data, 240);
1296             } else {
1297                 memset(&packet[4], 0, 240);
1298                 int name_len = strlen(hci_stack->local_name);
1299                 packet[4] = name_len + 1;
1300                 packet[5] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
1301                 memcpy(&packet[6], hci_stack->local_name, name_len);
1302             }
1303             // expand '00:00:00:00:00:00' in name with bd_addr
1304             hci_replace_bd_addr_placeholder(&packet[4], 240);
1305             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + 240);
1306             break;
1307         }
1308         case HCI_INIT_WRITE_INQUIRY_MODE:
1309             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
1310             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1311             break;
1312         case HCI_INIT_WRITE_SCAN_ENABLE:
1313             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1314             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
1315             break;
1316         // only sent if ENABLE_SCO_OVER_HCI is defined
1317         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1318             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1319             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1320             break;
1321         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1322             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1323             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1324             break;
1325         // only sent if ENABLE_SCO_OVER_HCI and manufacturer is Broadcom
1326         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1327             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1328             log_info("BCM: Route SCO data via HCI transport");
1329             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
1330             break;
1331 
1332 #endif
1333 #ifdef ENABLE_BLE
1334         // LE INIT
1335         case HCI_INIT_LE_READ_BUFFER_SIZE:
1336             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
1337             hci_send_cmd(&hci_le_read_buffer_size);
1338             break;
1339         case HCI_INIT_LE_SET_EVENT_MASK:
1340             hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
1341             hci_send_cmd(&hci_le_set_event_mask, 0x1FF, 0x0);
1342             break;
1343         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
1344             // LE Supported Host = 1, Simultaneous Host = 0
1345             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
1346             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1347             break;
1348 #endif
1349 
1350 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1351         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
1352             hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
1353             hci_send_cmd(&hci_le_read_maximum_data_length);
1354             break;
1355         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
1356             hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
1357             hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1358             break;
1359 #endif
1360 
1361 #ifdef ENABLE_LE_CENTRAL
1362         case HCI_INIT_READ_WHITE_LIST_SIZE:
1363             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
1364             hci_send_cmd(&hci_le_read_white_list_size);
1365             break;
1366         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1367             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, own address type, accept all advs
1368             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1369             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, hci_stack->le_own_addr_type, 0);
1370             break;
1371 #endif
1372         default:
1373             return;
1374     }
1375 }
1376 
1377 static void hci_init_done(void){
1378     // done. tell the app
1379     log_info("hci_init_done -> HCI_STATE_WORKING");
1380     hci_stack->state = HCI_STATE_WORKING;
1381     hci_emit_state();
1382     hci_run();
1383 }
1384 
1385 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
1386 
1387     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
1388 
1389     uint8_t command_completed = 0;
1390 
1391     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1392         uint16_t opcode = little_endian_read_16(packet,3);
1393         if (opcode == hci_stack->last_cmd_opcode){
1394             command_completed = 1;
1395             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
1396         } else {
1397             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
1398         }
1399     }
1400 
1401     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
1402         uint8_t  status = packet[2];
1403         uint16_t opcode = little_endian_read_16(packet,4);
1404         if (opcode == hci_stack->last_cmd_opcode){
1405             if (status){
1406                 command_completed = 1;
1407                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
1408             } else {
1409                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
1410             }
1411         } else {
1412             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1413         }
1414     }
1415 
1416 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1417 
1418     // Vendor == CSR
1419     if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1420         // TODO: track actual command
1421         command_completed = 1;
1422     }
1423 
1424     // Vendor == Toshiba
1425     if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1426         // TODO: track actual command
1427         command_completed = 1;
1428     }
1429 
1430     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1431     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1432     //
1433     // HCI Reset
1434     // Timeout 100 ms
1435     // HCI Reset
1436     // Command Complete Reset
1437     // HCI Read Local Version Information
1438     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1439     // hang...
1440     //
1441     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1442     if (!command_completed
1443             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1444             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
1445 
1446         uint16_t opcode = little_endian_read_16(packet,3);
1447         if (opcode == hci_reset.opcode){
1448             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1449             return;
1450         }
1451     }
1452 
1453     // CSR & H5
1454     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1455     if (!command_completed
1456             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1457             && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){
1458 
1459         uint16_t opcode = little_endian_read_16(packet,3);
1460         if (opcode == hci_reset.opcode){
1461             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1462             return;
1463         }
1464     }
1465 
1466     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
1467     // fix: Correct substate and behave as command below
1468     if (command_completed){
1469         switch (hci_stack->substate){
1470             case HCI_INIT_SEND_RESET:
1471                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1472                 break;
1473             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1474                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1475                 break;
1476             default:
1477                 break;
1478         }
1479     }
1480 
1481 #endif
1482 
1483     if (!command_completed) return;
1484 
1485     int need_baud_change = 0;
1486     int need_addr_change = 0;
1487 
1488 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1489     need_baud_change = hci_stack->config
1490                         && hci_stack->chipset
1491                         && hci_stack->chipset->set_baudrate_command
1492                         && hci_stack->hci_transport->set_baudrate
1493                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1494 
1495     need_addr_change = hci_stack->custom_bd_addr_set
1496                         && hci_stack->chipset
1497                         && hci_stack->chipset->set_bd_addr_command;
1498 #endif
1499 
1500     switch(hci_stack->substate){
1501 
1502 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1503         case HCI_INIT_SEND_RESET:
1504             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
1505             // fix: just correct substate and behave as command below
1506             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1507             btstack_run_loop_remove_timer(&hci_stack->timeout);
1508             break;
1509         case HCI_INIT_W4_SEND_RESET:
1510             btstack_run_loop_remove_timer(&hci_stack->timeout);
1511             break;
1512         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
1513             log_info("Received local name, need baud change %d", need_baud_change);
1514             if (need_baud_change){
1515                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
1516                 return;
1517             }
1518             // skip baud change
1519             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1520             return;
1521         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1522             // for STLC2500D, baud rate change already happened.
1523             // for others, baud rate gets changed now
1524             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
1525                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1526                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1527                 hci_stack->hci_transport->set_baudrate(baud_rate);
1528             }
1529             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1530             return;
1531         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1532             btstack_run_loop_remove_timer(&hci_stack->timeout);
1533             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1534             return;
1535         case HCI_INIT_W4_CUSTOM_INIT:
1536             // repeat custom init
1537             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1538             return;
1539 #else
1540         case HCI_INIT_W4_SEND_RESET:
1541             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1542             return ;
1543 #endif
1544 
1545         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1546             if (need_baud_change && hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION){
1547                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1548                 return;
1549             }
1550             if (need_addr_change){
1551                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1552                 return;
1553             }
1554             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1555             return;
1556 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1557         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
1558             if (need_baud_change){
1559                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1560                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1561                 hci_stack->hci_transport->set_baudrate(baud_rate);
1562             }
1563             if (need_addr_change){
1564                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1565                 return;
1566             }
1567             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1568             return;
1569         case HCI_INIT_W4_SET_BD_ADDR:
1570             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
1571             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
1572             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
1573                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
1574                 return;
1575             }
1576             // skipping st warm boot
1577             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1578             return;
1579         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
1580             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1581             return;
1582 #endif
1583         case HCI_INIT_W4_READ_BD_ADDR:
1584             // only read buffer size if supported
1585             if (hci_stack->local_supported_commands[0] & 0x01) {
1586                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
1587                 return;
1588             }
1589             // skipping read buffer size
1590             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1591             return;
1592         case HCI_INIT_W4_SET_EVENT_MASK:
1593             // skip Classic init commands for LE only chipsets
1594             if (!hci_classic_supported()){
1595 #ifdef ENABLE_BLE
1596                 if (hci_le_supported()){
1597                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
1598                     return;
1599                 }
1600 #endif
1601                 log_error("Neither BR/EDR nor LE supported");
1602                 hci_init_done();
1603                 return;
1604             }
1605             if (!gap_ssp_supported()){
1606                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
1607                 return;
1608             }
1609             break;
1610 #ifdef ENABLE_BLE
1611         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1612             // skip write le host if not supported (e.g. on LE only EM9301)
1613             if (hci_stack->local_supported_commands[0] & 0x02) break;
1614             hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1615             return;
1616 
1617 
1618 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1619         case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED:
1620             if ((hci_stack->local_supported_commands[0] & 0x30) == 0x30){
1621                 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1622                 return;
1623             }
1624             // explicit fall through to reduce repetitions
1625 #endif
1626 
1627 #ifdef ENABLE_LE_CENTRAL
1628             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1629 #else
1630             hci_init_done();
1631 #endif
1632             return;
1633 #endif
1634 
1635 #ifdef ENABLE_SCO_OVER_HCI
1636         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1637             // skip write synchronous flow control if not supported
1638             if (hci_stack->local_supported_commands[0] & 0x04) break;
1639             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1640             // explicit fall through to reduce repetitions
1641 
1642         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1643             // skip write default erroneous data reporting if not supported
1644             if (hci_stack->local_supported_commands[0] & 0x08) break;
1645             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1646             // explicit fall through to reduce repetitions
1647 
1648         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1649             // skip bcm set sco pcm config on non-Broadcom chipsets
1650             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break;
1651             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1652             // explicit fall through to reduce repetitions
1653 
1654         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1655             if (!hci_le_supported()){
1656                 // SKIP LE init for Classic only configuration
1657                 hci_init_done();
1658                 return;
1659             }
1660             break;
1661 
1662 #else /* !ENABLE_SCO_OVER_HCI */
1663 
1664         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1665 #ifdef ENABLE_BLE
1666             if (hci_le_supported()){
1667                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
1668                 return;
1669             }
1670 #endif
1671             // SKIP LE init for Classic only configuration
1672             hci_init_done();
1673             return;
1674 #endif /* ENABLE_SCO_OVER_HCI */
1675 
1676         // Response to command before init done state -> init done
1677         case (HCI_INIT_DONE-1):
1678             hci_init_done();
1679             return;
1680 
1681         default:
1682             break;
1683     }
1684     hci_initializing_next_state();
1685 }
1686 
1687 static void event_handler(uint8_t *packet, int size){
1688 
1689     uint16_t event_length = packet[1];
1690 
1691     // assert packet is complete
1692     if (size != event_length + 2){
1693         log_error("hci.c: event_handler called with event packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
1694         return;
1695     }
1696 
1697     bd_addr_t addr;
1698     bd_addr_type_t addr_type;
1699     hci_con_handle_t handle;
1700     hci_connection_t * conn;
1701     int i;
1702 #ifdef ENABLE_CLASSIC
1703     uint8_t link_type;
1704 #endif
1705 
1706     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
1707 
1708     switch (hci_event_packet_get_type(packet)) {
1709 
1710         case HCI_EVENT_COMMAND_COMPLETE:
1711             // get num cmd packets - limit to 1 to reduce complexity
1712             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
1713 
1714             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
1715                 if (packet[5]) break;
1716                 // terminate, name 248 chars
1717                 packet[6+248] = 0;
1718                 log_info("local name: %s", &packet[6]);
1719             }
1720             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1721                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1722                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1723                     uint16_t acl_len = little_endian_read_16(packet, 6);
1724                     uint16_t sco_len = packet[8];
1725 
1726                     // determine usable ACL/SCO payload size
1727                     hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
1728                     hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
1729 
1730                     hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1731                     hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1732 
1733                     log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
1734                              acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1735                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1736                 }
1737             }
1738 #ifdef ENABLE_BLE
1739             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1740                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1741                 hci_stack->le_acl_packets_total_num  = packet[8];
1742                 // determine usable ACL payload size
1743                 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1744                     hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1745                 }
1746                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1747             }
1748 #endif
1749 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1750             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_maximum_data_length)){
1751                 hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
1752                 hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
1753                 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);
1754             }
1755 #endif
1756 #ifdef ENABLE_LE_CENTRAL
1757             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1758                 hci_stack->le_whitelist_capacity = packet[6];
1759                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1760             }
1761 #endif
1762             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1763                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1764 				hci_stack->local_bd_addr);
1765                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1766                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1767 #ifdef ENABLE_CLASSIC
1768                 if (hci_stack->link_key_db){
1769                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1770                 }
1771 #endif
1772             }
1773 #ifdef ENABLE_CLASSIC
1774             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1775                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1776             }
1777             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_inquiry_cancel)){
1778                 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
1779                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1780                     uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1781                     hci_emit_event(event, sizeof(event), 1);
1782                 }
1783             }
1784 #endif
1785 
1786             // Note: HCI init checks
1787             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1788                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1789 
1790 #ifdef ENABLE_CLASSIC
1791                 // determine usable ACL packet types based on host buffer size and supported features
1792                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1793                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
1794 #endif
1795                 // Classic/LE
1796                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1797             }
1798             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1799                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1800                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1801                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1802                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1803                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1804                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1805             }
1806             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1807                 hci_stack->local_supported_commands[0] =
1808                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7
1809                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6
1810                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4
1811                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08)      |  // bit 3 = Octet 18, bit 3
1812                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x01) << 4 |  // bit 4 = Octet 34, bit 0
1813                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x08) << 2;   // bit 5 = Octet 35, bit 3
1814                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1815             }
1816 #ifdef ENABLE_CLASSIC
1817             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1818                 if (packet[5] == 0){
1819                     hci_stack->synchronous_flow_control_enabled = 1;
1820                 }
1821             }
1822 #endif
1823             break;
1824 
1825         case HCI_EVENT_COMMAND_STATUS:
1826             // get num cmd packets - limit to 1 to reduce complexity
1827             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
1828             break;
1829 
1830         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1831             int offset = 3;
1832             for (i=0; i<packet[2];i++){
1833                 handle = little_endian_read_16(packet, offset);
1834                 offset += 2;
1835                 uint16_t num_packets = little_endian_read_16(packet, offset);
1836                 offset += 2;
1837 
1838                 conn = hci_connection_for_handle(handle);
1839                 if (!conn){
1840                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1841                     continue;
1842                 }
1843 
1844                 if (conn->address_type == BD_ADDR_TYPE_SCO){
1845 #ifdef ENABLE_CLASSIC
1846                     if (conn->num_sco_packets_sent >= num_packets){
1847                         conn->num_sco_packets_sent -= num_packets;
1848                     } else {
1849                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1850                         conn->num_sco_packets_sent = 0;
1851                     }
1852                     hci_notify_if_sco_can_send_now();
1853 #endif
1854                 } else {
1855                     if (conn->num_acl_packets_sent >= num_packets){
1856                         conn->num_acl_packets_sent -= num_packets;
1857                     } else {
1858                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
1859                         conn->num_acl_packets_sent = 0;
1860                     }
1861                 }
1862                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1863             }
1864             break;
1865         }
1866 
1867 #ifdef ENABLE_CLASSIC
1868         case HCI_EVENT_INQUIRY_COMPLETE:
1869             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
1870                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1871                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1872                 hci_emit_event(event, sizeof(event), 1);
1873             }
1874             break;
1875         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1876             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
1877                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
1878             }
1879             break;
1880         case HCI_EVENT_CONNECTION_REQUEST:
1881             reverse_bd_addr(&packet[2], addr);
1882             // TODO: eval COD 8-10
1883             link_type = packet[11];
1884             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1885             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
1886             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1887             if (!conn) {
1888                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1889             }
1890             if (!conn) {
1891                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1892                 hci_stack->decline_reason = 0x0d;
1893                 bd_addr_copy(hci_stack->decline_addr, addr);
1894                 break;
1895             }
1896             conn->role  = HCI_ROLE_SLAVE;
1897             conn->state = RECEIVED_CONNECTION_REQUEST;
1898             // store info about eSCO
1899             if (link_type == 0x02){
1900                 conn->remote_supported_feature_eSCO = 1;
1901             }
1902             hci_run();
1903             break;
1904 
1905         case HCI_EVENT_CONNECTION_COMPLETE:
1906             // Connection management
1907             reverse_bd_addr(&packet[5], addr);
1908             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1909             addr_type = BD_ADDR_TYPE_CLASSIC;
1910             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1911             if (conn) {
1912                 if (!packet[2]){
1913                     conn->state = OPEN;
1914                     conn->con_handle = little_endian_read_16(packet, 3);
1915                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1916 
1917                     // restart timer
1918                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1919                     btstack_run_loop_add_timer(&conn->timeout);
1920 
1921                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1922 
1923                     hci_emit_nr_connections_changed();
1924                 } else {
1925                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1926                     uint8_t status = packet[2];
1927                     bd_addr_t bd_address;
1928                     memcpy(&bd_address, conn->address, 6);
1929 
1930                     // connection failed, remove entry
1931                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1932                     btstack_memory_hci_connection_free( conn );
1933 
1934                     // notify client if dedicated bonding
1935                     if (notify_dedicated_bonding_failed){
1936                         log_info("hci notify_dedicated_bonding_failed");
1937                         hci_emit_dedicated_bonding_result(bd_address, status);
1938                     }
1939 
1940                     // if authentication error, also delete link key
1941                     if (packet[2] == 0x05) {
1942                         gap_drop_link_key_for_bd_addr(addr);
1943                     }
1944                 }
1945             }
1946             break;
1947 
1948         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1949             reverse_bd_addr(&packet[5], addr);
1950             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1951             if (packet[2]){
1952                 // connection failed
1953                 break;
1954             }
1955             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1956             if (!conn) {
1957                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1958             }
1959             if (!conn) {
1960                 break;
1961             }
1962             conn->state = OPEN;
1963             conn->con_handle = little_endian_read_16(packet, 3);
1964 
1965 #ifdef ENABLE_SCO_OVER_HCI
1966             // update SCO
1967             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
1968                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1969             }
1970 #endif
1971             break;
1972 
1973         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1974             handle = little_endian_read_16(packet, 3);
1975             conn = hci_connection_for_handle(handle);
1976             if (!conn) break;
1977             if (!packet[2]){
1978                 uint8_t * features = &packet[5];
1979                 if (features[6] & (1 << 3)){
1980                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1981                 }
1982                 if (features[3] & (1<<7)){
1983                     conn->remote_supported_feature_eSCO = 1;
1984                 }
1985             }
1986             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1987             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
1988             if (conn->bonding_flags & BONDING_DEDICATED){
1989                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1990             }
1991             break;
1992 
1993         case HCI_EVENT_LINK_KEY_REQUEST:
1994             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1995             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1996             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1997             if (hci_stack->bondable && !hci_stack->link_key_db) break;
1998             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1999             hci_run();
2000             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
2001             return;
2002 
2003         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2004             reverse_bd_addr(&packet[2], addr);
2005             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2006             if (!conn) break;
2007             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
2008             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2009             // Change Connection Encryption keeps link key type
2010             if (link_key_type != CHANGED_COMBINATION_KEY){
2011                 conn->link_key_type = link_key_type;
2012             }
2013             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2014             // still forward event to allow dismiss of pairing dialog
2015             break;
2016         }
2017 
2018         case HCI_EVENT_PIN_CODE_REQUEST:
2019             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
2020             // non-bondable mode: pin code negative reply will be sent
2021             if (!hci_stack->bondable){
2022                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
2023                 hci_run();
2024                 return;
2025             }
2026             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
2027             if (!hci_stack->link_key_db) break;
2028             hci_event_pin_code_request_get_bd_addr(packet, addr);
2029             hci_stack->link_key_db->delete_link_key(addr);
2030             break;
2031 
2032         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2033             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
2034             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
2035             break;
2036 
2037         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2038             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2039             if (!hci_stack->ssp_auto_accept) break;
2040             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
2041             break;
2042 
2043         case HCI_EVENT_USER_PASSKEY_REQUEST:
2044             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2045             if (!hci_stack->ssp_auto_accept) break;
2046             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
2047             break;
2048 #endif
2049 
2050         case HCI_EVENT_ENCRYPTION_CHANGE:
2051             handle = little_endian_read_16(packet, 3);
2052             conn = hci_connection_for_handle(handle);
2053             if (!conn) break;
2054             if (packet[2] == 0) {
2055                 if (packet[5]){
2056                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
2057                 } else {
2058                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
2059                 }
2060             }
2061 #ifdef ENABLE_CLASSIC
2062             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2063 #endif
2064             break;
2065 
2066 #ifdef ENABLE_CLASSIC
2067         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2068             handle = little_endian_read_16(packet, 3);
2069             conn = hci_connection_for_handle(handle);
2070             if (!conn) break;
2071 
2072             // dedicated bonding: send result and disconnect
2073             if (conn->bonding_flags & BONDING_DEDICATED){
2074                 conn->bonding_flags &= ~BONDING_DEDICATED;
2075                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2076                 conn->bonding_status = packet[2];
2077                 break;
2078             }
2079 
2080             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
2081                 // link key sufficient for requested security
2082                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2083                 break;
2084             }
2085             // not enough
2086             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2087             break;
2088 #endif
2089 
2090         // HCI_EVENT_DISCONNECTION_COMPLETE
2091         // has been split, to first notify stack before shutting connection down
2092         // see end of function, too.
2093         case HCI_EVENT_DISCONNECTION_COMPLETE:
2094             if (packet[2]) break;   // status != 0
2095             handle = little_endian_read_16(packet, 3);
2096             // drop outgoing ACL fragments if it is for closed connection
2097             if (hci_stack->acl_fragmentation_total_size > 0) {
2098                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
2099                     log_info("hci: drop fragmented ACL data for closed connection");
2100                      hci_stack->acl_fragmentation_total_size = 0;
2101                      hci_stack->acl_fragmentation_pos = 0;
2102                 }
2103             }
2104 
2105             // re-enable advertisements for le connections if active
2106             conn = hci_connection_for_handle(handle);
2107             if (!conn) break;
2108 #ifdef ENABLE_BLE
2109 #ifdef ENABLE_LE_PERIPHERAL
2110             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
2111                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2112             }
2113 #endif
2114 #endif
2115             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2116             break;
2117 
2118         case HCI_EVENT_HARDWARE_ERROR:
2119             log_error("Hardware Error: 0x%02x", packet[2]);
2120             if (hci_stack->hardware_error_callback){
2121                 (*hci_stack->hardware_error_callback)(packet[2]);
2122             } else {
2123                 // if no special requests, just reboot stack
2124                 hci_power_control_off();
2125                 hci_power_control_on();
2126             }
2127             break;
2128 
2129 #ifdef ENABLE_CLASSIC
2130         case HCI_EVENT_ROLE_CHANGE:
2131             if (packet[2]) break;   // status != 0
2132             handle = little_endian_read_16(packet, 3);
2133             conn = hci_connection_for_handle(handle);
2134             if (!conn) break;       // no conn
2135             conn->role = packet[9];
2136             break;
2137 #endif
2138 
2139         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2140             // release packet buffer only for asynchronous transport and if there are not further fragements
2141             if (hci_transport_synchronous()) {
2142                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2143                 return; // instead of break: to avoid re-entering hci_run()
2144             }
2145             if (hci_stack->acl_fragmentation_total_size) break;
2146             hci_release_packet_buffer();
2147 
2148             // L2CAP receives this event via the hci_emit_event below
2149 
2150 #ifdef ENABLE_CLASSIC
2151             // For SCO, we do the can_send_now_check here
2152             hci_notify_if_sco_can_send_now();
2153 #endif
2154             break;
2155 
2156 #ifdef ENABLE_CLASSIC
2157         case HCI_EVENT_SCO_CAN_SEND_NOW:
2158             // For SCO, we do the can_send_now_check here
2159             hci_notify_if_sco_can_send_now();
2160             return;
2161 
2162         // explode inquriy results for easier consumption
2163         case HCI_EVENT_INQUIRY_RESULT:
2164         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
2165         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
2166             gap_inquiry_explode(packet);
2167             break;
2168 #endif
2169 
2170 #ifdef ENABLE_BLE
2171         case HCI_EVENT_LE_META:
2172             switch (packet[2]){
2173 #ifdef ENABLE_LE_CENTRAL
2174                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
2175                     // log_info("advertising report received");
2176                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
2177                     le_handle_advertisement_report(packet, size);
2178                     break;
2179 #endif
2180                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
2181                     // Connection management
2182                     reverse_bd_addr(&packet[8], addr);
2183                     addr_type = (bd_addr_type_t)packet[7];
2184                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2185                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2186 #ifdef ENABLE_LE_CENTRAL
2187                     // if auto-connect, remove from whitelist in both roles
2188                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
2189                         hci_remove_from_whitelist(addr_type, addr);
2190                     }
2191                     // handle error: error is reported only to the initiator -> outgoing connection
2192                     if (packet[3]){
2193                         // outgoing connection establishment is done
2194                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2195                         // remove entry
2196                         if (conn){
2197                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2198                             btstack_memory_hci_connection_free( conn );
2199                         }
2200                         break;
2201                     }
2202 #endif
2203                     // on success, both hosts receive connection complete event
2204                     if (packet[6] == HCI_ROLE_MASTER){
2205 #ifdef ENABLE_LE_CENTRAL
2206                         // if we're master, it was an outgoing connection and we're done with it
2207                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2208 #endif
2209                     } else {
2210 #ifdef ENABLE_LE_PERIPHERAL
2211                         // if we're slave, it was an incoming connection, advertisements have stopped
2212                         hci_stack->le_advertisements_active = 0;
2213                         // try to re-enable them
2214                         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2215 #endif
2216                     }
2217                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2218                     if (!conn){
2219                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2220                     }
2221                     // no memory, sorry.
2222                     if (!conn){
2223                         break;
2224                     }
2225 
2226                     conn->state = OPEN;
2227                     conn->role  = packet[6];
2228                     conn->con_handle = little_endian_read_16(packet, 4);
2229 
2230                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2231 
2232                     // restart timer
2233                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2234                     // btstack_run_loop_add_timer(&conn->timeout);
2235 
2236                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2237 
2238                     hci_emit_nr_connections_changed();
2239                     break;
2240 
2241             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2242 
2243                 default:
2244                     break;
2245             }
2246             break;
2247 #endif
2248         default:
2249             break;
2250     }
2251 
2252     // handle BT initialization
2253     if (hci_stack->state == HCI_STATE_INITIALIZING){
2254         hci_initializing_event_handler(packet, size);
2255     }
2256 
2257     // help with BT sleep
2258     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2259         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2260         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2261         hci_initializing_next_state();
2262     }
2263 
2264     // notify upper stack
2265 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2266 
2267     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2268     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2269         if (!packet[2]){
2270             handle = little_endian_read_16(packet, 3);
2271             hci_connection_t * aConn = hci_connection_for_handle(handle);
2272             if (aConn) {
2273                 uint8_t status = aConn->bonding_status;
2274                 uint16_t flags = aConn->bonding_flags;
2275                 bd_addr_t bd_address;
2276                 memcpy(&bd_address, aConn->address, 6);
2277                 hci_shutdown_connection(aConn);
2278                 // connection struct is gone, don't access anymore
2279                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2280                     hci_emit_dedicated_bonding_result(bd_address, status);
2281                 }
2282             }
2283         }
2284     }
2285 
2286 	// execute main loop
2287 	hci_run();
2288 }
2289 
2290 #ifdef ENABLE_CLASSIC
2291 static void sco_handler(uint8_t * packet, uint16_t size){
2292     if (!hci_stack->sco_packet_handler) return;
2293     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2294 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2295     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2296     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
2297     if (conn){
2298         conn->num_packets_completed++;
2299         hci_stack->host_completed_packets = 1;
2300         hci_run();
2301     }
2302 #endif
2303 }
2304 #endif
2305 
2306 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2307     hci_dump_packet(packet_type, 1, packet, size);
2308     switch (packet_type) {
2309         case HCI_EVENT_PACKET:
2310             event_handler(packet, size);
2311             break;
2312         case HCI_ACL_DATA_PACKET:
2313             acl_handler(packet, size);
2314             break;
2315 #ifdef ENABLE_CLASSIC
2316         case HCI_SCO_DATA_PACKET:
2317             sco_handler(packet, size);
2318             break;
2319 #endif
2320         default:
2321             break;
2322     }
2323 }
2324 
2325 /**
2326  * @brief Add event packet handler.
2327  */
2328 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2329     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2330 }
2331 
2332 
2333 /** Register HCI packet handlers */
2334 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2335     hci_stack->acl_packet_handler = handler;
2336 }
2337 
2338 #ifdef ENABLE_CLASSIC
2339 /**
2340  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2341  */
2342 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2343     hci_stack->sco_packet_handler = handler;
2344 }
2345 #endif
2346 
2347 static void hci_state_reset(void){
2348     // no connections yet
2349     hci_stack->connections = NULL;
2350 
2351     // keep discoverable/connectable as this has been requested by the client(s)
2352     // hci_stack->discoverable = 0;
2353     // hci_stack->connectable = 0;
2354     // hci_stack->bondable = 1;
2355     // hci_stack->own_addr_type = 0;
2356 
2357     // buffer is free
2358     hci_stack->hci_packet_buffer_reserved = 0;
2359 
2360     // no pending cmds
2361     hci_stack->decline_reason = 0;
2362     hci_stack->new_scan_enable_value = 0xff;
2363 
2364     // LE
2365 #ifdef ENABLE_BLE
2366     memset(hci_stack->le_random_address, 0, 6);
2367     hci_stack->le_random_address_set = 0;
2368 #endif
2369 #ifdef ENABLE_LE_CENTRAL
2370     hci_stack->le_scanning_state = LE_SCAN_IDLE;
2371     hci_stack->le_scan_type = 0xff;
2372     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2373     hci_stack->le_whitelist = 0;
2374     hci_stack->le_whitelist_capacity = 0;
2375 #endif
2376 }
2377 
2378 #ifdef ENABLE_CLASSIC
2379 /**
2380  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2381  */
2382 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2383     // store and open remote device db
2384     hci_stack->link_key_db = link_key_db;
2385     if (hci_stack->link_key_db) {
2386         hci_stack->link_key_db->open();
2387     }
2388 }
2389 #endif
2390 
2391 void hci_init(const hci_transport_t *transport, const void *config){
2392 
2393 #ifdef HAVE_MALLOC
2394     if (!hci_stack) {
2395         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2396     }
2397 #else
2398     hci_stack = &hci_stack_static;
2399 #endif
2400     memset(hci_stack, 0, sizeof(hci_stack_t));
2401 
2402     // reference to use transport layer implementation
2403     hci_stack->hci_transport = transport;
2404 
2405     // reference to used config
2406     hci_stack->config = config;
2407 
2408     // setup pointer for outgoing packet buffer
2409     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2410 
2411     // max acl payload size defined in config.h
2412     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2413 
2414     // register packet handlers with transport
2415     transport->register_packet_handler(&packet_handler);
2416 
2417     hci_stack->state = HCI_STATE_OFF;
2418 
2419     // class of device
2420     hci_stack->class_of_device = 0x007a020c; // Smartphone
2421 
2422     // bondable by default
2423     hci_stack->bondable = 1;
2424 
2425 #ifdef ENABLE_CLASSIC
2426     // classic name
2427     hci_stack->local_name = default_classic_name;
2428 #endif
2429 
2430     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2431     hci_stack->ssp_enable = 1;
2432     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2433     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2434     hci_stack->ssp_auto_accept = 1;
2435 
2436     // voice setting - signed 16 bit pcm data with CVSD over the air
2437     hci_stack->sco_voice_setting = 0x60;
2438 
2439 #ifdef ENABLE_LE_CENTRAL
2440     // connection parameter to use for outgoing connections
2441     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
2442     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
2443     hci_stack->le_connection_latency      = 4;         // 4
2444     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
2445     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
2446     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
2447 #endif
2448 
2449     // connection parameter range used to answer connection parameter update requests in l2cap
2450     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2451     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2452     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2453     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2454     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2455     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2456 
2457     hci_state_reset();
2458 }
2459 
2460 /**
2461  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2462  */
2463 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2464     hci_stack->chipset = chipset_driver;
2465 
2466     // reset chipset driver - init is also called on power_up
2467     if (hci_stack->chipset && hci_stack->chipset->init){
2468         hci_stack->chipset->init(hci_stack->config);
2469     }
2470 }
2471 
2472 /**
2473  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2474  */
2475 void hci_set_control(const btstack_control_t *hardware_control){
2476     // references to used control implementation
2477     hci_stack->control = hardware_control;
2478     // init with transport config
2479     hardware_control->init(hci_stack->config);
2480 }
2481 
2482 void hci_close(void){
2483     // close remote device db
2484     if (hci_stack->link_key_db) {
2485         hci_stack->link_key_db->close();
2486     }
2487 
2488     btstack_linked_list_iterator_t lit;
2489     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2490     while (btstack_linked_list_iterator_has_next(&lit)){
2491         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2492         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2493         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2494         hci_shutdown_connection(connection);
2495     }
2496 
2497     hci_power_control(HCI_POWER_OFF);
2498 
2499 #ifdef HAVE_MALLOC
2500     free(hci_stack);
2501 #endif
2502     hci_stack = NULL;
2503 }
2504 
2505 #ifdef ENABLE_CLASSIC
2506 void gap_set_class_of_device(uint32_t class_of_device){
2507     hci_stack->class_of_device = class_of_device;
2508 }
2509 
2510 void hci_disable_l2cap_timeout_check(void){
2511     disable_l2cap_timeouts = 1;
2512 }
2513 #endif
2514 
2515 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2516 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2517 void hci_set_bd_addr(bd_addr_t addr){
2518     memcpy(hci_stack->custom_bd_addr, addr, 6);
2519     hci_stack->custom_bd_addr_set = 1;
2520 }
2521 #endif
2522 
2523 // State-Module-Driver overview
2524 // state                    module  low-level
2525 // HCI_STATE_OFF             off      close
2526 // HCI_STATE_INITIALIZING,   on       open
2527 // HCI_STATE_WORKING,        on       open
2528 // HCI_STATE_HALTING,        on       open
2529 // HCI_STATE_SLEEPING,    off/sleep   close
2530 // HCI_STATE_FALLING_ASLEEP  on       open
2531 
2532 static int hci_power_control_on(void){
2533 
2534     // power on
2535     int err = 0;
2536     if (hci_stack->control && hci_stack->control->on){
2537         err = (*hci_stack->control->on)();
2538     }
2539     if (err){
2540         log_error( "POWER_ON failed");
2541         hci_emit_hci_open_failed();
2542         return err;
2543     }
2544 
2545     // int chipset driver
2546     if (hci_stack->chipset && hci_stack->chipset->init){
2547         hci_stack->chipset->init(hci_stack->config);
2548     }
2549 
2550     // init transport
2551     if (hci_stack->hci_transport->init){
2552         hci_stack->hci_transport->init(hci_stack->config);
2553     }
2554 
2555     // open transport
2556     err = hci_stack->hci_transport->open();
2557     if (err){
2558         log_error( "HCI_INIT failed, turning Bluetooth off again");
2559         if (hci_stack->control && hci_stack->control->off){
2560             (*hci_stack->control->off)();
2561         }
2562         hci_emit_hci_open_failed();
2563         return err;
2564     }
2565     return 0;
2566 }
2567 
2568 static void hci_power_control_off(void){
2569 
2570     log_info("hci_power_control_off");
2571 
2572     // close low-level device
2573     hci_stack->hci_transport->close();
2574 
2575     log_info("hci_power_control_off - hci_transport closed");
2576 
2577     // power off
2578     if (hci_stack->control && hci_stack->control->off){
2579         (*hci_stack->control->off)();
2580     }
2581 
2582     log_info("hci_power_control_off - control closed");
2583 
2584     hci_stack->state = HCI_STATE_OFF;
2585 }
2586 
2587 static void hci_power_control_sleep(void){
2588 
2589     log_info("hci_power_control_sleep");
2590 
2591 #if 0
2592     // don't close serial port during sleep
2593 
2594     // close low-level device
2595     hci_stack->hci_transport->close(hci_stack->config);
2596 #endif
2597 
2598     // sleep mode
2599     if (hci_stack->control && hci_stack->control->sleep){
2600         (*hci_stack->control->sleep)();
2601     }
2602 
2603     hci_stack->state = HCI_STATE_SLEEPING;
2604 }
2605 
2606 static int hci_power_control_wake(void){
2607 
2608     log_info("hci_power_control_wake");
2609 
2610     // wake on
2611     if (hci_stack->control && hci_stack->control->wake){
2612         (*hci_stack->control->wake)();
2613     }
2614 
2615 #if 0
2616     // open low-level device
2617     int err = hci_stack->hci_transport->open(hci_stack->config);
2618     if (err){
2619         log_error( "HCI_INIT failed, turning Bluetooth off again");
2620         if (hci_stack->control && hci_stack->control->off){
2621             (*hci_stack->control->off)();
2622         }
2623         hci_emit_hci_open_failed();
2624         return err;
2625     }
2626 #endif
2627 
2628     return 0;
2629 }
2630 
2631 static void hci_power_transition_to_initializing(void){
2632     // set up state machine
2633     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2634     hci_stack->hci_packet_buffer_reserved = 0;
2635     hci_stack->state = HCI_STATE_INITIALIZING;
2636     hci_stack->substate = HCI_INIT_SEND_RESET;
2637 }
2638 
2639 int hci_power_control(HCI_POWER_MODE power_mode){
2640 
2641     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2642 
2643     int err = 0;
2644     switch (hci_stack->state){
2645 
2646         case HCI_STATE_OFF:
2647             switch (power_mode){
2648                 case HCI_POWER_ON:
2649                     err = hci_power_control_on();
2650                     if (err) {
2651                         log_error("hci_power_control_on() error %d", err);
2652                         return err;
2653                     }
2654                     hci_power_transition_to_initializing();
2655                     break;
2656                 case HCI_POWER_OFF:
2657                     // do nothing
2658                     break;
2659                 case HCI_POWER_SLEEP:
2660                     // do nothing (with SLEEP == OFF)
2661                     break;
2662             }
2663             break;
2664 
2665         case HCI_STATE_INITIALIZING:
2666             switch (power_mode){
2667                 case HCI_POWER_ON:
2668                     // do nothing
2669                     break;
2670                 case HCI_POWER_OFF:
2671                     // no connections yet, just turn it off
2672                     hci_power_control_off();
2673                     break;
2674                 case HCI_POWER_SLEEP:
2675                     // no connections yet, just turn it off
2676                     hci_power_control_sleep();
2677                     break;
2678             }
2679             break;
2680 
2681         case HCI_STATE_WORKING:
2682             switch (power_mode){
2683                 case HCI_POWER_ON:
2684                     // do nothing
2685                     break;
2686                 case HCI_POWER_OFF:
2687                     // see hci_run
2688                     hci_stack->state = HCI_STATE_HALTING;
2689                     break;
2690                 case HCI_POWER_SLEEP:
2691                     // see hci_run
2692                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2693                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2694                     break;
2695             }
2696             break;
2697 
2698         case HCI_STATE_HALTING:
2699             switch (power_mode){
2700                 case HCI_POWER_ON:
2701                     hci_power_transition_to_initializing();
2702                     break;
2703                 case HCI_POWER_OFF:
2704                     // do nothing
2705                     break;
2706                 case HCI_POWER_SLEEP:
2707                     // see hci_run
2708                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2709                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2710                     break;
2711             }
2712             break;
2713 
2714         case HCI_STATE_FALLING_ASLEEP:
2715             switch (power_mode){
2716                 case HCI_POWER_ON:
2717 
2718 #ifdef HAVE_PLATFORM_IPHONE_OS
2719                     // nothing to do, if H4 supports power management
2720                     if (btstack_control_iphone_power_management_enabled()){
2721                         hci_stack->state = HCI_STATE_INITIALIZING;
2722                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2723                         break;
2724                     }
2725 #endif
2726                     hci_power_transition_to_initializing();
2727                     break;
2728                 case HCI_POWER_OFF:
2729                     // see hci_run
2730                     hci_stack->state = HCI_STATE_HALTING;
2731                     break;
2732                 case HCI_POWER_SLEEP:
2733                     // do nothing
2734                     break;
2735             }
2736             break;
2737 
2738         case HCI_STATE_SLEEPING:
2739             switch (power_mode){
2740                 case HCI_POWER_ON:
2741 
2742 #ifdef HAVE_PLATFORM_IPHONE_OS
2743                     // nothing to do, if H4 supports power management
2744                     if (btstack_control_iphone_power_management_enabled()){
2745                         hci_stack->state = HCI_STATE_INITIALIZING;
2746                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2747                         hci_update_scan_enable();
2748                         break;
2749                     }
2750 #endif
2751                     err = hci_power_control_wake();
2752                     if (err) return err;
2753                     hci_power_transition_to_initializing();
2754                     break;
2755                 case HCI_POWER_OFF:
2756                     hci_stack->state = HCI_STATE_HALTING;
2757                     break;
2758                 case HCI_POWER_SLEEP:
2759                     // do nothing
2760                     break;
2761             }
2762             break;
2763     }
2764 
2765     // create internal event
2766 	hci_emit_state();
2767 
2768 	// trigger next/first action
2769 	hci_run();
2770 
2771     return 0;
2772 }
2773 
2774 
2775 #ifdef ENABLE_CLASSIC
2776 
2777 static void hci_update_scan_enable(void){
2778     // 2 = page scan, 1 = inq scan
2779     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2780     hci_run();
2781 }
2782 
2783 void gap_discoverable_control(uint8_t enable){
2784     if (enable) enable = 1; // normalize argument
2785 
2786     if (hci_stack->discoverable == enable){
2787         hci_emit_discoverable_enabled(hci_stack->discoverable);
2788         return;
2789     }
2790 
2791     hci_stack->discoverable = enable;
2792     hci_update_scan_enable();
2793 }
2794 
2795 void gap_connectable_control(uint8_t enable){
2796     if (enable) enable = 1; // normalize argument
2797 
2798     // don't emit event
2799     if (hci_stack->connectable == enable) return;
2800 
2801     hci_stack->connectable = enable;
2802     hci_update_scan_enable();
2803 }
2804 #endif
2805 
2806 void gap_local_bd_addr(bd_addr_t address_buffer){
2807     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
2808 }
2809 
2810 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2811 static void hci_host_num_completed_packets(void){
2812 
2813     // create packet manually as arrays are not supported and num_commands should not get reduced
2814     hci_reserve_packet_buffer();
2815     uint8_t * packet = hci_get_outgoing_packet_buffer();
2816 
2817     uint16_t size = 0;
2818     uint16_t num_handles = 0;
2819     packet[size++] = 0x35;
2820     packet[size++] = 0x0c;
2821     size++;  // skip param len
2822     size++;  // skip num handles
2823 
2824     // add { handle, packets } entries
2825     btstack_linked_item_t * it;
2826     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
2827         hci_connection_t * connection = (hci_connection_t *) it;
2828         if (connection->num_packets_completed){
2829             little_endian_store_16(packet, size, connection->con_handle);
2830             size += 2;
2831             little_endian_store_16(packet, size, connection->num_packets_completed);
2832             size += 2;
2833             //
2834             num_handles++;
2835             connection->num_packets_completed = 0;
2836         }
2837     }
2838 
2839     packet[2] = size - 3;
2840     packet[3] = num_handles;
2841 
2842     hci_stack->host_completed_packets = 0;
2843 
2844     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2845     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2846 
2847     // release packet buffer for synchronous transport implementations
2848     if (hci_transport_synchronous()){
2849         hci_stack->hci_packet_buffer_reserved = 0;
2850     }
2851 }
2852 #endif
2853 
2854 static void hci_run(void){
2855 
2856     // log_info("hci_run: entered");
2857     btstack_linked_item_t * it;
2858 
2859     // send continuation fragments first, as they block the prepared packet buffer
2860     if (hci_stack->acl_fragmentation_total_size > 0) {
2861         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2862         hci_connection_t *connection = hci_connection_for_handle(con_handle);
2863         if (connection) {
2864             if (hci_can_send_prepared_acl_packet_now(con_handle)){
2865                 hci_send_acl_packet_fragments(connection);
2866                 return;
2867             }
2868         } else {
2869             // connection gone -> discard further fragments
2870             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
2871             hci_stack->acl_fragmentation_total_size = 0;
2872             hci_stack->acl_fragmentation_pos = 0;
2873         }
2874     }
2875 
2876 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2877     // send host num completed packets next as they don't require num_cmd_packets > 0
2878     if (!hci_can_send_comand_packet_transport()) return;
2879     if (hci_stack->host_completed_packets){
2880         hci_host_num_completed_packets();
2881         return;
2882     }
2883 #endif
2884 
2885     if (!hci_can_send_command_packet_now()) return;
2886 
2887     // global/non-connection oriented commands
2888 
2889 #ifdef ENABLE_CLASSIC
2890     // decline incoming connections
2891     if (hci_stack->decline_reason){
2892         uint8_t reason = hci_stack->decline_reason;
2893         hci_stack->decline_reason = 0;
2894         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2895         return;
2896     }
2897     // send scan enable
2898     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
2899         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
2900         hci_stack->new_scan_enable_value = 0xff;
2901         return;
2902     }
2903     // start/stop inquiry
2904     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX){
2905         uint8_t duration = hci_stack->inquiry_state;
2906         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2907         hci_send_cmd(&hci_inquiry, HCI_INQUIRY_LAP, duration, 0);
2908         return;
2909     }
2910     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
2911         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
2912         hci_send_cmd(&hci_inquiry_cancel);
2913         return;
2914     }
2915     // remote name request
2916     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
2917         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
2918         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
2919             hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
2920         return;
2921     }
2922     // pairing
2923     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
2924         uint8_t state = hci_stack->gap_pairing_state;
2925         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
2926         switch (state){
2927             case GAP_PAIRING_STATE_SEND_PIN:
2928                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, strlen(hci_stack->gap_pairing_pin), hci_stack->gap_pairing_pin);
2929                 break;
2930             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
2931                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
2932                 break;
2933             case GAP_PAIRING_STATE_SEND_PASSKEY:
2934                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_passkey);
2935                 break;
2936             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
2937                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
2938                 break;
2939             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
2940                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
2941                 break;
2942             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
2943                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
2944                 break;
2945             default:
2946                 break;
2947         }
2948         return;
2949     }
2950 #endif
2951 
2952 #ifdef ENABLE_BLE
2953     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
2954     if ((hci_stack->state == HCI_STATE_WORKING)
2955     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
2956 
2957 #ifdef ENABLE_LE_CENTRAL
2958         // handle le scan
2959         switch(hci_stack->le_scanning_state){
2960             case LE_START_SCAN:
2961                 hci_stack->le_scanning_state = LE_SCANNING;
2962                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
2963                 return;
2964 
2965             case LE_STOP_SCAN:
2966                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
2967                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
2968                 return;
2969             default:
2970                 break;
2971         }
2972         if (hci_stack->le_scan_type != 0xff){
2973             // defaults: active scanning, accept all advertisement packets
2974             int scan_type = hci_stack->le_scan_type;
2975             hci_stack->le_scan_type = 0xff;
2976             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);
2977             return;
2978         }
2979 #endif
2980 #ifdef ENABLE_LE_PERIPHERAL
2981         // le advertisement control
2982         if (hci_stack->le_advertisements_todo){
2983             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
2984         }
2985         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
2986             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
2987             hci_send_cmd(&hci_le_set_advertise_enable, 0);
2988             return;
2989         }
2990         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
2991             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
2992             hci_send_cmd(&hci_le_set_advertising_parameters,
2993                  hci_stack->le_advertisements_interval_min,
2994                  hci_stack->le_advertisements_interval_max,
2995                  hci_stack->le_advertisements_type,
2996                  hci_stack->le_own_addr_type,
2997                  hci_stack->le_advertisements_direct_address_type,
2998                  hci_stack->le_advertisements_direct_address,
2999                  hci_stack->le_advertisements_channel_map,
3000                  hci_stack->le_advertisements_filter_policy);
3001             return;
3002         }
3003         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3004             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3005             uint8_t adv_data_clean[31];
3006             memset(adv_data_clean, 0, sizeof(adv_data_clean));
3007             memcpy(adv_data_clean, hci_stack->le_advertisements_data, hci_stack->le_advertisements_data_len);
3008             hci_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len);
3009             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3010             return;
3011         }
3012         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3013             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3014             uint8_t scan_data_clean[31];
3015             memset(scan_data_clean, 0, sizeof(scan_data_clean));
3016             memcpy(scan_data_clean, hci_stack->le_scan_response_data, hci_stack->le_scan_response_data_len);
3017             hci_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len);
3018             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, hci_stack->le_scan_response_data);
3019             return;
3020         }
3021         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
3022             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
3023             hci_send_cmd(&hci_le_set_advertise_enable, 1);
3024             return;
3025         }
3026 #endif
3027 
3028 #ifdef ENABLE_LE_CENTRAL
3029         //
3030         // LE Whitelist Management
3031         //
3032 
3033         // check if whitelist needs modification
3034         btstack_linked_list_iterator_t lit;
3035         int modification_pending = 0;
3036         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3037         while (btstack_linked_list_iterator_has_next(&lit)){
3038             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3039             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3040                 modification_pending = 1;
3041                 break;
3042             }
3043         }
3044 
3045         if (modification_pending){
3046             // stop connnecting if modification pending
3047             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
3048                 hci_send_cmd(&hci_le_create_connection_cancel);
3049                 return;
3050             }
3051 
3052             // add/remove entries
3053             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3054             while (btstack_linked_list_iterator_has_next(&lit)){
3055                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3056                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
3057                     entry->state = LE_WHITELIST_ON_CONTROLLER;
3058                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3059                     return;
3060 
3061                 }
3062                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
3063                     bd_addr_t address;
3064                     bd_addr_type_t address_type = entry->address_type;
3065                     memcpy(address, entry->address, 6);
3066                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3067                     btstack_memory_whitelist_entry_free(entry);
3068                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
3069                     return;
3070                 }
3071             }
3072         }
3073 
3074         // start connecting
3075         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
3076             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
3077             bd_addr_t null_addr;
3078             memset(null_addr, 0, 6);
3079             hci_send_cmd(&hci_le_create_connection,
3080                  0x0060,    // scan interval: 60 ms
3081                  0x0030,    // scan interval: 30 ms
3082                  1,         // use whitelist
3083                  0,         // peer address type
3084                  null_addr, // peer bd addr
3085                  hci_stack->le_own_addr_type, // our addr type:
3086                  hci_stack->le_connection_interval_min,    // conn interval min
3087                  hci_stack->le_connection_interval_max,    // conn interval max
3088                  hci_stack->le_connection_latency,         // conn latency
3089                  hci_stack->le_supervision_timeout,        // conn latency
3090                  hci_stack->le_minimum_ce_length,          // min ce length
3091                  hci_stack->le_maximum_ce_length           // max ce length
3092                 );
3093             return;
3094         }
3095 #endif
3096     }
3097 #endif
3098 
3099     // send pending HCI commands
3100     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3101         hci_connection_t * connection = (hci_connection_t *) it;
3102 
3103         switch(connection->state){
3104             case SEND_CREATE_CONNECTION:
3105                 switch(connection->address_type){
3106 #ifdef ENABLE_CLASSIC
3107                     case BD_ADDR_TYPE_CLASSIC:
3108                         log_info("sending hci_create_connection");
3109                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
3110                         break;
3111 #endif
3112                     default:
3113 #ifdef ENABLE_BLE
3114 #ifdef ENABLE_LE_CENTRAL
3115                         log_info("sending hci_le_create_connection");
3116                         hci_send_cmd(&hci_le_create_connection,
3117                              0x0060,    // scan interval: 60 ms
3118                              0x0030,    // scan interval: 30 ms
3119                              0,         // don't use whitelist
3120                              connection->address_type, // peer address type
3121                              connection->address,      // peer bd addr
3122                              hci_stack->le_own_addr_type, // our addr type:
3123                              hci_stack->le_connection_interval_min,    // conn interval min
3124                              hci_stack->le_connection_interval_max,    // conn interval max
3125                              hci_stack->le_connection_latency,         // conn latency
3126                              hci_stack->le_supervision_timeout,        // conn latency
3127                              hci_stack->le_minimum_ce_length,          // min ce length
3128                              hci_stack->le_maximum_ce_length          // max ce length
3129                              );
3130                         connection->state = SENT_CREATE_CONNECTION;
3131 #endif
3132 #endif
3133                         break;
3134                 }
3135                 return;
3136 
3137 #ifdef ENABLE_CLASSIC
3138             case RECEIVED_CONNECTION_REQUEST:
3139                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
3140                 connection->state = ACCEPTED_CONNECTION_REQUEST;
3141                 connection->role  = HCI_ROLE_SLAVE;
3142                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
3143                     hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
3144                 }
3145                 return;
3146 #endif
3147 
3148 #ifdef ENABLE_BLE
3149 #ifdef ENABLE_LE_CENTRAL
3150             case SEND_CANCEL_CONNECTION:
3151                 connection->state = SENT_CANCEL_CONNECTION;
3152                 hci_send_cmd(&hci_le_create_connection_cancel);
3153                 return;
3154 #endif
3155 #endif
3156             case SEND_DISCONNECT:
3157                 connection->state = SENT_DISCONNECT;
3158                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
3159                 return;
3160 
3161             default:
3162                 break;
3163         }
3164 
3165 #ifdef ENABLE_CLASSIC
3166         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
3167             log_info("responding to link key request");
3168             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
3169             link_key_t link_key;
3170             link_key_type_t link_key_type;
3171             if ( hci_stack->link_key_db
3172               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
3173               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
3174                connection->link_key_type = link_key_type;
3175                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
3176             } else {
3177                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
3178             }
3179             return;
3180         }
3181 
3182         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
3183             log_info("denying to pin request");
3184             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
3185             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
3186             return;
3187         }
3188 
3189         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
3190             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
3191             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
3192             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3193                 // tweak authentication requirements
3194                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3195                 if (connection->bonding_flags & BONDING_DEDICATED){
3196                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3197                 }
3198                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
3199                     authreq |= 1;
3200                 }
3201                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3202             } else {
3203                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3204             }
3205             return;
3206         }
3207 
3208         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3209             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
3210             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3211             return;
3212         }
3213 
3214         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3215             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
3216             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3217             return;
3218         }
3219 
3220         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
3221             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
3222             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3223             return;
3224         }
3225 
3226         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3227             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
3228             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
3229             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
3230             return;
3231         }
3232 
3233         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
3234             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3235             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3236             return;
3237         }
3238 
3239         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3240             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3241             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3242             return;
3243         }
3244 #endif
3245 
3246         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
3247             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
3248             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
3249             return;
3250         }
3251 
3252 #ifdef ENABLE_BLE
3253         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
3254             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3255 
3256             uint16_t connection_interval_min = connection->le_conn_interval_min;
3257             connection->le_conn_interval_min = 0;
3258             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
3259                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3260                 0x0000, 0xffff);
3261         }
3262 #endif
3263     }
3264 
3265     hci_connection_t * connection;
3266     switch (hci_stack->state){
3267         case HCI_STATE_INITIALIZING:
3268             hci_initializing_run();
3269             break;
3270 
3271         case HCI_STATE_HALTING:
3272 
3273             log_info("HCI_STATE_HALTING");
3274 
3275             // free whitelist entries
3276 #ifdef ENABLE_BLE
3277 #ifdef ENABLE_LE_CENTRAL
3278             {
3279                 btstack_linked_list_iterator_t lit;
3280                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3281                 while (btstack_linked_list_iterator_has_next(&lit)){
3282                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3283                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3284                     btstack_memory_whitelist_entry_free(entry);
3285                 }
3286             }
3287 #endif
3288 #endif
3289             // close all open connections
3290             connection =  (hci_connection_t *) hci_stack->connections;
3291             if (connection){
3292                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
3293                 if (!hci_can_send_command_packet_now()) return;
3294 
3295                 // check state
3296                 if (connection->state == SENT_DISCONNECT) return;
3297                 connection->state = SENT_DISCONNECT;
3298 
3299                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
3300 
3301                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
3302                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
3303 
3304                 // ... which would be ignored anyway as we shutdown (free) the connection now
3305                 hci_shutdown_connection(connection);
3306 
3307                 // finally, send the disconnect command
3308                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
3309                 return;
3310             }
3311             log_info("HCI_STATE_HALTING, calling off");
3312 
3313             // switch mode
3314             hci_power_control_off();
3315 
3316             log_info("HCI_STATE_HALTING, emitting state");
3317             hci_emit_state();
3318             log_info("HCI_STATE_HALTING, done");
3319             break;
3320 
3321         case HCI_STATE_FALLING_ASLEEP:
3322             switch(hci_stack->substate) {
3323                 case HCI_FALLING_ASLEEP_DISCONNECT:
3324                     log_info("HCI_STATE_FALLING_ASLEEP");
3325                     // close all open connections
3326                     connection =  (hci_connection_t *) hci_stack->connections;
3327 
3328 #ifdef HAVE_PLATFORM_IPHONE_OS
3329                     // don't close connections, if H4 supports power management
3330                     if (btstack_control_iphone_power_management_enabled()){
3331                         connection = NULL;
3332                     }
3333 #endif
3334                     if (connection){
3335 
3336                         // send disconnect
3337                         if (!hci_can_send_command_packet_now()) return;
3338 
3339                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3340                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3341 
3342                         // send disconnected event right away - causes higher layer connections to get closed, too.
3343                         hci_shutdown_connection(connection);
3344                         return;
3345                     }
3346 
3347                     if (hci_classic_supported()){
3348                         // disable page and inquiry scan
3349                         if (!hci_can_send_command_packet_now()) return;
3350 
3351                         log_info("HCI_STATE_HALTING, disabling inq scans");
3352                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3353 
3354                         // continue in next sub state
3355                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3356                         break;
3357                     }
3358                     // no break - fall through for ble-only chips
3359 
3360                 case HCI_FALLING_ASLEEP_COMPLETE:
3361                     log_info("HCI_STATE_HALTING, calling sleep");
3362 #ifdef HAVE_PLATFORM_IPHONE_OS
3363                     // don't actually go to sleep, if H4 supports power management
3364                     if (btstack_control_iphone_power_management_enabled()){
3365                         // SLEEP MODE reached
3366                         hci_stack->state = HCI_STATE_SLEEPING;
3367                         hci_emit_state();
3368                         break;
3369                     }
3370 #endif
3371                     // switch mode
3372                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3373                     hci_emit_state();
3374                     break;
3375 
3376                 default:
3377                     break;
3378             }
3379             break;
3380 
3381         default:
3382             break;
3383     }
3384 }
3385 
3386 int hci_send_cmd_packet(uint8_t *packet, int size){
3387     // house-keeping
3388 
3389     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3390         hci_stack->loopback_mode = packet[3];
3391     }
3392 
3393 #ifdef ENABLE_CLASSIC
3394     bd_addr_t addr;
3395     hci_connection_t * conn;
3396 
3397     // create_connection?
3398     if (IS_COMMAND(packet, hci_create_connection)){
3399         reverse_bd_addr(&packet[3], addr);
3400         log_info("Create_connection to %s", bd_addr_to_str(addr));
3401 
3402         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3403         if (!conn){
3404             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3405             if (!conn){
3406                 // notify client that alloc failed
3407                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3408                 return 0; // don't sent packet to controller
3409             }
3410             conn->state = SEND_CREATE_CONNECTION;
3411         }
3412         log_info("conn state %u", conn->state);
3413         switch (conn->state){
3414             // if connection active exists
3415             case OPEN:
3416                 // and OPEN, emit connection complete command, don't send to controller
3417                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3418                 return 0;
3419             case SEND_CREATE_CONNECTION:
3420                 // connection created by hci, e.g. dedicated bonding
3421                 break;
3422             default:
3423                 // otherwise, just ignore as it is already in the open process
3424                 return 0;
3425         }
3426         conn->state = SENT_CREATE_CONNECTION;
3427     }
3428 
3429     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3430         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3431     }
3432     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3433         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3434     }
3435 
3436     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3437         if (hci_stack->link_key_db){
3438             reverse_bd_addr(&packet[3], addr);
3439             hci_stack->link_key_db->delete_link_key(addr);
3440         }
3441     }
3442 
3443     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3444     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3445         reverse_bd_addr(&packet[3], addr);
3446         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3447         if (conn){
3448             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3449         }
3450     }
3451 
3452     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3453     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3454     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3455     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3456         reverse_bd_addr(&packet[3], addr);
3457         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3458         if (conn){
3459             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3460         }
3461     }
3462 
3463 #ifdef ENABLE_SCO_OVER_HCI
3464     // setup_synchronous_connection? Voice setting at offset 22
3465     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3466         // TODO: compare to current setting if sco connection already active
3467         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3468     }
3469     // accept_synchronus_connection? Voice setting at offset 18
3470     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3471         // TODO: compare to current setting if sco connection already active
3472         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3473     }
3474 #endif
3475 #endif
3476 
3477 #ifdef ENABLE_BLE
3478 #ifdef ENABLE_LE_PERIPHERAL
3479     if (IS_COMMAND(packet, hci_le_set_random_address)){
3480         hci_stack->le_random_address_set = 1;
3481         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3482     }
3483     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3484         hci_stack->le_advertisements_active = packet[3];
3485     }
3486 #endif
3487 #ifdef ENABLE_LE_CENTRAL
3488     if (IS_COMMAND(packet, hci_le_create_connection)){
3489         // white list used?
3490         uint8_t initiator_filter_policy = packet[7];
3491         switch (initiator_filter_policy){
3492             case 0:
3493                 // whitelist not used
3494                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3495                 break;
3496             case 1:
3497                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3498                 break;
3499             default:
3500                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3501                 break;
3502         }
3503     }
3504     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3505         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3506     }
3507 #endif
3508 #endif
3509 
3510     hci_stack->num_cmd_packets--;
3511 
3512     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3513     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3514 
3515     // release packet buffer for synchronous transport implementations
3516     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
3517         hci_stack->hci_packet_buffer_reserved = 0;
3518     }
3519 
3520     return err;
3521 }
3522 
3523 // disconnect because of security block
3524 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3525     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3526     if (!connection) return;
3527     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3528 }
3529 
3530 
3531 // Configure Secure Simple Pairing
3532 
3533 #ifdef ENABLE_CLASSIC
3534 
3535 // enable will enable SSP during init
3536 void gap_ssp_set_enable(int enable){
3537     hci_stack->ssp_enable = enable;
3538 }
3539 
3540 static int hci_local_ssp_activated(void){
3541     return gap_ssp_supported() && hci_stack->ssp_enable;
3542 }
3543 
3544 // if set, BTstack will respond to io capability request using authentication requirement
3545 void gap_ssp_set_io_capability(int io_capability){
3546     hci_stack->ssp_io_capability = io_capability;
3547 }
3548 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3549     hci_stack->ssp_authentication_requirement = authentication_requirement;
3550 }
3551 
3552 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3553 void gap_ssp_set_auto_accept(int auto_accept){
3554     hci_stack->ssp_auto_accept = auto_accept;
3555 }
3556 #endif
3557 
3558 // va_list part of hci_send_cmd
3559 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3560     if (!hci_can_send_command_packet_now()){
3561         log_error("hci_send_cmd called but cannot send packet now");
3562         return 0;
3563     }
3564 
3565     // for HCI INITIALIZATION
3566     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3567     hci_stack->last_cmd_opcode = cmd->opcode;
3568 
3569     hci_reserve_packet_buffer();
3570     uint8_t * packet = hci_stack->hci_packet_buffer;
3571     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3572     return hci_send_cmd_packet(packet, size);
3573 }
3574 
3575 /**
3576  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3577  */
3578 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3579     va_list argptr;
3580     va_start(argptr, cmd);
3581     int res = hci_send_cmd_va_arg(cmd, argptr);
3582     va_end(argptr);
3583     return res;
3584 }
3585 
3586 // Create various non-HCI events.
3587 // TODO: generalize, use table similar to hci_create_command
3588 
3589 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3590     // dump packet
3591     if (dump) {
3592         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3593     }
3594 
3595     // dispatch to all event handlers
3596     btstack_linked_list_iterator_t it;
3597     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3598     while (btstack_linked_list_iterator_has_next(&it)){
3599         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3600         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3601     }
3602 }
3603 
3604 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3605     if (!hci_stack->acl_packet_handler) return;
3606     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3607 }
3608 
3609 #ifdef ENABLE_CLASSIC
3610 static void hci_notify_if_sco_can_send_now(void){
3611     // notify SCO sender if waiting
3612     if (!hci_stack->sco_waiting_for_can_send_now) return;
3613     if (hci_can_send_sco_packet_now()){
3614         hci_stack->sco_waiting_for_can_send_now = 0;
3615         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3616         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3617         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3618     }
3619 }
3620 
3621 // parsing end emitting has been merged to reduce code size
3622 static void gap_inquiry_explode(uint8_t * packet){
3623     uint8_t event[15+GAP_INQUIRY_MAX_NAME_LEN];
3624 
3625     uint8_t * eir_data;
3626     ad_context_t context;
3627     const uint8_t * name;
3628     uint8_t         name_len;
3629 
3630     int event_type = hci_event_packet_get_type(packet);
3631     int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1;    // 2 for old event, 1 otherwise
3632     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
3633 
3634     // event[1] is set at the end
3635     int i;
3636     for (i=0; i<num_responses;i++){
3637         memset(event, 0, sizeof(event));
3638         event[0] = GAP_EVENT_INQUIRY_RESULT;
3639         uint8_t event_size = 18;    // if name is not set by EIR
3640 
3641         memcpy(&event[2],  &packet[3 +                                             i*6], 6); // bd_addr
3642         event[8] =          packet[3 + num_responses*(6)                         + i*1];     // page_scan_repetition_mode
3643         memcpy(&event[9],  &packet[3 + num_responses*(6+1+num_reserved_fields)   + i*3], 3); // class of device
3644         memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset
3645 
3646         switch (event_type){
3647             case HCI_EVENT_INQUIRY_RESULT:
3648                 // 14,15,16,17 = 0, size 18
3649                 break;
3650             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3651                 event[14] = 1;
3652                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3653                 // 16,17 = 0, size 18
3654                 break;
3655             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3656                 event[14] = 1;
3657                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3658                 // for EIR packets, there is only one reponse in it
3659                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
3660                 name = NULL;
3661                 // EIR data is 240 bytes in EIR event
3662                 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
3663                     uint8_t data_type    = ad_iterator_get_data_type(&context);
3664                     uint8_t data_size    = ad_iterator_get_data_len(&context);
3665                     const uint8_t * data = ad_iterator_get_data(&context);
3666                     // Prefer Complete Local Name over Shortend Local Name
3667                     switch (data_type){
3668                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
3669                             if (name) continue;
3670                             /* explicit fall-through */
3671                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
3672                             name = data;
3673                             name_len = data_size;
3674                             break;
3675                         default:
3676                             break;
3677                     }
3678                 }
3679                 if (name){
3680                     event[16] = 1;
3681                     // truncate name if needed
3682                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
3683                     event[17] = len;
3684                     memcpy(&event[18], name, len);
3685                     event_size += len;
3686                 }
3687                 break;
3688         }
3689         event[1] = event_size - 2;
3690         hci_emit_event(event, event_size, 1);
3691     }
3692 }
3693 #endif
3694 
3695 void hci_emit_state(void){
3696     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3697     uint8_t event[3];
3698     event[0] = BTSTACK_EVENT_STATE;
3699     event[1] = sizeof(event) - 2;
3700     event[2] = hci_stack->state;
3701     hci_emit_event(event, sizeof(event), 1);
3702 }
3703 
3704 #ifdef ENABLE_CLASSIC
3705 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3706     uint8_t event[13];
3707     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3708     event[1] = sizeof(event) - 2;
3709     event[2] = status;
3710     little_endian_store_16(event, 3, con_handle);
3711     reverse_bd_addr(address, &event[5]);
3712     event[11] = 1; // ACL connection
3713     event[12] = 0; // encryption disabled
3714     hci_emit_event(event, sizeof(event), 1);
3715 }
3716 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3717     if (disable_l2cap_timeouts) return;
3718     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3719     uint8_t event[4];
3720     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3721     event[1] = sizeof(event) - 2;
3722     little_endian_store_16(event, 2, conn->con_handle);
3723     hci_emit_event(event, sizeof(event), 1);
3724 }
3725 #endif
3726 
3727 #ifdef ENABLE_BLE
3728 #ifdef ENABLE_LE_CENTRAL
3729 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3730     uint8_t event[21];
3731     event[0] = HCI_EVENT_LE_META;
3732     event[1] = sizeof(event) - 2;
3733     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
3734     event[3] = status;
3735     little_endian_store_16(event, 4, con_handle);
3736     event[6] = 0; // TODO: role
3737     event[7] = address_type;
3738     reverse_bd_addr(address, &event[8]);
3739     little_endian_store_16(event, 14, 0); // interval
3740     little_endian_store_16(event, 16, 0); // latency
3741     little_endian_store_16(event, 18, 0); // supervision timeout
3742     event[20] = 0; // master clock accuracy
3743     hci_emit_event(event, sizeof(event), 1);
3744 }
3745 #endif
3746 #endif
3747 
3748 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
3749     uint8_t event[6];
3750     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
3751     event[1] = sizeof(event) - 2;
3752     event[2] = 0; // status = OK
3753     little_endian_store_16(event, 3, con_handle);
3754     event[5] = reason;
3755     hci_emit_event(event, sizeof(event), 1);
3756 }
3757 
3758 static void hci_emit_nr_connections_changed(void){
3759     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
3760     uint8_t event[3];
3761     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3762     event[1] = sizeof(event) - 2;
3763     event[2] = nr_hci_connections();
3764     hci_emit_event(event, sizeof(event), 1);
3765 }
3766 
3767 static void hci_emit_hci_open_failed(void){
3768     log_info("BTSTACK_EVENT_POWERON_FAILED");
3769     uint8_t event[2];
3770     event[0] = BTSTACK_EVENT_POWERON_FAILED;
3771     event[1] = sizeof(event) - 2;
3772     hci_emit_event(event, sizeof(event), 1);
3773 }
3774 
3775 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
3776     log_info("hci_emit_dedicated_bonding_result %u ", status);
3777     uint8_t event[9];
3778     int pos = 0;
3779     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
3780     event[pos++] = sizeof(event) - 2;
3781     event[pos++] = status;
3782     reverse_bd_addr(address, &event[pos]);
3783     hci_emit_event(event, sizeof(event), 1);
3784 }
3785 
3786 
3787 #ifdef ENABLE_CLASSIC
3788 
3789 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3790     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3791     uint8_t event[5];
3792     int pos = 0;
3793     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3794     event[pos++] = sizeof(event) - 2;
3795     little_endian_store_16(event, 2, con_handle);
3796     pos += 2;
3797     event[pos++] = level;
3798     hci_emit_event(event, sizeof(event), 1);
3799 }
3800 
3801 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
3802     if (!connection) return LEVEL_0;
3803     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
3804     return gap_security_level_for_link_key_type(connection->link_key_type);
3805 }
3806 
3807 static void hci_emit_discoverable_enabled(uint8_t enabled){
3808     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
3809     uint8_t event[3];
3810     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
3811     event[1] = sizeof(event) - 2;
3812     event[2] = enabled;
3813     hci_emit_event(event, sizeof(event), 1);
3814 }
3815 
3816 #ifdef ENABLE_CLASSIC
3817 // query if remote side supports eSCO
3818 int hci_remote_esco_supported(hci_con_handle_t con_handle){
3819     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3820     if (!connection) return 0;
3821     return connection->remote_supported_feature_eSCO;
3822 }
3823 
3824 // query if remote side supports SSP
3825 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
3826     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3827     if (!connection) return 0;
3828     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
3829 }
3830 
3831 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
3832     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3833 }
3834 #endif
3835 
3836 // GAP API
3837 /**
3838  * @bbrief enable/disable bonding. default is enabled
3839  * @praram enabled
3840  */
3841 void gap_set_bondable_mode(int enable){
3842     hci_stack->bondable = enable ? 1 : 0;
3843 }
3844 /**
3845  * @brief Get bondable mode.
3846  * @return 1 if bondable
3847  */
3848 int gap_get_bondable_mode(void){
3849     return hci_stack->bondable;
3850 }
3851 
3852 /**
3853  * @brief map link keys to security levels
3854  */
3855 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
3856     switch (link_key_type){
3857         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
3858             return LEVEL_4;
3859         case COMBINATION_KEY:
3860         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
3861             return LEVEL_3;
3862         default:
3863             return LEVEL_2;
3864     }
3865 }
3866 
3867 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
3868     log_info("gap_mitm_protection_required_for_security_level %u", level);
3869     return level > LEVEL_2;
3870 }
3871 
3872 /**
3873  * @brief get current security level
3874  */
3875 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
3876     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3877     if (!connection) return LEVEL_0;
3878     return gap_security_level_for_connection(connection);
3879 }
3880 
3881 /**
3882  * @brief request connection to device to
3883  * @result GAP_AUTHENTICATION_RESULT
3884  */
3885 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
3886     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3887     if (!connection){
3888         hci_emit_security_level(con_handle, LEVEL_0);
3889         return;
3890     }
3891     gap_security_level_t current_level = gap_security_level(con_handle);
3892     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
3893     if (current_level >= requested_level){
3894         hci_emit_security_level(con_handle, current_level);
3895         return;
3896     }
3897 
3898     connection->requested_security_level = requested_level;
3899 
3900 #if 0
3901     // sending encryption request without a link key results in an error.
3902     // TODO: figure out how to use it properly
3903 
3904     // would enabling ecnryption suffice (>= LEVEL_2)?
3905     if (hci_stack->link_key_db){
3906         link_key_type_t link_key_type;
3907         link_key_t      link_key;
3908         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3909             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3910                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3911                 return;
3912             }
3913         }
3914     }
3915 #endif
3916 
3917     // try to authenticate connection
3918     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3919     hci_run();
3920 }
3921 
3922 /**
3923  * @brief start dedicated bonding with device. disconnect after bonding
3924  * @param device
3925  * @param request MITM protection
3926  * @result GAP_DEDICATED_BONDING_COMPLETE
3927  */
3928 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3929 
3930     // create connection state machine
3931     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3932 
3933     if (!connection){
3934         return BTSTACK_MEMORY_ALLOC_FAILED;
3935     }
3936 
3937     // delete linkn key
3938     gap_drop_link_key_for_bd_addr(device);
3939 
3940     // configure LEVEL_2/3, dedicated bonding
3941     connection->state = SEND_CREATE_CONNECTION;
3942     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
3943     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
3944     connection->bonding_flags = BONDING_DEDICATED;
3945 
3946     // wait for GAP Security Result and send GAP Dedicated Bonding complete
3947 
3948     // handle: connnection failure (connection complete != ok)
3949     // handle: authentication failure
3950     // handle: disconnect on done
3951 
3952     hci_run();
3953 
3954     return 0;
3955 }
3956 #endif
3957 
3958 void gap_set_local_name(const char * local_name){
3959     hci_stack->local_name = local_name;
3960 }
3961 
3962 
3963 #ifdef ENABLE_BLE
3964 
3965 #ifdef ENABLE_LE_CENTRAL
3966 void gap_start_scan(void){
3967     if (hci_stack->le_scanning_state == LE_SCANNING) return;
3968     hci_stack->le_scanning_state = LE_START_SCAN;
3969     hci_run();
3970 }
3971 
3972 void gap_stop_scan(void){
3973     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return;
3974     hci_stack->le_scanning_state = LE_STOP_SCAN;
3975     hci_run();
3976 }
3977 
3978 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
3979     hci_stack->le_scan_type     = scan_type;
3980     hci_stack->le_scan_interval = scan_interval;
3981     hci_stack->le_scan_window   = scan_window;
3982     hci_run();
3983 }
3984 
3985 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
3986     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3987     if (!conn){
3988         log_info("gap_connect: no connection exists yet, creating context");
3989         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3990         if (!conn){
3991             // notify client that alloc failed
3992             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3993             log_info("gap_connect: failed to alloc hci_connection_t");
3994             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
3995         }
3996         conn->state = SEND_CREATE_CONNECTION;
3997         log_info("gap_connect: send create connection next");
3998         hci_run();
3999         return 0;
4000     }
4001 
4002     if (!hci_is_le_connection(conn) ||
4003         conn->state == SEND_CREATE_CONNECTION ||
4004         conn->state == SENT_CREATE_CONNECTION) {
4005         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
4006         log_error("gap_connect: classic connection or connect is already being created");
4007         return GATT_CLIENT_IN_WRONG_STATE;
4008     }
4009 
4010     log_info("gap_connect: context exists with state %u", conn->state);
4011     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
4012     hci_run();
4013     return 0;
4014 }
4015 
4016 // @assumption: only a single outgoing LE Connection exists
4017 static hci_connection_t * gap_get_outgoing_connection(void){
4018     btstack_linked_item_t *it;
4019     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4020         hci_connection_t * conn = (hci_connection_t *) it;
4021         if (!hci_is_le_connection(conn)) continue;
4022         switch (conn->state){
4023             case SEND_CREATE_CONNECTION:
4024             case SENT_CREATE_CONNECTION:
4025                 return conn;
4026             default:
4027                 break;
4028         };
4029     }
4030     return NULL;
4031 }
4032 
4033 uint8_t gap_connect_cancel(void){
4034     hci_connection_t * conn = gap_get_outgoing_connection();
4035     if (!conn) return 0;
4036     switch (conn->state){
4037         case SEND_CREATE_CONNECTION:
4038             // skip sending create connection and emit event instead
4039             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
4040             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
4041             btstack_memory_hci_connection_free( conn );
4042             break;
4043         case SENT_CREATE_CONNECTION:
4044             // request to send cancel connection
4045             conn->state = SEND_CANCEL_CONNECTION;
4046             hci_run();
4047             break;
4048         default:
4049             break;
4050     }
4051     return 0;
4052 }
4053 #endif
4054 
4055 #ifdef ENABLE_LE_CENTRAL
4056 /**
4057  * @brief Set connection parameters for outgoing connections
4058  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
4059  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
4060  * @param conn_latency, default: 4
4061  * @param supervision_timeout (unit: 10ms), default: 720 ms
4062  * @param min_ce_length (unit: 0.625ms), default: 10 ms
4063  * @param max_ce_length (unit: 0.625ms), default: 30 ms
4064  */
4065 
4066 void gap_set_connection_parameters(uint16_t conn_interval_min, uint16_t conn_interval_max,
4067     uint16_t conn_latency, uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
4068     hci_stack->le_connection_interval_min = conn_interval_min;
4069     hci_stack->le_connection_interval_max = conn_interval_max;
4070     hci_stack->le_connection_latency = conn_latency;
4071     hci_stack->le_supervision_timeout = supervision_timeout;
4072     hci_stack->le_minimum_ce_length = min_ce_length;
4073     hci_stack->le_maximum_ce_length = max_ce_length;
4074 }
4075 #endif
4076 
4077 /**
4078  * @brief Updates the connection parameters for a given LE connection
4079  * @param handle
4080  * @param conn_interval_min (unit: 1.25ms)
4081  * @param conn_interval_max (unit: 1.25ms)
4082  * @param conn_latency
4083  * @param supervision_timeout (unit: 10ms)
4084  * @returns 0 if ok
4085  */
4086 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4087     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4088     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4089     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4090     connection->le_conn_interval_min = conn_interval_min;
4091     connection->le_conn_interval_max = conn_interval_max;
4092     connection->le_conn_latency = conn_latency;
4093     connection->le_supervision_timeout = supervision_timeout;
4094     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
4095     hci_run();
4096     return 0;
4097 }
4098 
4099 /**
4100  * @brief Request an update of the connection parameter for a given LE connection
4101  * @param handle
4102  * @param conn_interval_min (unit: 1.25ms)
4103  * @param conn_interval_max (unit: 1.25ms)
4104  * @param conn_latency
4105  * @param supervision_timeout (unit: 10ms)
4106  * @returns 0 if ok
4107  */
4108 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4109     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4110     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4111     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4112     connection->le_conn_interval_min = conn_interval_min;
4113     connection->le_conn_interval_max = conn_interval_max;
4114     connection->le_conn_latency = conn_latency;
4115     connection->le_supervision_timeout = supervision_timeout;
4116     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
4117     hci_run();
4118     return 0;
4119 }
4120 
4121 #ifdef ENABLE_LE_PERIPHERAL
4122 
4123 static void gap_advertisments_changed(void){
4124     // disable advertisements before updating adv, scan data, or adv params
4125     if (hci_stack->le_advertisements_active){
4126         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
4127     }
4128     hci_run();
4129 }
4130 
4131 /**
4132  * @brief Set Advertisement Data
4133  * @param advertising_data_length
4134  * @param advertising_data (max 31 octets)
4135  * @note data is not copied, pointer has to stay valid
4136  */
4137 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
4138     hci_stack->le_advertisements_data_len = advertising_data_length;
4139     hci_stack->le_advertisements_data = advertising_data;
4140     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4141     gap_advertisments_changed();
4142 }
4143 
4144 /**
4145  * @brief Set Scan Response Data
4146  * @param advertising_data_length
4147  * @param advertising_data (max 31 octets)
4148  * @note data is not copied, pointer has to stay valid
4149  */
4150 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
4151     hci_stack->le_scan_response_data_len = scan_response_data_length;
4152     hci_stack->le_scan_response_data = scan_response_data;
4153     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4154     gap_advertisments_changed();
4155 }
4156 
4157 /**
4158  * @brief Set Advertisement Parameters
4159  * @param adv_int_min
4160  * @param adv_int_max
4161  * @param adv_type
4162  * @param direct_address_type
4163  * @param direct_address
4164  * @param channel_map
4165  * @param filter_policy
4166  *
4167  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
4168  */
4169  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4170     uint8_t direct_address_typ, bd_addr_t direct_address,
4171     uint8_t channel_map, uint8_t filter_policy) {
4172 
4173     hci_stack->le_advertisements_interval_min = adv_int_min;
4174     hci_stack->le_advertisements_interval_max = adv_int_max;
4175     hci_stack->le_advertisements_type = adv_type;
4176     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
4177     hci_stack->le_advertisements_channel_map = channel_map;
4178     hci_stack->le_advertisements_filter_policy = filter_policy;
4179     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
4180 
4181     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4182     gap_advertisments_changed();
4183  }
4184 
4185 /**
4186  * @brief Enable/Disable Advertisements
4187  * @param enabled
4188  */
4189 void gap_advertisements_enable(int enabled){
4190     hci_stack->le_advertisements_enabled = enabled;
4191     if (enabled && !hci_stack->le_advertisements_active){
4192         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
4193     }
4194     if (!enabled && hci_stack->le_advertisements_active){
4195         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
4196     }
4197     hci_run();
4198 }
4199 
4200 #endif
4201 
4202 void hci_le_set_own_address_type(uint8_t own_address_type){
4203     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
4204     if (own_address_type == hci_stack->le_own_addr_type) return;
4205     hci_stack->le_own_addr_type = own_address_type;
4206 
4207 #ifdef ENABLE_LE_PERIPHERAL
4208     // update advertisement parameters, too
4209     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4210     gap_advertisments_changed();
4211 #endif
4212 #ifdef ENABLE_LE_CENTRAL
4213     // note: we don't update scan parameters or modify ongoing connection attempts
4214 #endif
4215 }
4216 
4217 #endif
4218 
4219 uint8_t gap_disconnect(hci_con_handle_t handle){
4220     hci_connection_t * conn = hci_connection_for_handle(handle);
4221     if (!conn){
4222         hci_emit_disconnection_complete(handle, 0);
4223         return 0;
4224     }
4225     conn->state = SEND_DISCONNECT;
4226     hci_run();
4227     return 0;
4228 }
4229 
4230 /**
4231  * @brief Get connection type
4232  * @param con_handle
4233  * @result connection_type
4234  */
4235 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
4236     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4237     if (!conn) return GAP_CONNECTION_INVALID;
4238     switch (conn->address_type){
4239         case BD_ADDR_TYPE_LE_PUBLIC:
4240         case BD_ADDR_TYPE_LE_RANDOM:
4241             return GAP_CONNECTION_LE;
4242         case BD_ADDR_TYPE_SCO:
4243             return GAP_CONNECTION_SCO;
4244         case BD_ADDR_TYPE_CLASSIC:
4245             return GAP_CONNECTION_ACL;
4246         default:
4247             return GAP_CONNECTION_INVALID;
4248     }
4249 }
4250 
4251 #ifdef ENABLE_BLE
4252 
4253 #ifdef ENABLE_LE_CENTRAL
4254 /**
4255  * @brief Auto Connection Establishment - Start Connecting to device
4256  * @param address_typ
4257  * @param address
4258  * @returns 0 if ok
4259  */
4260 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
4261     // check capacity
4262     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
4263     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
4264     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
4265     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
4266     entry->address_type = address_type;
4267     memcpy(entry->address, address, 6);
4268     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4269     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
4270     hci_run();
4271     return 0;
4272 }
4273 
4274 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
4275     btstack_linked_list_iterator_t it;
4276     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4277     while (btstack_linked_list_iterator_has_next(&it)){
4278         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4279         if (entry->address_type != address_type) continue;
4280         if (memcmp(entry->address, address, 6) != 0) continue;
4281         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4282             // remove from controller if already present
4283             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4284             continue;
4285         }
4286         // direclty remove entry from whitelist
4287         btstack_linked_list_iterator_remove(&it);
4288         btstack_memory_whitelist_entry_free(entry);
4289     }
4290 }
4291 
4292 /**
4293  * @brief Auto Connection Establishment - Stop Connecting to device
4294  * @param address_typ
4295  * @param address
4296  * @returns 0 if ok
4297  */
4298 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
4299     hci_remove_from_whitelist(address_type, address);
4300     hci_run();
4301     return 0;
4302 }
4303 
4304 /**
4305  * @brief Auto Connection Establishment - Stop everything
4306  * @note  Convenience function to stop all active auto connection attempts
4307  */
4308 void gap_auto_connection_stop_all(void){
4309     btstack_linked_list_iterator_t it;
4310     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4311     while (btstack_linked_list_iterator_has_next(&it)){
4312         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4313         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4314             // remove from controller if already present
4315             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4316             continue;
4317         }
4318         // directly remove entry from whitelist
4319         btstack_linked_list_iterator_remove(&it);
4320         btstack_memory_whitelist_entry_free(entry);
4321     }
4322     hci_run();
4323 }
4324 #endif
4325 #endif
4326 
4327 #ifdef ENABLE_CLASSIC
4328 /**
4329  * @brief Set Extended Inquiry Response data
4330  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
4331  * @note has to be done before stack starts up
4332  */
4333 void gap_set_extended_inquiry_response(const uint8_t * data){
4334     hci_stack->eir_data = data;
4335 }
4336 
4337 /**
4338  * @brief Start GAP Classic Inquiry
4339  * @param duration in 1.28s units
4340  * @return 0 if ok
4341  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
4342  */
4343 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
4344     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4345     if (duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN || duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX){
4346         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
4347     }
4348     hci_stack->inquiry_state = duration_in_1280ms_units;
4349     hci_run();
4350     return 0;
4351 }
4352 
4353 /**
4354  * @brief Stop GAP Classic Inquiry
4355  * @returns 0 if ok
4356  */
4357 int gap_inquiry_stop(void){
4358     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN || hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX) {
4359         // emit inquiry complete event, before it even started
4360         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
4361         hci_emit_event(event, sizeof(event), 1);
4362         return 0;
4363     }
4364     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
4365     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
4366     hci_run();
4367     return 0;
4368 }
4369 
4370 
4371 /**
4372  * @brief Remote Name Request
4373  * @param addr
4374  * @param page_scan_repetition_mode
4375  * @param clock_offset only used when bit 15 is set
4376  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
4377  */
4378 int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
4379     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4380     memcpy(hci_stack->remote_name_addr, addr, 6);
4381     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
4382     hci_stack->remote_name_clock_offset = clock_offset;
4383     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
4384     hci_run();
4385     return 0;
4386 }
4387 
4388 static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){
4389     hci_stack->gap_pairing_state = state;
4390     memcpy(hci_stack->gap_pairing_addr, addr, 6);
4391     hci_run();
4392     return 0;
4393 }
4394 
4395 /**
4396  * @brief Legacy Pairing Pin Code Response
4397  * @param addr
4398  * @param pin
4399  * @return 0 if ok
4400  */
4401 int gap_pin_code_response(bd_addr_t addr, const char * pin){
4402     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4403     hci_stack->gap_pairing_pin = pin;
4404     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
4405 }
4406 
4407 /**
4408  * @brief Abort Legacy Pairing
4409  * @param addr
4410  * @param pin
4411  * @return 0 if ok
4412  */
4413 int gap_pin_code_negative(bd_addr_t addr){
4414     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4415     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
4416 }
4417 
4418 /**
4419  * @brief SSP Passkey Response
4420  * @param addr
4421  * @param passkey
4422  * @return 0 if ok
4423  */
4424 int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){
4425     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4426     hci_stack->gap_pairing_passkey = passkey;
4427     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
4428 }
4429 
4430 /**
4431  * @brief Abort SSP Passkey Entry/Pairing
4432  * @param addr
4433  * @param pin
4434  * @return 0 if ok
4435  */
4436 int gap_ssp_passkey_negative(bd_addr_t addr){
4437     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4438     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
4439 }
4440 
4441 /**
4442  * @brief Accept SSP Numeric Comparison
4443  * @param addr
4444  * @param passkey
4445  * @return 0 if ok
4446  */
4447 int gap_ssp_confirmation_response(bd_addr_t addr){
4448     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4449     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
4450 }
4451 
4452 /**
4453  * @brief Abort SSP Numeric Comparison/Pairing
4454  * @param addr
4455  * @param pin
4456  * @return 0 if ok
4457  */
4458 int gap_ssp_confirmation_negative(bd_addr_t addr){
4459     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4460     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
4461 }
4462 
4463 /**
4464  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
4465  * @param inquiry_mode see bluetooth_defines.h
4466  */
4467 void hci_set_inquiry_mode(inquiry_mode_t mode){
4468     hci_stack->inquiry_mode = mode;
4469 }
4470 
4471 /**
4472  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
4473  */
4474 void hci_set_sco_voice_setting(uint16_t voice_setting){
4475     hci_stack->sco_voice_setting = voice_setting;
4476 }
4477 
4478 /**
4479  * @brief Get SCO Voice Setting
4480  * @return current voice setting
4481  */
4482 uint16_t hci_get_sco_voice_setting(void){
4483     return hci_stack->sco_voice_setting;
4484 }
4485 
4486 /** @brief Get SCO packet length for current SCO Voice setting
4487  *  @note  Using SCO packets of the exact length is required for USB transfer
4488  *  @return Length of SCO packets in bytes (not audio frames)
4489  */
4490 int hci_get_sco_packet_length(void){
4491     // see Core Spec for H2 USB Transfer.
4492     if (hci_stack->sco_voice_setting & 0x0020) return 51;
4493     return 27;
4494 }
4495 #endif
4496 
4497 
4498 HCI_STATE hci_get_state(void){
4499     return hci_stack->state;
4500 }
4501 
4502 
4503 /**
4504  * @brief Set callback for Bluetooth Hardware Error
4505  */
4506 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
4507     hci_stack->hardware_error_callback = fn;
4508 }
4509 
4510 void hci_disconnect_all(void){
4511     btstack_linked_list_iterator_t it;
4512     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4513     while (btstack_linked_list_iterator_has_next(&it)){
4514         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4515         if (con->state == SENT_DISCONNECT) continue;
4516         con->state = SEND_DISCONNECT;
4517     }
4518     hci_run();
4519 }
4520 
4521 uint16_t hci_get_manufacturer(void){
4522     return hci_stack->manufacturer;
4523 }
4524