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