xref: /btstack/src/hci.c (revision 3bc639ce9b185765674d2ee07fb0ae3ed2d267a8)
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 /*
39  *  hci.c
40  *
41  *  Created by Matthias Ringwald on 4/29/09.
42  *
43  */
44 
45 #include "btstack_config.h"
46 
47 
48 #ifdef HAVE_TICK
49 #include "btstack_run_loop_embedded.h"
50 #endif
51 
52 #ifdef HAVE_PLATFORM_IPHONE_OS
53 #include "../port/ios/src/btstack_control_iphone.h"
54 #endif
55 
56 #ifdef ENABLE_BLE
57 #include "gap.h"
58 #endif
59 
60 #include <stdarg.h>
61 #include <string.h>
62 #include <stdio.h>
63 #include <inttypes.h>
64 
65 #include "btstack_debug.h"
66 #include "btstack_linked_list.h"
67 #include "btstack_memory.h"
68 #include "gap.h"
69 #include "hci.h"
70 #include "hci_cmd.h"
71 #include "hci_dump.h"
72 
73 
74 #define HCI_CONNECTION_TIMEOUT_MS 10000
75 
76 static void hci_update_scan_enable(void);
77 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
78 static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
79 static void hci_connection_timestamp(hci_connection_t *connection);
80 static int  hci_power_control_on(void);
81 static void hci_power_control_off(void);
82 static void hci_state_reset(void);
83 
84 #ifdef ENABLE_BLE
85 // called from test/ble_client/advertising_data_parser.c
86 void le_handle_advertisement_report(uint8_t *packet, int size);
87 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address);
88 #endif
89 
90 // prototypes
91 static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
92 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
93 
94 // the STACK is here
95 #ifndef HAVE_MALLOC
96 static hci_stack_t   hci_stack_static;
97 #endif
98 static hci_stack_t * hci_stack = NULL;
99 
100 // test helper
101 static uint8_t disable_l2cap_timeouts = 0;
102 
103 /**
104  * create connection for given address
105  *
106  * @return connection OR NULL, if no memory left
107  */
108 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
109     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
110     hci_connection_t * conn = btstack_memory_hci_connection_get();
111     if (!conn) return NULL;
112     memset(conn, 0, sizeof(hci_connection_t));
113     BD_ADDR_COPY(conn->address, addr);
114     conn->address_type = addr_type;
115     conn->con_handle = 0xffff;
116     conn->authentication_flags = AUTH_FLAGS_NONE;
117     conn->bonding_flags = 0;
118     conn->requested_security_level = LEVEL_0;
119     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
120     btstack_run_loop_set_timer_context(&conn->timeout, conn);
121     hci_connection_timestamp(conn);
122     conn->acl_recombination_length = 0;
123     conn->acl_recombination_pos = 0;
124     conn->num_acl_packets_sent = 0;
125     conn->num_sco_packets_sent = 0;
126     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
127     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
128     return conn;
129 }
130 
131 
132 /**
133  * get le connection parameter range
134 *
135  * @return le connection parameter range struct
136  */
137 void gap_le_get_connection_parameter_range(le_connection_parameter_range_t range){
138     range = hci_stack->le_connection_parameter_range;
139 }
140 
141 /**
142  * set le connection parameter range
143  *
144  */
145 
146 void gap_le_set_connection_parameter_range(le_connection_parameter_range_t range){
147     hci_stack->le_connection_parameter_range = range;
148 }
149 
150 /**
151  * get hci connections iterator
152  *
153  * @return hci connections iterator
154  */
155 
156 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
157     btstack_linked_list_iterator_init(it, &hci_stack->connections);
158 }
159 
160 /**
161  * get connection for a given handle
162  *
163  * @return connection OR NULL, if not found
164  */
165 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
166     btstack_linked_list_iterator_t it;
167     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
168     while (btstack_linked_list_iterator_has_next(&it)){
169         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
170         if ( item->con_handle == con_handle ) {
171             return item;
172         }
173     }
174     return NULL;
175 }
176 
177 /**
178  * get connection for given address
179  *
180  * @return connection OR NULL, if not found
181  */
182 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t  addr, bd_addr_type_t addr_type){
183     btstack_linked_list_iterator_t it;
184     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
185     while (btstack_linked_list_iterator_has_next(&it)){
186         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
187         if (connection->address_type != addr_type)  continue;
188         if (memcmp(addr, connection->address, 6) != 0) continue;
189         return connection;
190     }
191     return NULL;
192 }
193 
194 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
195     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
196 #ifdef HAVE_TIME
197     struct timeval tv;
198     gettimeofday(&tv, NULL);
199     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
200         // connections might be timed out
201         hci_emit_l2cap_check_timeout(connection);
202     }
203 #endif
204 #ifdef HAVE_TICK
205     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
206         // connections might be timed out
207         hci_emit_l2cap_check_timeout(connection);
208     }
209 #endif
210 #ifdef HAVE_TIME_MS
211     if (btstack_run_loop_get_time_ms() > connection->timestamp + HCI_CONNECTION_TIMEOUT_MS){
212         // connections might be timed out
213         hci_emit_l2cap_check_timeout(connection);
214     }
215 #endif
216     btstack_run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
217     btstack_run_loop_add_timer(timer);
218 }
219 
220 static void hci_connection_timestamp(hci_connection_t *connection){
221 #ifdef HAVE_TIME
222     gettimeofday(&connection->timestamp, NULL);
223 #endif
224 #ifdef HAVE_TICK
225     connection->timestamp = btstack_run_loop_embedded_get_ticks();
226 #endif
227 #ifdef HAVE_TIME_MS
228     connection->timestamp = btstack_run_loop_get_time_ms();
229 #endif
230 }
231 
232 
233 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
234     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
235 }
236 
237 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
238     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
239 }
240 
241 
242 /**
243  * add authentication flags and reset timer
244  * @note: assumes classic connection
245  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
246  */
247 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
248     bd_addr_t addr;
249     bt_flip_addr(addr, bd_addr);
250     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
251     if (conn) {
252         connectionSetAuthenticationFlags(conn, flags);
253         hci_connection_timestamp(conn);
254     }
255 }
256 
257 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
258     hci_connection_t * conn = hci_connection_for_handle(handle);
259     if (!conn) return 0;
260     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
261     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
262     return 0;
263 }
264 
265 void hci_drop_link_key_for_bd_addr(bd_addr_t addr){
266     if (hci_stack->link_key_db) {
267         hci_stack->link_key_db->delete_link_key(addr);
268     }
269 }
270 
271 int hci_is_le_connection(hci_connection_t * connection){
272     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
273     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
274 }
275 
276 
277 /**
278  * count connections
279  */
280 static int nr_hci_connections(void){
281     int count = 0;
282     btstack_linked_item_t *it;
283     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
284     return count;
285 }
286 
287 int hci_number_outgoing_packets(hci_con_handle_t handle){
288     hci_connection_t * connection = hci_connection_for_handle(handle);
289     if (!connection) {
290         log_error("hci_number_outgoing_packets: connection for handle %u does not exist!", handle);
291         return 0;
292     }
293     return connection->num_acl_packets_sent;
294 }
295 
296 int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
297 
298     int num_packets_sent_classic = 0;
299     int num_packets_sent_le = 0;
300 
301     btstack_linked_item_t *it;
302     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
303         hci_connection_t * connection = (hci_connection_t *) it;
304         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
305             num_packets_sent_classic += connection->num_acl_packets_sent;
306         } else {
307             num_packets_sent_le += connection->num_acl_packets_sent;
308         }
309     }
310 
311     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
312     int free_slots_le = 0;
313 
314     if (free_slots_classic < 0){
315         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);
316         return 0;
317     }
318 
319     if (hci_stack->le_acl_packets_total_num){
320         // if we have LE slots, they are used
321         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
322         if (free_slots_le < 0){
323             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);
324             return 0;
325         }
326     } else {
327         // otherwise, classic slots are used for LE, too
328         free_slots_classic -= num_packets_sent_le;
329         if (free_slots_classic < 0){
330             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);
331             return 0;
332         }
333     }
334 
335     switch (address_type){
336         case BD_ADDR_TYPE_UNKNOWN:
337             log_error("hci_number_free_acl_slots: unknown address type");
338             return 0;
339 
340         case BD_ADDR_TYPE_CLASSIC:
341             return free_slots_classic;
342 
343         default:
344            if (hci_stack->le_acl_packets_total_num){
345                return free_slots_le;
346            }
347            return free_slots_classic;
348     }
349 }
350 
351 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
352     // get connection type
353     hci_connection_t * connection = hci_connection_for_handle(con_handle);
354     if (!connection){
355         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
356         return 0;
357     }
358     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
359 }
360 
361 static int hci_number_free_sco_slots_for_handle(hci_con_handle_t handle){
362     int num_sco_packets_sent = 0;
363     btstack_linked_item_t *it;
364     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
365         hci_connection_t * connection = (hci_connection_t *) it;
366         num_sco_packets_sent += connection->num_sco_packets_sent;
367     }
368     if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
369         log_info("hci_number_free_sco_slots_for_handle: outgoing packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
370         return 0;
371     }
372     // log_info("hci_number_free_sco_slots_for_handle %x: sent %u", handle, num_sco_packets_sent);
373     return hci_stack->sco_packets_total_num - num_sco_packets_sent;
374 }
375 
376 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
377 int hci_can_send_command_packet_now(void){
378     if (hci_stack->hci_packet_buffer_reserved) return 0;
379 
380     // check for async hci transport implementations
381     if (hci_stack->hci_transport->can_send_packet_now){
382         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
383             return 0;
384         }
385     }
386 
387     return hci_stack->num_cmd_packets > 0;
388 }
389 
390 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
391     // check for async hci transport implementations
392     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
393     return hci_stack->hci_transport->can_send_packet_now(packet_type);
394 }
395 
396 static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
397     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
398     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
399 }
400 
401 int hci_can_send_acl_classic_packet_now(void){
402     if (hci_stack->hci_packet_buffer_reserved) return 0;
403     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_CLASSIC);
404 }
405 
406 int hci_can_send_acl_le_packet_now(void){
407     if (hci_stack->hci_packet_buffer_reserved) return 0;
408     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
409 }
410 
411 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
412     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
413     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
414 }
415 
416 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
417     if (hci_stack->hci_packet_buffer_reserved) return 0;
418     return hci_can_send_prepared_acl_packet_now(con_handle);
419 }
420 
421 int hci_can_send_prepared_sco_packet_now(hci_con_handle_t con_handle){
422     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) {
423         hci_stack->sco_waiting_for_can_send_now = 1;
424         return 0;
425     }
426     if (!hci_stack->synchronous_flow_control_enabled) return 1;
427     return hci_number_free_sco_slots_for_handle(con_handle) > 0;
428 }
429 
430 int hci_can_send_sco_packet_now(hci_con_handle_t con_handle){
431     if (hci_stack->hci_packet_buffer_reserved) {
432         hci_stack->sco_waiting_for_can_send_now = 1;
433         return 0;
434     }
435     return hci_can_send_prepared_sco_packet_now(con_handle);
436 }
437 
438 // used for internal checks in l2cap[-le].c
439 int hci_is_packet_buffer_reserved(void){
440     return hci_stack->hci_packet_buffer_reserved;
441 }
442 
443 // reserves outgoing packet buffer. @returns 1 if successful
444 int hci_reserve_packet_buffer(void){
445     if (hci_stack->hci_packet_buffer_reserved) {
446         log_error("hci_reserve_packet_buffer called but buffer already reserved");
447         return 0;
448     }
449     hci_stack->hci_packet_buffer_reserved = 1;
450     return 1;
451 }
452 
453 void hci_release_packet_buffer(void){
454     hci_stack->hci_packet_buffer_reserved = 0;
455 }
456 
457 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
458 static int hci_transport_synchronous(void){
459     return hci_stack->hci_transport->can_send_packet_now == NULL;
460 }
461 
462 uint16_t hci_max_acl_le_data_packet_length(void){
463     return hci_stack->le_data_packets_length > 0 ? hci_stack->le_data_packets_length : hci_stack->acl_data_packet_length;
464 }
465 
466 static int hci_send_acl_packet_fragments(hci_connection_t *connection){
467 
468     // 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);
469 
470     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
471     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
472     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
473         max_acl_data_packet_length = hci_stack->le_data_packets_length;
474     }
475 
476     // testing: reduce buffer to minimum
477     // max_acl_data_packet_length = 52;
478 
479     int err;
480     // multiple packets could be send on a synchronous HCI transport
481     while (1){
482 
483         // get current data
484         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
485         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
486         int more_fragments = 0;
487 
488         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
489         if (current_acl_data_packet_length > max_acl_data_packet_length){
490             more_fragments = 1;
491             current_acl_data_packet_length = max_acl_data_packet_length;
492         }
493 
494         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
495         if (acl_header_pos > 0){
496             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
497             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
498             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
499         }
500 
501         // update header len
502         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
503 
504         // count packet
505         connection->num_acl_packets_sent++;
506 
507         // send packet
508         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
509         const int size = current_acl_data_packet_length + 4;
510         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
511         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
512 
513         // done yet?
514         if (!more_fragments) break;
515 
516         // update start of next fragment to send
517         hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
518 
519         // can send more?
520         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
521     }
522 
523     // done
524     hci_stack->acl_fragmentation_pos = 0;
525     hci_stack->acl_fragmentation_total_size = 0;
526 
527     // release buffer now for synchronous transport
528     if (hci_transport_synchronous()){
529         hci_release_packet_buffer();
530         // notify upper stack that iit might be possible to send again
531         uint8_t event[] = { DAEMON_EVENT_HCI_PACKET_SENT, 0};
532         hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
533     }
534 
535     return err;
536 }
537 
538 // pre: caller has reserved the packet buffer
539 int hci_send_acl_packet_buffer(int size){
540 
541     // log_info("hci_send_acl_packet_buffer size %u", size);
542 
543     if (!hci_stack->hci_packet_buffer_reserved) {
544         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
545         return 0;
546     }
547 
548     uint8_t * packet = hci_stack->hci_packet_buffer;
549     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
550 
551     // check for free places on Bluetooth module
552     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
553         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
554         hci_release_packet_buffer();
555         return BTSTACK_ACL_BUFFERS_FULL;
556     }
557 
558     hci_connection_t *connection = hci_connection_for_handle( con_handle);
559     if (!connection) {
560         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
561         hci_release_packet_buffer();
562         return 0;
563     }
564     hci_connection_timestamp(connection);
565 
566     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
567 
568     // setup data
569     hci_stack->acl_fragmentation_total_size = size;
570     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
571 
572     return hci_send_acl_packet_fragments(connection);
573 }
574 
575 // pre: caller has reserved the packet buffer
576 int hci_send_sco_packet_buffer(int size){
577 
578     // log_info("hci_send_acl_packet_buffer size %u", size);
579 
580     if (!hci_stack->hci_packet_buffer_reserved) {
581         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
582         return 0;
583     }
584 
585     uint8_t * packet = hci_stack->hci_packet_buffer;
586 
587     // skip checks in loopback mode
588     if (!hci_stack->loopback_mode){
589         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
590 
591         // check for free places on Bluetooth module
592         if (!hci_can_send_prepared_sco_packet_now(con_handle)) {
593             log_error("hci_send_sco_packet_buffer called but no free ACL buffers on controller");
594             hci_release_packet_buffer();
595             return BTSTACK_ACL_BUFFERS_FULL;
596         }
597 
598         // track send packet in connection struct
599         hci_connection_t *connection = hci_connection_for_handle( con_handle);
600         if (!connection) {
601             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
602             hci_release_packet_buffer();
603             return 0;
604         }
605         connection->num_sco_packets_sent++;
606     }
607 
608     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
609     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
610 
611     if (hci_transport_synchronous()){
612         hci_release_packet_buffer();
613         // notify upper stack that iit might be possible to send again
614         uint8_t event[] = { DAEMON_EVENT_HCI_PACKET_SENT, 0};
615         hci_emit_event(&event[0], sizeof(event), 0);    // don't dump
616     }
617 
618     return err;
619 }
620 
621 static void acl_handler(uint8_t *packet, int size){
622 
623     // log_info("acl_handler: size %u", size);
624 
625     // get info
626     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
627     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
628     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
629     uint16_t acl_length         = READ_ACL_LENGTH(packet);
630 
631     // ignore non-registered handle
632     if (!conn){
633         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
634         return;
635     }
636 
637     // assert packet is complete
638     if (acl_length + 4 != size){
639         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
640         return;
641     }
642 
643     // update idle timestamp
644     hci_connection_timestamp(conn);
645 
646     // handle different packet types
647     switch (acl_flags & 0x03) {
648 
649         case 0x01: // continuation fragment
650 
651             // sanity checks
652             if (conn->acl_recombination_pos == 0) {
653                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
654                 return;
655             }
656             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
657                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
658                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
659                 conn->acl_recombination_pos = 0;
660                 return;
661             }
662 
663             // append fragment payload (header already stored)
664             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
665             conn->acl_recombination_pos += acl_length;
666 
667             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
668             //        conn->acl_recombination_pos, conn->acl_recombination_length);
669 
670             // forward complete L2CAP packet if complete.
671             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
672                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
673                 // reset recombination buffer
674                 conn->acl_recombination_length = 0;
675                 conn->acl_recombination_pos = 0;
676             }
677             break;
678 
679         case 0x02: { // first fragment
680 
681             // sanity check
682             if (conn->acl_recombination_pos) {
683                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
684                 conn->acl_recombination_pos = 0;
685             }
686 
687             // peek into L2CAP packet!
688             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
689 
690             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
691 
692             // compare fragment size to L2CAP packet size
693             if (acl_length >= l2cap_length + 4){
694                 // forward fragment as L2CAP packet
695                 hci_emit_acl_packet(packet, acl_length + 4);
696             } else {
697 
698                 if (acl_length > HCI_ACL_BUFFER_SIZE){
699                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
700                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
701                     return;
702                 }
703 
704                 // store first fragment and tweak acl length for complete package
705                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
706                 conn->acl_recombination_pos    = acl_length + 4;
707                 conn->acl_recombination_length = l2cap_length;
708                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
709             }
710             break;
711 
712         }
713         default:
714             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
715             return;
716     }
717 
718     // execute main loop
719     hci_run();
720 }
721 
722 static void hci_shutdown_connection(hci_connection_t *conn){
723     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
724 
725     btstack_run_loop_remove_timer(&conn->timeout);
726 
727     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
728     btstack_memory_hci_connection_free( conn );
729 
730     // now it's gone
731     hci_emit_nr_connections_changed();
732 }
733 
734 static const uint16_t packet_type_sizes[] = {
735     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
736     HCI_ACL_DH1_SIZE, 0, 0, 0,
737     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
738     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
739 };
740 static const uint8_t  packet_type_feature_requirement_bit[] = {
741      0, // 3 slot packets
742      1, // 5 slot packets
743     25, // EDR 2 mpbs
744     26, // EDR 3 mbps
745     39, // 3 slot EDR packts
746     40, // 5 slot EDR packet
747 };
748 static const uint16_t packet_type_feature_packet_mask[] = {
749     0x0f00, // 3 slot packets
750     0xf000, // 5 slot packets
751     0x1102, // EDR 2 mpbs
752     0x2204, // EDR 3 mbps
753     0x0300, // 3 slot EDR packts
754     0x3000, // 5 slot EDR packet
755 };
756 
757 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
758     // enable packet types based on size
759     uint16_t packet_types = 0;
760     unsigned int i;
761     for (i=0;i<16;i++){
762         if (packet_type_sizes[i] == 0) continue;
763         if (packet_type_sizes[i] <= buffer_size){
764             packet_types |= 1 << i;
765         }
766     }
767     // disable packet types due to missing local supported features
768     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
769         int bit_idx = packet_type_feature_requirement_bit[i];
770         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
771         if (feature_set) continue;
772         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
773         packet_types &= ~packet_type_feature_packet_mask[i];
774     }
775     // flip bits for "may not be used"
776     packet_types ^= 0x3306;
777     return packet_types;
778 }
779 
780 uint16_t hci_usable_acl_packet_types(void){
781     return hci_stack->packet_types;
782 }
783 
784 uint8_t* hci_get_outgoing_packet_buffer(void){
785     // hci packet buffer is >= acl data packet length
786     return hci_stack->hci_packet_buffer;
787 }
788 
789 uint16_t hci_max_acl_data_packet_length(void){
790     return hci_stack->acl_data_packet_length;
791 }
792 
793 int hci_non_flushable_packet_boundary_flag_supported(void){
794     // No. 54, byte 6, bit 6
795     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
796 }
797 
798 static int hci_ssp_supported(void){
799     // No. 51, byte 6, bit 3
800     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
801 }
802 
803 static int hci_classic_supported(void){
804     // No. 37, byte 4, bit 5, = No BR/EDR Support
805     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
806 }
807 
808 static int hci_le_supported(void){
809 #ifdef ENABLE_BLE
810     // No. 37, byte 4, bit 6 = LE Supported (Controller)
811     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
812 #else
813     return 0;
814 #endif
815 }
816 
817 // get addr type and address used in advertisement packets
818 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t  addr){
819     *addr_type = hci_stack->adv_addr_type;
820     if (hci_stack->adv_addr_type){
821         memcpy(addr, hci_stack->adv_address, 6);
822     } else {
823         memcpy(addr, hci_stack->local_bd_addr, 6);
824     }
825 }
826 
827 #ifdef ENABLE_BLE
828 void le_handle_advertisement_report(uint8_t *packet, int size){
829     int offset = 3;
830     int num_reports = packet[offset];
831     offset += 1;
832 
833     int i;
834     log_info("HCI: handle adv report with num reports: %d", num_reports);
835     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
836     for (i=0; i<num_reports;i++){
837         uint8_t data_length = packet[offset + 8];
838         uint8_t event_size = 10 + data_length;
839         int pos = 0;
840         event[pos++] = GAP_LE_EVENT_ADVERTISING_REPORT;
841         event[pos++] = event_size;
842         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
843         offset += 8;
844         pos += 8;
845         event[pos++] = packet[offset + 1 + data_length]; // rssi
846         event[pos++] = packet[offset++]; //data_length;
847         memcpy(&event[pos], &packet[offset], data_length);
848         pos += data_length;
849         offset += data_length + 1; // rssi
850         hci_emit_event(event, pos, 1);
851     }
852 }
853 #endif
854 
855 static uint32_t hci_transport_uart_get_main_baud_rate(void){
856     if (!hci_stack->config) return 0;
857     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
858     // Limit baud rate for Broadcom chipsets to 3 mbps
859     if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION && baud_rate > 3000000){
860         baud_rate = 3000000;
861     }
862     return baud_rate;
863 }
864 
865 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
866     switch (hci_stack->substate){
867         case HCI_INIT_W4_SEND_RESET:
868             log_info("Resend HCI Reset");
869             hci_stack->substate = HCI_INIT_SEND_RESET;
870             hci_stack->num_cmd_packets = 1;
871             hci_run();
872             break;
873         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
874             log_info("Resend HCI Reset - CSR Warm Boot");
875             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
876             hci_stack->num_cmd_packets = 1;
877             hci_run();
878             break;
879         case HCI_INIT_W4_SEND_BAUD_CHANGE: {
880 			uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
881             log_info("Local baud rate change to %"PRIu32"(timeout handler)", baud_rate);
882             hci_stack->hci_transport->set_baudrate(baud_rate);
883             // For CSR, HCI Reset is sent on new baud rate
884             if (hci_stack->manufacturer == COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
885                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
886                 hci_run();
887             }
888             break;
889         }
890         default:
891             break;
892     }
893 }
894 
895 static void hci_initializing_next_state(void){
896     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
897 }
898 
899 // assumption: hci_can_send_command_packet_now() == true
900 static void hci_initializing_run(void){
901     log_info("hci_initializing_run: substate %u", hci_stack->substate);
902     switch (hci_stack->substate){
903         case HCI_INIT_SEND_RESET:
904             hci_state_reset();
905 
906 #ifndef HAVE_PLATFORM_IPHONE_OS
907             // prepare reset if command complete not received in 100ms
908             btstack_run_loop_set_timer(&hci_stack->timeout, 100);
909             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
910             btstack_run_loop_add_timer(&hci_stack->timeout);
911 #endif
912             // send command
913             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
914             hci_send_cmd(&hci_reset);
915             break;
916         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
917             hci_send_cmd(&hci_read_local_version_information);
918             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
919             break;
920         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
921             hci_state_reset();
922             // prepare reset if command complete not received in 100ms
923             btstack_run_loop_set_timer(&hci_stack->timeout, 100);
924             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
925             btstack_run_loop_add_timer(&hci_stack->timeout);
926             // send command
927             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
928             hci_send_cmd(&hci_reset);
929             break;
930         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
931             hci_state_reset();
932             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
933             hci_send_cmd(&hci_reset);
934             break;
935         case HCI_INIT_SEND_BAUD_CHANGE: {
936             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
937             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
938             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
939             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
940             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
941             // STLC25000D: baudrate change happens within 0.5 s after command was send,
942             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
943             if (hci_stack->manufacturer == COMPANY_ID_ST_MICROELECTRONICS){
944                 btstack_run_loop_set_timer(&hci_stack->timeout, 100);
945                 btstack_run_loop_add_timer(&hci_stack->timeout);
946             }
947             break;
948         }
949         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
950             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
951             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
952             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
953             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
954             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
955             break;
956         }
957         case HCI_INIT_CUSTOM_INIT:
958             log_info("Custom init");
959             // Custom initialization
960             if (hci_stack->chipset && hci_stack->chipset->next_command){
961                 int valid_cmd = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
962                 if (valid_cmd){
963                     int size = 3 + hci_stack->hci_packet_buffer[2];
964                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
965                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
966                     switch (valid_cmd) {
967                         case 1:
968                         default:
969                             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
970                             break;
971                         case 2: // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
972                             log_info("CSR Warm Boot");
973                             btstack_run_loop_set_timer(&hci_stack->timeout, 100);
974                             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
975                             btstack_run_loop_add_timer(&hci_stack->timeout);
976                             if (hci_stack->manufacturer == COMPANY_ID_CAMBRIDGE_SILICON_RADIO
977                                 && hci_stack->config
978                                 && hci_stack->chipset
979                                 // && hci_stack->chipset->set_baudrate_command -- there's no such command
980                                 && hci_stack->hci_transport->set_baudrate
981                                 && hci_transport_uart_get_main_baud_rate()){
982                                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
983                             } else {
984                                hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
985                             }
986                             break;
987                     }
988                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
989                     break;
990                 }
991                 log_info("hci_run: init script done");
992 
993                 // Init script download causes baud rate to reset on Broadcom chipsets, restore UART baud rate if needed
994                 if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION){
995                     int need_baud_change = hci_stack->config
996                         && hci_stack->chipset
997                         && hci_stack->chipset->set_baudrate_command
998                         && hci_stack->hci_transport->set_baudrate
999                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1000                     if (need_baud_change) {
1001                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1002                         log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate);
1003                         hci_stack->hci_transport->set_baudrate(baud_rate);
1004                     }
1005                 }
1006             }
1007             // otherwise continue
1008             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1009             hci_send_cmd(&hci_read_local_supported_commands);
1010             break;
1011         case HCI_INIT_SET_BD_ADDR:
1012             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1013             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1014             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1015             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1016             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1017             break;
1018         case HCI_INIT_READ_BD_ADDR:
1019             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
1020             hci_send_cmd(&hci_read_bd_addr);
1021             break;
1022         case HCI_INIT_READ_BUFFER_SIZE:
1023             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
1024             hci_send_cmd(&hci_read_buffer_size);
1025             break;
1026         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
1027             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
1028             hci_send_cmd(&hci_read_local_supported_features);
1029             break;
1030         case HCI_INIT_SET_EVENT_MASK:
1031             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
1032             if (hci_le_supported()){
1033                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1034             } else {
1035                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1036                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1037             }
1038             break;
1039         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1040             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
1041             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1042             break;
1043         case HCI_INIT_WRITE_PAGE_TIMEOUT:
1044             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
1045             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
1046             break;
1047         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
1048             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
1049             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1050             break;
1051         case HCI_INIT_WRITE_LOCAL_NAME:
1052             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
1053             if (hci_stack->local_name){
1054                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
1055             } else {
1056                 char local_name[30];
1057                 // BTstack-11:22:33:44:55:66
1058                 strcpy(local_name, "BTstack ");
1059                 strcat(local_name, bd_addr_to_str(hci_stack->local_bd_addr));
1060                 log_info("---> Name %s", local_name);
1061                 hci_send_cmd(&hci_write_local_name, local_name);
1062             }
1063             break;
1064         case HCI_INIT_WRITE_SCAN_ENABLE:
1065             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1066             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
1067             break;
1068         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1069             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1070             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1071             break;
1072 #ifdef ENABLE_BLE
1073         // LE INIT
1074         case HCI_INIT_LE_READ_BUFFER_SIZE:
1075             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
1076             hci_send_cmd(&hci_le_read_buffer_size);
1077             break;
1078         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
1079             // LE Supported Host = 1, Simultaneous Host = 0
1080             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
1081             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1082             break;
1083         case HCI_INIT_READ_WHITE_LIST_SIZE:
1084             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
1085             hci_send_cmd(&hci_le_read_white_list_size);
1086             break;
1087         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1088             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs
1089             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1090             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0);
1091             break;
1092 #endif
1093         // DONE
1094         case HCI_INIT_DONE:
1095             // done.
1096             hci_stack->state = HCI_STATE_WORKING;
1097             hci_emit_state();
1098             return;
1099         default:
1100             return;
1101     }
1102 }
1103 
1104 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
1105     uint8_t command_completed = 0;
1106 
1107     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
1108         uint16_t opcode = little_endian_read_16(packet,3);
1109         if (opcode == hci_stack->last_cmd_opcode){
1110             command_completed = 1;
1111             log_info("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
1112         } else {
1113             log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1114         }
1115     }
1116 
1117     if (packet[0] == HCI_EVENT_COMMAND_STATUS){
1118         uint8_t  status = packet[2];
1119         uint16_t opcode = little_endian_read_16(packet,4);
1120         if (opcode == hci_stack->last_cmd_opcode){
1121             if (status){
1122                 command_completed = 1;
1123                 log_error("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
1124             } else {
1125                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
1126             }
1127         } else {
1128             log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1129         }
1130     }
1131 
1132     // Vendor == CSR
1133     if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && packet[0] == HCI_EVENT_VENDOR_SPECIFIC){
1134         // TODO: track actual command
1135         command_completed = 1;
1136     }
1137 
1138     // Vendor == Toshiba
1139     if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && packet[0] == HCI_EVENT_VENDOR_SPECIFIC){
1140         // TODO: track actual command
1141         command_completed = 1;
1142     }
1143 
1144     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1145     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1146     //
1147     // HCI Reset
1148     // Timeout 100 ms
1149     // HCI Reset
1150     // Command Complete Reset
1151     // HCI Read Local Version Information
1152     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1153     // hang...
1154     //
1155     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1156     if (!command_completed
1157             && packet[0] == HCI_EVENT_COMMAND_COMPLETE
1158             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
1159 
1160         uint16_t opcode = little_endian_read_16(packet,3);
1161         if (opcode == hci_reset.opcode){
1162             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1163             return;
1164         }
1165     }
1166 
1167 
1168 
1169     if (!command_completed) return;
1170 
1171     int need_baud_change = hci_stack->config
1172                         && hci_stack->chipset
1173                         && hci_stack->chipset->set_baudrate_command
1174                         && hci_stack->hci_transport->set_baudrate
1175                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1176 
1177     int need_addr_change = hci_stack->custom_bd_addr_set
1178                         && hci_stack->chipset
1179                         && hci_stack->chipset->set_bd_addr_command;
1180 
1181     switch(hci_stack->substate){
1182         case HCI_INIT_W4_SEND_RESET:
1183             btstack_run_loop_remove_timer(&hci_stack->timeout);
1184             break;
1185         case HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION:
1186             log_info("Received local version info, need baud change %u", need_baud_change);
1187             if (need_baud_change){
1188                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
1189                 return;
1190             }
1191             // skip baud change
1192             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1193             return;
1194         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1195             // for STLC2500D, baud rate change already happened.
1196             // for others, baud rate gets changed now
1197             if (hci_stack->manufacturer != COMPANY_ID_ST_MICROELECTRONICS){
1198                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1199                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1200                 hci_stack->hci_transport->set_baudrate(baud_rate);
1201             }
1202             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1203             return;
1204         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1205             btstack_run_loop_remove_timer(&hci_stack->timeout);
1206             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1207             return;
1208         case HCI_INIT_W4_CUSTOM_INIT:
1209             // repeat custom init
1210             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1211             return;
1212         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1213             if (need_baud_change && hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION){
1214                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1215                 return;
1216             }
1217             if (need_addr_change){
1218                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1219                 return;
1220             }
1221             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1222             return;
1223         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM: {
1224             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1225             log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1226             hci_stack->hci_transport->set_baudrate(baud_rate);
1227             if (need_addr_change){
1228                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1229                 return;
1230             }
1231             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1232             return;
1233         }
1234         case HCI_INIT_W4_SET_BD_ADDR:
1235             // for STLC2500D, bd addr change only gets active after sending reset command
1236             if (hci_stack->manufacturer == COMPANY_ID_ST_MICROELECTRONICS){
1237                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
1238                 return;
1239             }
1240             // skipping st warm boot
1241             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1242             return;
1243         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
1244             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1245             return;
1246         case HCI_INIT_W4_READ_BD_ADDR:
1247             // only read buffer size if supported
1248             if (hci_stack->local_supported_commands[0] & 0x01) {
1249                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
1250                 return;
1251             }
1252             // skipping read buffer size
1253             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1254             return;
1255         case HCI_INIT_W4_SET_EVENT_MASK:
1256             // skip Classic init commands for LE only chipsets
1257             if (!hci_classic_supported()){
1258                 if (hci_le_supported()){
1259                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
1260                     return;
1261                 } else {
1262                     log_error("Neither BR/EDR nor LE supported");
1263                     hci_stack->substate = HCI_INIT_DONE; // skip all
1264                     return;
1265                 }
1266             }
1267             if (!hci_ssp_supported()){
1268                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
1269                 return;
1270             }
1271             break;
1272         case HCI_INIT_W4_WRITE_PAGE_TIMEOUT:
1273             break;
1274         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1275             // skip write le host if not supported (e.g. on LE only EM9301)
1276             if (hci_stack->local_supported_commands[0] & 0x02) break;
1277             hci_stack->substate = HCI_INIT_LE_SET_SCAN_PARAMETERS;
1278             return;
1279 
1280 #ifdef HAVE_SCO_OVER_HCI
1281         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1282             // just go to next state
1283             break;
1284         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1285             if (!hci_le_supported()){
1286                 // SKIP LE init for Classic only configuration
1287                 hci_stack->substate = HCI_INIT_DONE;
1288                 return;
1289             }
1290             break;
1291 #else
1292         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1293             if (!hci_le_supported()){
1294                 // SKIP LE init for Classic only configuration
1295                 hci_stack->substate = HCI_INIT_DONE;
1296                 return;
1297             }
1298 #endif
1299             break;
1300         default:
1301             break;
1302     }
1303     hci_initializing_next_state();
1304 }
1305 
1306 static void event_handler(uint8_t *packet, int size){
1307 
1308     uint16_t event_length = packet[1];
1309 
1310     // assert packet is complete
1311     if (size != event_length + 2){
1312         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
1313         return;
1314     }
1315 
1316     bd_addr_t addr;
1317     bd_addr_type_t addr_type;
1318     uint8_t link_type;
1319     hci_con_handle_t handle;
1320     hci_connection_t * conn;
1321     int i;
1322 
1323     // log_info("HCI:EVENT:%02x", packet[0]);
1324 
1325     switch (packet[0]) {
1326 
1327         case HCI_EVENT_COMMAND_COMPLETE:
1328             // get num cmd packets
1329             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]);
1330             hci_stack->num_cmd_packets = packet[2];
1331 
1332             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
1333                 // from offset 5
1334                 // status
1335                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1336                 hci_stack->acl_data_packet_length = little_endian_read_16(packet, 6);
1337                 hci_stack->sco_data_packet_length = packet[8];
1338                 hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1339                 hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1340 
1341                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1342                     // determine usable ACL payload size
1343                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
1344                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1345                     }
1346                     log_info("hci_read_buffer_size: acl used size %u, count %u / sco size %u, count %u",
1347                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1348                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1349                 }
1350             }
1351 #ifdef ENABLE_BLE
1352             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){
1353                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1354                 hci_stack->le_acl_packets_total_num  = packet[8];
1355                     // determine usable ACL payload size
1356                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1357                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1358                     }
1359                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1360             }
1361             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_white_list_size)){
1362                 hci_stack->le_whitelist_capacity = little_endian_read_16(packet, 6);
1363                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1364             }
1365 #endif
1366             // Dump local address
1367             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
1368                 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
1369                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1370                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1371             }
1372             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1373                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1374             }
1375             // Note: HCI init checks
1376             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
1377                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1378 
1379                 // determine usable ACL packet types based on host buffer size and supported features
1380                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1381                 log_info("packet types %04x", hci_stack->packet_types);
1382 
1383                 // Classic/LE
1384                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1385             }
1386             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_version_information)){
1387                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1388                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1389                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1390                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1391                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1392                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1393             }
1394             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_commands)){
1395                 hci_stack->local_supported_commands[0] =
1396                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0X80) >> 7 |  // Octet 14, bit 7
1397                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5;   // Octet 24, bit 6
1398             }
1399             if (COMMAND_COMPLETE_EVENT(packet, hci_write_synchronous_flow_control_enable)){
1400                 if (packet[5] == 0){
1401                     hci_stack->synchronous_flow_control_enabled = 1;
1402                 }
1403             }
1404             break;
1405 
1406         case HCI_EVENT_COMMAND_STATUS:
1407             // get num cmd packets
1408             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]);
1409             hci_stack->num_cmd_packets = packet[3];
1410             break;
1411 
1412         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1413             int offset = 3;
1414             for (i=0; i<packet[2];i++){
1415                 handle = little_endian_read_16(packet, offset);
1416                 offset += 2;
1417                 uint16_t num_packets = little_endian_read_16(packet, offset);
1418                 offset += 2;
1419 
1420                 conn = hci_connection_for_handle(handle);
1421                 if (!conn){
1422                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1423                     continue;
1424                 }
1425 
1426                 if (conn->address_type == BD_ADDR_TYPE_SCO){
1427                     if (conn->num_sco_packets_sent >= num_packets){
1428                         conn->num_sco_packets_sent -= num_packets;
1429                     } else {
1430                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1431                         conn->num_sco_packets_sent = 0;
1432                     }
1433                     hci_notify_sco_can_send_now(handle);
1434                 } else {
1435                     if (conn->num_acl_packets_sent >= num_packets){
1436                         conn->num_acl_packets_sent -= num_packets;
1437                     } else {
1438                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
1439                         conn->num_acl_packets_sent = 0;
1440                     }
1441                 }
1442                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1443             }
1444             break;
1445         }
1446         case HCI_EVENT_CONNECTION_REQUEST:
1447             bt_flip_addr(addr, &packet[2]);
1448             // TODO: eval COD 8-10
1449             link_type = packet[11];
1450             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1451             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
1452             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1453             if (!conn) {
1454                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1455             }
1456             if (!conn) {
1457                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1458                 hci_stack->decline_reason = 0x0d;
1459                 BD_ADDR_COPY(hci_stack->decline_addr, addr);
1460                 break;
1461             }
1462             conn->role  = HCI_ROLE_SLAVE;
1463             conn->state = RECEIVED_CONNECTION_REQUEST;
1464             // store info about eSCO
1465             if (link_type == 0x02){
1466                 conn->remote_supported_feature_eSCO = 1;
1467             }
1468             hci_run();
1469             break;
1470 
1471         case HCI_EVENT_CONNECTION_COMPLETE:
1472             // Connection management
1473             bt_flip_addr(addr, &packet[5]);
1474             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1475             addr_type = BD_ADDR_TYPE_CLASSIC;
1476             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1477             if (conn) {
1478                 if (!packet[2]){
1479                     conn->state = OPEN;
1480                     conn->con_handle = little_endian_read_16(packet, 3);
1481                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1482 
1483                     // restart timer
1484                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1485                     btstack_run_loop_add_timer(&conn->timeout);
1486 
1487                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1488 
1489                     hci_emit_nr_connections_changed();
1490                 } else {
1491                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1492                     uint8_t status = packet[2];
1493                     bd_addr_t bd_address;
1494                     memcpy(&bd_address, conn->address, 6);
1495 
1496                     // connection failed, remove entry
1497                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1498                     btstack_memory_hci_connection_free( conn );
1499 
1500                     // notify client if dedicated bonding
1501                     if (notify_dedicated_bonding_failed){
1502                         log_info("hci notify_dedicated_bonding_failed");
1503                         hci_emit_dedicated_bonding_result(bd_address, status);
1504                     }
1505 
1506                     // if authentication error, also delete link key
1507                     if (packet[2] == 0x05) {
1508                         hci_drop_link_key_for_bd_addr(addr);
1509                     }
1510                 }
1511             }
1512             break;
1513 
1514         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1515             bt_flip_addr(addr, &packet[5]);
1516             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1517             if (packet[2]){
1518                 // connection failed
1519                 break;
1520             }
1521             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1522             if (!conn) {
1523                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1524             }
1525             if (!conn) {
1526                 break;
1527             }
1528             conn->state = OPEN;
1529             conn->con_handle = little_endian_read_16(packet, 3);
1530             break;
1531 
1532         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1533             handle = little_endian_read_16(packet, 3);
1534             conn = hci_connection_for_handle(handle);
1535             if (!conn) break;
1536             if (!packet[2]){
1537                 uint8_t * features = &packet[5];
1538                 if (features[6] & (1 << 3)){
1539                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1540                 }
1541                 if (features[3] & (1<<7)){
1542                     conn->remote_supported_feature_eSCO = 1;
1543                 }
1544             }
1545             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1546             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
1547             if (conn->bonding_flags & BONDING_DEDICATED){
1548                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1549             }
1550             break;
1551 
1552         case HCI_EVENT_LINK_KEY_REQUEST:
1553             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1554             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1555             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1556             if (hci_stack->bondable && !hci_stack->link_key_db) break;
1557             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1558             hci_run();
1559             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1560             return;
1561 
1562         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1563             bt_flip_addr(addr, &packet[2]);
1564             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1565             if (!conn) break;
1566             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1567             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1568             // Change Connection Encryption keeps link key type
1569             if (link_key_type != CHANGED_COMBINATION_KEY){
1570                 conn->link_key_type = link_key_type;
1571             }
1572             if (!hci_stack->link_key_db) break;
1573             hci_stack->link_key_db->put_link_key(addr, &packet[8], conn->link_key_type);
1574             // still forward event to allow dismiss of pairing dialog
1575             break;
1576         }
1577 
1578         case HCI_EVENT_PIN_CODE_REQUEST:
1579             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1580             // non-bondable mode: pin code negative reply will be sent
1581             if (!hci_stack->bondable){
1582                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1583                 hci_run();
1584                 return;
1585             }
1586             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1587             if (!hci_stack->link_key_db) break;
1588             bt_flip_addr(addr, &packet[2]);
1589             hci_stack->link_key_db->delete_link_key(addr);
1590             break;
1591 
1592         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1593             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1594             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1595             break;
1596 
1597         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
1598             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1599             if (!hci_stack->ssp_auto_accept) break;
1600             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1601             break;
1602 
1603         case HCI_EVENT_USER_PASSKEY_REQUEST:
1604             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1605             if (!hci_stack->ssp_auto_accept) break;
1606             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1607             break;
1608 
1609         case HCI_EVENT_ENCRYPTION_CHANGE:
1610             handle = little_endian_read_16(packet, 3);
1611             conn = hci_connection_for_handle(handle);
1612             if (!conn) break;
1613             if (packet[2] == 0) {
1614                 if (packet[5]){
1615                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1616                 } else {
1617                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1618                 }
1619             }
1620             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1621             break;
1622 
1623         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1624             handle = little_endian_read_16(packet, 3);
1625             conn = hci_connection_for_handle(handle);
1626             if (!conn) break;
1627 
1628             // dedicated bonding: send result and disconnect
1629             if (conn->bonding_flags & BONDING_DEDICATED){
1630                 conn->bonding_flags &= ~BONDING_DEDICATED;
1631                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1632                 conn->bonding_status = packet[2];
1633                 break;
1634             }
1635 
1636             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1637                 // link key sufficient for requested security
1638                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1639                 break;
1640             }
1641             // not enough
1642             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1643             break;
1644 
1645         // HCI_EVENT_DISCONNECTION_COMPLETE
1646         // has been split, to first notify stack before shutting connection down
1647         // see end of function, too.
1648         case HCI_EVENT_DISCONNECTION_COMPLETE:
1649             if (packet[2]) break;   // status != 0
1650             handle = little_endian_read_16(packet, 3);
1651             conn = hci_connection_for_handle(handle);
1652             if (!conn) break;       // no conn struct anymore
1653             // re-enable advertisements for le connections if active
1654             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
1655                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
1656             }
1657             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1658             break;
1659 
1660         case HCI_EVENT_HARDWARE_ERROR:
1661             if (hci_stack->hardware_error_callback){
1662                 (*hci_stack->hardware_error_callback)();
1663             } else {
1664                 // if no special requests, just reboot stack
1665                 hci_power_control_off();
1666                 hci_power_control_on();
1667             }
1668             break;
1669 
1670         case HCI_EVENT_ROLE_CHANGE:
1671             if (packet[2]) break;   // status != 0
1672             handle = little_endian_read_16(packet, 3);
1673             conn = hci_connection_for_handle(handle);
1674             if (!conn) break;       // no conn
1675             conn->role = packet[9];
1676             break;
1677 
1678         case DAEMON_EVENT_HCI_PACKET_SENT:
1679             // release packet buffer only for asynchronous transport and if there are not further fragements
1680             if (hci_transport_synchronous()) {
1681                 log_error("Synchronous HCI Transport shouldn't send DAEMON_EVENT_HCI_PACKET_SENT");
1682                 return; // instead of break: to avoid re-entering hci_run()
1683             }
1684             if (hci_stack->acl_fragmentation_total_size) break;
1685             hci_release_packet_buffer();
1686             break;
1687 
1688 #ifdef ENABLE_BLE
1689         case HCI_EVENT_LE_META:
1690             switch (packet[2]){
1691                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1692                     log_info("advertising report received");
1693                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1694                     le_handle_advertisement_report(packet, size);
1695                     break;
1696                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1697                     // Connection management
1698                     bt_flip_addr(addr, &packet[8]);
1699                     addr_type = (bd_addr_type_t)packet[7];
1700                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
1701                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1702                     // if auto-connect, remove from whitelist in both roles
1703                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
1704                         hci_remove_from_whitelist(addr_type, addr);
1705                     }
1706                     // handle error: error is reported only to the initiator -> outgoing connection
1707                     if (packet[3]){
1708                         // outgoing connection establishment is done
1709                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
1710                         // remove entry
1711                         if (conn){
1712                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1713                             btstack_memory_hci_connection_free( conn );
1714                         }
1715                         break;
1716                     }
1717                     // on success, both hosts receive connection complete event
1718                     if (packet[6] == HCI_ROLE_MASTER){
1719                         // if we're master, it was an outgoing connection and we're done with it
1720                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
1721                     } else {
1722                         // if we're slave, it was an incoming connection, advertisements have stopped
1723                         hci_stack->le_advertisements_active = 0;
1724                     }
1725                     // LE connections are auto-accepted, so just create a connection if there isn't one already
1726                     if (!conn){
1727                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1728                     }
1729                     // no memory, sorry.
1730                     if (!conn){
1731                         break;
1732                     }
1733 
1734                     conn->state = OPEN;
1735                     conn->role  = packet[6];
1736                     conn->con_handle = little_endian_read_16(packet, 4);
1737 
1738                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
1739 
1740                     // restart timer
1741                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1742                     // btstack_run_loop_add_timer(&conn->timeout);
1743 
1744                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1745 
1746                     hci_emit_nr_connections_changed();
1747                     break;
1748 
1749             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
1750 
1751                 default:
1752                     break;
1753             }
1754             break;
1755 #endif
1756         default:
1757             break;
1758     }
1759 
1760     // handle BT initialization
1761     if (hci_stack->state == HCI_STATE_INITIALIZING){
1762         hci_initializing_event_handler(packet, size);
1763     }
1764 
1765     // help with BT sleep
1766     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
1767         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
1768         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1769         hci_initializing_next_state();
1770     }
1771 
1772     // notify upper stack
1773 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
1774 
1775     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
1776     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1777         if (!packet[2]){
1778             handle = little_endian_read_16(packet, 3);
1779             hci_connection_t * aConn = hci_connection_for_handle(handle);
1780             if (aConn) {
1781                 uint8_t status = aConn->bonding_status;
1782                 uint16_t flags = aConn->bonding_flags;
1783                 bd_addr_t bd_address;
1784                 memcpy(&bd_address, aConn->address, 6);
1785                 hci_shutdown_connection(aConn);
1786                 // connection struct is gone, don't access anymore
1787                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
1788                     hci_emit_dedicated_bonding_result(bd_address, status);
1789                 }
1790             }
1791         }
1792     }
1793 
1794 	// execute main loop
1795 	hci_run();
1796 }
1797 
1798 static void sco_handler(uint8_t * packet, uint16_t size){
1799     if (!hci_stack->sco_packet_handler) return;
1800     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, packet, size);
1801 }
1802 
1803 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1804     hci_dump_packet(packet_type, 1, packet, size);
1805     switch (packet_type) {
1806         case HCI_EVENT_PACKET:
1807             event_handler(packet, size);
1808             break;
1809         case HCI_ACL_DATA_PACKET:
1810             acl_handler(packet, size);
1811             break;
1812         case HCI_SCO_DATA_PACKET:
1813             sco_handler(packet, size);
1814         default:
1815             break;
1816     }
1817 }
1818 
1819 /**
1820  * @brief Add event packet handler.
1821  */
1822 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
1823     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
1824 }
1825 
1826 
1827 /** Register HCI packet handlers */
1828 void hci_register_acl_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1829     hci_stack->acl_packet_handler = handler;
1830 }
1831 
1832 /**
1833  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
1834  */
1835 void hci_register_sco_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1836     hci_stack->sco_packet_handler = handler;
1837 }
1838 
1839 static void hci_state_reset(void){
1840     // no connections yet
1841     hci_stack->connections = NULL;
1842 
1843     // keep discoverable/connectable as this has been requested by the client(s)
1844     // hci_stack->discoverable = 0;
1845     // hci_stack->connectable = 0;
1846     // hci_stack->bondable = 1;
1847 
1848     // buffer is free
1849     hci_stack->hci_packet_buffer_reserved = 0;
1850 
1851     // no pending cmds
1852     hci_stack->decline_reason = 0;
1853     hci_stack->new_scan_enable_value = 0xff;
1854 
1855     // LE
1856     hci_stack->adv_addr_type = 0;
1857     memset(hci_stack->adv_address, 0, 6);
1858     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1859     hci_stack->le_scan_type = 0xff;
1860     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
1861     hci_stack->le_whitelist = 0;
1862     hci_stack->le_whitelist_capacity = 0;
1863     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
1864     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
1865     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
1866     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
1867     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
1868     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
1869 }
1870 
1871 void hci_init(const hci_transport_t *transport, void *config, btstack_link_key_db_t const * link_key_db){
1872 
1873 #ifdef HAVE_MALLOC
1874     if (!hci_stack) {
1875         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
1876     }
1877 #else
1878     hci_stack = &hci_stack_static;
1879 #endif
1880     memset(hci_stack, 0, sizeof(hci_stack_t));
1881 
1882     // reference to use transport layer implementation
1883     hci_stack->hci_transport = transport;
1884 
1885     // reference to used config
1886     hci_stack->config = config;
1887 
1888     // init used hardware control with NULL
1889     // init used chipset with NULL
1890 
1891     // store and open remote device db
1892     hci_stack->link_key_db = link_key_db;
1893     if (hci_stack->link_key_db) {
1894         hci_stack->link_key_db->open();
1895     }
1896 
1897     // max acl payload size defined in config.h
1898     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1899 
1900     // register packet handlers with transport
1901     transport->register_packet_handler(&packet_handler);
1902 
1903     hci_stack->state = HCI_STATE_OFF;
1904 
1905     // class of device
1906     hci_stack->class_of_device = 0x007a020c; // Smartphone
1907 
1908     // bondable by default
1909     hci_stack->bondable = 1;
1910 
1911     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
1912     hci_stack->ssp_enable = 1;
1913     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1914     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
1915     hci_stack->ssp_auto_accept = 1;
1916 
1917     // voice setting - signed 8 bit pcm data with CVSD over the air
1918     hci_stack->sco_voice_setting = 0x40;
1919 
1920     hci_state_reset();
1921 }
1922 
1923 /**
1924  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
1925  */
1926 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
1927     hci_stack->chipset = chipset_driver;
1928 
1929     // reset chipset driver - init is also called on power_up
1930     if (hci_stack->chipset && hci_stack->chipset->init){
1931         hci_stack->chipset->init(hci_stack->config);
1932     }
1933 }
1934 
1935 /**
1936  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
1937  */
1938 void hci_set_control(const btstack_control_t *hardware_control){
1939     // references to used control implementation
1940     hci_stack->control = hardware_control;
1941     // init with transport config
1942     hardware_control->init(hci_stack->config);
1943 }
1944 
1945 void hci_close(void){
1946     // close remote device db
1947     if (hci_stack->link_key_db) {
1948         hci_stack->link_key_db->close();
1949     }
1950     while (hci_stack->connections) {
1951         // cancel all l2cap connections
1952         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
1953         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1954     }
1955     hci_power_control(HCI_POWER_OFF);
1956 
1957 #ifdef HAVE_MALLOC
1958     free(hci_stack);
1959 #endif
1960     hci_stack = NULL;
1961 }
1962 
1963 void hci_set_class_of_device(uint32_t class_of_device){
1964     hci_stack->class_of_device = class_of_device;
1965 }
1966 
1967 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
1968 void hci_set_bd_addr(bd_addr_t addr){
1969     memcpy(hci_stack->custom_bd_addr, addr, 6);
1970     hci_stack->custom_bd_addr_set = 1;
1971 }
1972 
1973 void hci_disable_l2cap_timeout_check(void){
1974     disable_l2cap_timeouts = 1;
1975 }
1976 // State-Module-Driver overview
1977 // state                    module  low-level
1978 // HCI_STATE_OFF             off      close
1979 // HCI_STATE_INITIALIZING,   on       open
1980 // HCI_STATE_WORKING,        on       open
1981 // HCI_STATE_HALTING,        on       open
1982 // HCI_STATE_SLEEPING,    off/sleep   close
1983 // HCI_STATE_FALLING_ASLEEP  on       open
1984 
1985 static int hci_power_control_on(void){
1986 
1987     // power on
1988     int err = 0;
1989     if (hci_stack->control && hci_stack->control->on){
1990         err = (*hci_stack->control->on)();
1991     }
1992     if (err){
1993         log_error( "POWER_ON failed");
1994         hci_emit_hci_open_failed();
1995         return err;
1996     }
1997 
1998     // int chipset driver
1999     if (hci_stack->chipset && hci_stack->chipset->init){
2000         hci_stack->chipset->init(hci_stack->config);
2001     }
2002 
2003     // init transport
2004     if (hci_stack->hci_transport->init){
2005         hci_stack->hci_transport->init(hci_stack->config);
2006     }
2007 
2008     // open transport
2009     err = hci_stack->hci_transport->open();
2010     if (err){
2011         log_error( "HCI_INIT failed, turning Bluetooth off again");
2012         if (hci_stack->control && hci_stack->control->off){
2013             (*hci_stack->control->off)();
2014         }
2015         hci_emit_hci_open_failed();
2016         return err;
2017     }
2018     return 0;
2019 }
2020 
2021 static void hci_power_control_off(void){
2022 
2023     log_info("hci_power_control_off");
2024 
2025     // close low-level device
2026     hci_stack->hci_transport->close();
2027 
2028     log_info("hci_power_control_off - hci_transport closed");
2029 
2030     // power off
2031     if (hci_stack->control && hci_stack->control->off){
2032         (*hci_stack->control->off)();
2033     }
2034 
2035     log_info("hci_power_control_off - control closed");
2036 
2037     hci_stack->state = HCI_STATE_OFF;
2038 }
2039 
2040 static void hci_power_control_sleep(void){
2041 
2042     log_info("hci_power_control_sleep");
2043 
2044 #if 0
2045     // don't close serial port during sleep
2046 
2047     // close low-level device
2048     hci_stack->hci_transport->close(hci_stack->config);
2049 #endif
2050 
2051     // sleep mode
2052     if (hci_stack->control && hci_stack->control->sleep){
2053         (*hci_stack->control->sleep)();
2054     }
2055 
2056     hci_stack->state = HCI_STATE_SLEEPING;
2057 }
2058 
2059 static int hci_power_control_wake(void){
2060 
2061     log_info("hci_power_control_wake");
2062 
2063     // wake on
2064     if (hci_stack->control && hci_stack->control->wake){
2065         (*hci_stack->control->wake)();
2066     }
2067 
2068 #if 0
2069     // open low-level device
2070     int err = hci_stack->hci_transport->open(hci_stack->config);
2071     if (err){
2072         log_error( "HCI_INIT failed, turning Bluetooth off again");
2073         if (hci_stack->control && hci_stack->control->off){
2074             (*hci_stack->control->off)();
2075         }
2076         hci_emit_hci_open_failed();
2077         return err;
2078     }
2079 #endif
2080 
2081     return 0;
2082 }
2083 
2084 static void hci_power_transition_to_initializing(void){
2085     // set up state machine
2086     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2087     hci_stack->hci_packet_buffer_reserved = 0;
2088     hci_stack->state = HCI_STATE_INITIALIZING;
2089     hci_stack->substate = HCI_INIT_SEND_RESET;
2090 }
2091 
2092 int hci_power_control(HCI_POWER_MODE power_mode){
2093 
2094     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
2095 
2096     int err = 0;
2097     switch (hci_stack->state){
2098 
2099         case HCI_STATE_OFF:
2100             switch (power_mode){
2101                 case HCI_POWER_ON:
2102                     err = hci_power_control_on();
2103                     if (err) {
2104                         log_error("hci_power_control_on() error %u", err);
2105                         return err;
2106                     }
2107                     hci_power_transition_to_initializing();
2108                     break;
2109                 case HCI_POWER_OFF:
2110                     // do nothing
2111                     break;
2112                 case HCI_POWER_SLEEP:
2113                     // do nothing (with SLEEP == OFF)
2114                     break;
2115             }
2116             break;
2117 
2118         case HCI_STATE_INITIALIZING:
2119             switch (power_mode){
2120                 case HCI_POWER_ON:
2121                     // do nothing
2122                     break;
2123                 case HCI_POWER_OFF:
2124                     // no connections yet, just turn it off
2125                     hci_power_control_off();
2126                     break;
2127                 case HCI_POWER_SLEEP:
2128                     // no connections yet, just turn it off
2129                     hci_power_control_sleep();
2130                     break;
2131             }
2132             break;
2133 
2134         case HCI_STATE_WORKING:
2135             switch (power_mode){
2136                 case HCI_POWER_ON:
2137                     // do nothing
2138                     break;
2139                 case HCI_POWER_OFF:
2140                     // see hci_run
2141                     hci_stack->state = HCI_STATE_HALTING;
2142                     break;
2143                 case HCI_POWER_SLEEP:
2144                     // see hci_run
2145                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2146                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2147                     break;
2148             }
2149             break;
2150 
2151         case HCI_STATE_HALTING:
2152             switch (power_mode){
2153                 case HCI_POWER_ON:
2154                     hci_power_transition_to_initializing();
2155                     break;
2156                 case HCI_POWER_OFF:
2157                     // do nothing
2158                     break;
2159                 case HCI_POWER_SLEEP:
2160                     // see hci_run
2161                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2162                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2163                     break;
2164             }
2165             break;
2166 
2167         case HCI_STATE_FALLING_ASLEEP:
2168             switch (power_mode){
2169                 case HCI_POWER_ON:
2170 
2171 #ifdef HAVE_PLATFORM_IPHONE_OS
2172                     // nothing to do, if H4 supports power management
2173                     if (btstack_control_iphone_power_management_enabled()){
2174                         hci_stack->state = HCI_STATE_INITIALIZING;
2175                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2176                         break;
2177                     }
2178 #endif
2179                     hci_power_transition_to_initializing();
2180                     break;
2181                 case HCI_POWER_OFF:
2182                     // see hci_run
2183                     hci_stack->state = HCI_STATE_HALTING;
2184                     break;
2185                 case HCI_POWER_SLEEP:
2186                     // do nothing
2187                     break;
2188             }
2189             break;
2190 
2191         case HCI_STATE_SLEEPING:
2192             switch (power_mode){
2193                 case HCI_POWER_ON:
2194 
2195 #ifdef HAVE_PLATFORM_IPHONE_OS
2196                     // nothing to do, if H4 supports power management
2197                     if (btstack_control_iphone_power_management_enabled()){
2198                         hci_stack->state = HCI_STATE_INITIALIZING;
2199                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2200                         hci_update_scan_enable();
2201                         break;
2202                     }
2203 #endif
2204                     err = hci_power_control_wake();
2205                     if (err) return err;
2206                     hci_power_transition_to_initializing();
2207                     break;
2208                 case HCI_POWER_OFF:
2209                     hci_stack->state = HCI_STATE_HALTING;
2210                     break;
2211                 case HCI_POWER_SLEEP:
2212                     // do nothing
2213                     break;
2214             }
2215             break;
2216     }
2217 
2218     // create internal event
2219 	hci_emit_state();
2220 
2221 	// trigger next/first action
2222 	hci_run();
2223 
2224     return 0;
2225 }
2226 
2227 static void hci_update_scan_enable(void){
2228     // 2 = page scan, 1 = inq scan
2229     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2230     hci_run();
2231 }
2232 
2233 void hci_discoverable_control(uint8_t enable){
2234     if (enable) enable = 1; // normalize argument
2235 
2236     if (hci_stack->discoverable == enable){
2237         hci_emit_discoverable_enabled(hci_stack->discoverable);
2238         return;
2239     }
2240 
2241     hci_stack->discoverable = enable;
2242     hci_update_scan_enable();
2243 }
2244 
2245 void hci_connectable_control(uint8_t enable){
2246     if (enable) enable = 1; // normalize argument
2247 
2248     // don't emit event
2249     if (hci_stack->connectable == enable) return;
2250 
2251     hci_stack->connectable = enable;
2252     hci_update_scan_enable();
2253 }
2254 
2255 void hci_local_bd_addr(bd_addr_t address_buffer){
2256     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
2257 }
2258 
2259 void hci_run(void){
2260 
2261     // log_info("hci_run: entered");
2262     btstack_linked_item_t * it;
2263 
2264     // send continuation fragments first, as they block the prepared packet buffer
2265     if (hci_stack->acl_fragmentation_total_size > 0) {
2266         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2267         if (hci_can_send_prepared_acl_packet_now(con_handle)){
2268             hci_connection_t *connection = hci_connection_for_handle(con_handle);
2269             if (connection) {
2270                 hci_send_acl_packet_fragments(connection);
2271                 return;
2272             }
2273             // connection gone -> discard further fragments
2274             hci_stack->acl_fragmentation_total_size = 0;
2275             hci_stack->acl_fragmentation_pos = 0;
2276         }
2277     }
2278 
2279     if (!hci_can_send_command_packet_now()) return;
2280 
2281     // global/non-connection oriented commands
2282 
2283     // decline incoming connections
2284     if (hci_stack->decline_reason){
2285         uint8_t reason = hci_stack->decline_reason;
2286         hci_stack->decline_reason = 0;
2287         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2288         return;
2289     }
2290 
2291     // send scan enable
2292     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
2293         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
2294         hci_stack->new_scan_enable_value = 0xff;
2295         return;
2296     }
2297 
2298 #ifdef ENABLE_BLE
2299     if (hci_stack->state == HCI_STATE_WORKING){
2300         // handle le scan
2301         switch(hci_stack->le_scanning_state){
2302             case LE_START_SCAN:
2303                 hci_stack->le_scanning_state = LE_SCANNING;
2304                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
2305                 return;
2306 
2307             case LE_STOP_SCAN:
2308                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
2309                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
2310                 return;
2311             default:
2312                 break;
2313         }
2314         if (hci_stack->le_scan_type != 0xff){
2315             // defaults: active scanning, accept all advertisement packets
2316             int scan_type = hci_stack->le_scan_type;
2317             hci_stack->le_scan_type = 0xff;
2318             hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->adv_addr_type, 0);
2319             return;
2320         }
2321         // le advertisement control
2322         if (hci_stack->le_advertisements_todo){
2323             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
2324         }
2325         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
2326             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
2327             hci_send_cmd(&hci_le_set_advertise_enable, 0);
2328             return;
2329         }
2330         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
2331             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
2332             hci_send_cmd(&hci_le_set_advertising_parameters,
2333                  hci_stack->le_advertisements_interval_min,
2334                  hci_stack->le_advertisements_interval_max,
2335                  hci_stack->le_advertisements_type,
2336                  hci_stack->le_advertisements_own_address_type,
2337                  hci_stack->le_advertisements_direct_address_type,
2338                  hci_stack->le_advertisements_direct_address,
2339                  hci_stack->le_advertisements_channel_map,
2340                  hci_stack->le_advertisements_filter_policy);
2341             return;
2342         }
2343         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_DATA){
2344             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_DATA;
2345             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len,
2346                 hci_stack->le_advertisements_data);
2347             return;
2348         }
2349         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
2350             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
2351             hci_send_cmd(&hci_le_set_advertise_enable, 1);
2352             return;
2353         }
2354 
2355         //
2356         // LE Whitelist Management
2357         //
2358 
2359         // check if whitelist needs modification
2360         btstack_linked_list_iterator_t lit;
2361         int modification_pending = 0;
2362         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2363         while (btstack_linked_list_iterator_has_next(&lit)){
2364             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2365             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
2366                 modification_pending = 1;
2367                 break;
2368             }
2369         }
2370 
2371         if (modification_pending){
2372             // stop connnecting if modification pending
2373             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
2374                 hci_send_cmd(&hci_le_create_connection_cancel);
2375                 return;
2376             }
2377 
2378             // add/remove entries
2379             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2380             while (btstack_linked_list_iterator_has_next(&lit)){
2381                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2382                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
2383                     entry->state = LE_WHITELIST_ON_CONTROLLER;
2384                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
2385                     return;
2386 
2387                 }
2388                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
2389                     bd_addr_t address;
2390                     bd_addr_type_t address_type = entry->address_type;
2391                     memcpy(address, entry->address, 6);
2392                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
2393                     btstack_memory_whitelist_entry_free(entry);
2394                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
2395                     return;
2396                 }
2397             }
2398         }
2399 
2400         // start connecting
2401         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
2402             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
2403             bd_addr_t null_addr;
2404             memset(null_addr, 0, 6);
2405             hci_send_cmd(&hci_le_create_connection,
2406                  0x0060,    // scan interval: 60 ms
2407                  0x0030,    // scan interval: 30 ms
2408                  1,         // use whitelist
2409                  0,         // peer address type
2410                  null_addr,      // peer bd addr
2411                  hci_stack->adv_addr_type, // our addr type:
2412                  0x0008,    // conn interval min
2413                  0x0018,    // conn interval max
2414                  0,         // conn latency
2415                  0x0048,    // supervision timeout
2416                  0x0001,    // min ce length
2417                  0x0001     // max ce length
2418                  );
2419             return;
2420         }
2421     }
2422 #endif
2423 
2424     // send pending HCI commands
2425     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
2426         hci_connection_t * connection = (hci_connection_t *) it;
2427 
2428         switch(connection->state){
2429             case SEND_CREATE_CONNECTION:
2430                 switch(connection->address_type){
2431                     case BD_ADDR_TYPE_CLASSIC:
2432                         log_info("sending hci_create_connection");
2433                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
2434                         break;
2435                     default:
2436 #ifdef ENABLE_BLE
2437                         log_info("sending hci_le_create_connection");
2438                         hci_send_cmd(&hci_le_create_connection,
2439                                      0x0060,    // scan interval: 60 ms
2440                                      0x0030,    // scan interval: 30 ms
2441                                      0,         // don't use whitelist
2442                                      connection->address_type, // peer address type
2443                                      connection->address,      // peer bd addr
2444                                      hci_stack->adv_addr_type, // our addr type:
2445                                      0x0008,    // conn interval min
2446                                      0x0018,    // conn interval max
2447                                      0,         // conn latency
2448                                      0x0048,    // supervision timeout
2449                                      0x0001,    // min ce length
2450                                      0x0001     // max ce length
2451                                      );
2452 
2453                         connection->state = SENT_CREATE_CONNECTION;
2454 #endif
2455                         break;
2456                 }
2457                 return;
2458 
2459             case RECEIVED_CONNECTION_REQUEST:
2460                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
2461                 connection->state = ACCEPTED_CONNECTION_REQUEST;
2462                 connection->role  = HCI_ROLE_SLAVE;
2463                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
2464                     hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
2465                 } else {
2466                     // remote supported feature eSCO is set if link type is eSCO
2467                     uint16_t max_latency;
2468                     uint8_t  retransmission_effort;
2469                     uint16_t packet_types;
2470                     // remote supported feature eSCO is set if link type is eSCO
2471                     if (connection->remote_supported_feature_eSCO){
2472                         // eSCO: S4 - max latency == transmission interval = 0x000c == 12 ms,
2473                         max_latency = 0x000c;
2474                         retransmission_effort = 0x02;
2475                         packet_types = 0x388;
2476                     } else {
2477                         // SCO: max latency, retransmission interval: N/A. any packet type
2478                         max_latency = 0xffff;
2479                         retransmission_effort = 0xff;
2480                         packet_types = 0x003f;
2481                     }
2482                     hci_send_cmd(&hci_accept_synchronous_connection, connection->address, 8000, 8000, max_latency, hci_stack->sco_voice_setting, retransmission_effort, packet_types);
2483                 }
2484                 return;
2485 
2486 #ifdef ENABLE_BLE
2487             case SEND_CANCEL_CONNECTION:
2488                 connection->state = SENT_CANCEL_CONNECTION;
2489                 hci_send_cmd(&hci_le_create_connection_cancel);
2490                 return;
2491 #endif
2492             case SEND_DISCONNECT:
2493                 connection->state = SENT_DISCONNECT;
2494                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
2495                 return;
2496 
2497             default:
2498                 break;
2499         }
2500 
2501         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
2502             log_info("responding to link key request");
2503             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
2504             link_key_t link_key;
2505             link_key_type_t link_key_type;
2506             if ( hci_stack->link_key_db
2507               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
2508               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
2509                connection->link_key_type = link_key_type;
2510                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
2511             } else {
2512                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
2513             }
2514             return;
2515         }
2516 
2517         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
2518             log_info("denying to pin request");
2519             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
2520             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
2521             return;
2522         }
2523 
2524         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
2525             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
2526             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
2527             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
2528                 // tweak authentication requirements
2529                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
2530                 if (connection->bonding_flags & BONDING_DEDICATED){
2531                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
2532                 }
2533                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
2534                     authreq |= 1;
2535                 }
2536                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
2537             } else {
2538                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
2539             }
2540             return;
2541         }
2542 
2543         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
2544             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
2545             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
2546             return;
2547         }
2548 
2549         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
2550             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
2551             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
2552             return;
2553         }
2554 
2555         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
2556             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
2557             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
2558             return;
2559         }
2560 
2561         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
2562             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
2563             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
2564             return;
2565         }
2566         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
2567             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
2568             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
2569             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
2570             return;
2571         }
2572         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
2573             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
2574             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
2575             return;
2576         }
2577         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
2578             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
2579             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
2580             return;
2581         }
2582 
2583 #ifdef ENABLE_BLE
2584         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2585             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2586 
2587             uint16_t connection_interval_min = connection->le_conn_interval_min;
2588             connection->le_conn_interval_min = 0;
2589             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2590                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2591                 0x0000, 0xffff);
2592         }
2593 #endif
2594     }
2595 
2596     hci_connection_t * connection;
2597     switch (hci_stack->state){
2598         case HCI_STATE_INITIALIZING:
2599             hci_initializing_run();
2600             break;
2601 
2602         case HCI_STATE_HALTING:
2603 
2604             log_info("HCI_STATE_HALTING");
2605 
2606             // free whitelist entries
2607 #ifdef ENABLE_BLE
2608             {
2609                 btstack_linked_list_iterator_t lit;
2610                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2611                 while (btstack_linked_list_iterator_has_next(&lit)){
2612                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2613                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
2614                     btstack_memory_whitelist_entry_free(entry);
2615                 }
2616             }
2617 #endif
2618             // close all open connections
2619             connection =  (hci_connection_t *) hci_stack->connections;
2620             if (connection){
2621                 uint16_t con_handle = (uint16_t) connection->con_handle;
2622                 if (!hci_can_send_command_packet_now()) return;
2623 
2624                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
2625 
2626                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
2627                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
2628 
2629                 // ... which would be ignored anyway as we shutdown (free) the connection now
2630                 hci_shutdown_connection(connection);
2631 
2632                 // finally, send the disconnect command
2633                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
2634                 return;
2635             }
2636             log_info("HCI_STATE_HALTING, calling off");
2637 
2638             // switch mode
2639             hci_power_control_off();
2640 
2641             log_info("HCI_STATE_HALTING, emitting state");
2642             hci_emit_state();
2643             log_info("HCI_STATE_HALTING, done");
2644             break;
2645 
2646         case HCI_STATE_FALLING_ASLEEP:
2647             switch(hci_stack->substate) {
2648                 case HCI_FALLING_ASLEEP_DISCONNECT:
2649                     log_info("HCI_STATE_FALLING_ASLEEP");
2650                     // close all open connections
2651                     connection =  (hci_connection_t *) hci_stack->connections;
2652 
2653 #ifdef HAVE_PLATFORM_IPHONE_OS
2654                     // don't close connections, if H4 supports power management
2655                     if (btstack_control_iphone_power_management_enabled()){
2656                         connection = NULL;
2657                     }
2658 #endif
2659                     if (connection){
2660 
2661                         // send disconnect
2662                         if (!hci_can_send_command_packet_now()) return;
2663 
2664                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2665                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2666 
2667                         // send disconnected event right away - causes higher layer connections to get closed, too.
2668                         hci_shutdown_connection(connection);
2669                         return;
2670                     }
2671 
2672                     if (hci_classic_supported()){
2673                         // disable page and inquiry scan
2674                         if (!hci_can_send_command_packet_now()) return;
2675 
2676                         log_info("HCI_STATE_HALTING, disabling inq scans");
2677                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
2678 
2679                         // continue in next sub state
2680                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
2681                         break;
2682                     }
2683                     // fall through for ble-only chips
2684 
2685                 case HCI_FALLING_ASLEEP_COMPLETE:
2686                     log_info("HCI_STATE_HALTING, calling sleep");
2687 #ifdef HAVE_PLATFORM_IPHONE_OS
2688                     // don't actually go to sleep, if H4 supports power management
2689                     if (btstack_control_iphone_power_management_enabled()){
2690                         // SLEEP MODE reached
2691                         hci_stack->state = HCI_STATE_SLEEPING;
2692                         hci_emit_state();
2693                         break;
2694                     }
2695 #endif
2696                     // switch mode
2697                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
2698                     hci_emit_state();
2699                     break;
2700 
2701                 default:
2702                     break;
2703             }
2704             break;
2705 
2706         default:
2707             break;
2708     }
2709 }
2710 
2711 int hci_send_cmd_packet(uint8_t *packet, int size){
2712     bd_addr_t addr;
2713     hci_connection_t * conn;
2714     // house-keeping
2715 
2716     // create_connection?
2717     if (IS_COMMAND(packet, hci_create_connection)){
2718         bt_flip_addr(addr, &packet[3]);
2719         log_info("Create_connection to %s", bd_addr_to_str(addr));
2720 
2721         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2722         if (!conn){
2723             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2724             if (!conn){
2725                 // notify client that alloc failed
2726                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2727                 return 0; // don't sent packet to controller
2728             }
2729             conn->state = SEND_CREATE_CONNECTION;
2730         }
2731         log_info("conn state %u", conn->state);
2732         switch (conn->state){
2733             // if connection active exists
2734             case OPEN:
2735                 // and OPEN, emit connection complete command, don't send to controller
2736                 hci_emit_connection_complete(conn, 0);
2737                 return 0;
2738             case SEND_CREATE_CONNECTION:
2739                 // connection created by hci, e.g. dedicated bonding
2740                 break;
2741             default:
2742                 // otherwise, just ignore as it is already in the open process
2743                 return 0;
2744         }
2745         conn->state = SENT_CREATE_CONNECTION;
2746     }
2747     if (IS_COMMAND(packet, hci_link_key_request_reply)){
2748         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
2749     }
2750     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
2751         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
2752     }
2753 
2754     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
2755         if (hci_stack->link_key_db){
2756             bt_flip_addr(addr, &packet[3]);
2757             hci_stack->link_key_db->delete_link_key(addr);
2758         }
2759     }
2760 
2761     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
2762     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
2763         bt_flip_addr(addr, &packet[3]);
2764         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2765         if (conn){
2766             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
2767         }
2768     }
2769 
2770     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
2771     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
2772     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
2773     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
2774         bt_flip_addr(addr, &packet[3]);
2775         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2776         if (conn){
2777             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
2778         }
2779     }
2780 
2781     if (IS_COMMAND(packet, hci_write_loopback_mode)){
2782         hci_stack->loopback_mode = packet[3];
2783     }
2784 
2785 #ifdef ENABLE_BLE
2786     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
2787         hci_stack->adv_addr_type = packet[8];
2788     }
2789     if (IS_COMMAND(packet, hci_le_set_random_address)){
2790         bt_flip_addr(hci_stack->adv_address, &packet[3]);
2791     }
2792     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
2793         hci_stack->le_advertisements_active = packet[3];
2794     }
2795     if (IS_COMMAND(packet, hci_le_create_connection)){
2796         // white list used?
2797         uint8_t initiator_filter_policy = packet[7];
2798         switch (initiator_filter_policy){
2799             case 0:
2800                 // whitelist not used
2801                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
2802                 break;
2803             case 1:
2804                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
2805                 break;
2806             default:
2807                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
2808                 break;
2809         }
2810     }
2811     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
2812         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2813     }
2814 #endif
2815 
2816     hci_stack->num_cmd_packets--;
2817 
2818     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2819     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2820 
2821     // release packet buffer for synchronous transport implementations
2822     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
2823         hci_stack->hci_packet_buffer_reserved = 0;
2824     }
2825 
2826     return err;
2827 }
2828 
2829 // disconnect because of security block
2830 void hci_disconnect_security_block(hci_con_handle_t con_handle){
2831     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2832     if (!connection) return;
2833     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2834 }
2835 
2836 
2837 // Configure Secure Simple Pairing
2838 
2839 // enable will enable SSP during init
2840 void hci_ssp_set_enable(int enable){
2841     hci_stack->ssp_enable = enable;
2842 }
2843 
2844 int hci_local_ssp_activated(void){
2845     return hci_ssp_supported() && hci_stack->ssp_enable;
2846 }
2847 
2848 // if set, BTstack will respond to io capability request using authentication requirement
2849 void hci_ssp_set_io_capability(int io_capability){
2850     hci_stack->ssp_io_capability = io_capability;
2851 }
2852 void hci_ssp_set_authentication_requirement(int authentication_requirement){
2853     hci_stack->ssp_authentication_requirement = authentication_requirement;
2854 }
2855 
2856 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2857 void hci_ssp_set_auto_accept(int auto_accept){
2858     hci_stack->ssp_auto_accept = auto_accept;
2859 }
2860 
2861 /**
2862  * pre: numcmds >= 0 - it's allowed to send a command to the controller
2863  */
2864 int hci_send_cmd(const hci_cmd_t *cmd, ...){
2865 
2866     if (!hci_can_send_command_packet_now()){
2867         log_error("hci_send_cmd called but cannot send packet now");
2868         return 0;
2869     }
2870 
2871     // for HCI INITIALIZATION
2872     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
2873     hci_stack->last_cmd_opcode = cmd->opcode;
2874 
2875     hci_reserve_packet_buffer();
2876     uint8_t * packet = hci_stack->hci_packet_buffer;
2877 
2878     va_list argptr;
2879     va_start(argptr, cmd);
2880     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
2881     va_end(argptr);
2882 
2883     return hci_send_cmd_packet(packet, size);
2884 }
2885 
2886 // Create various non-HCI events.
2887 // TODO: generalize, use table similar to hci_create_command
2888 
2889 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
2890     // dump packet
2891     if (dump) {
2892         hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2893     }
2894 
2895     // dispatch to all event handlers
2896     btstack_linked_list_iterator_t it;
2897     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
2898     while (btstack_linked_list_iterator_has_next(&it)){
2899         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
2900         entry->callback(HCI_EVENT_PACKET, 0, event, size);
2901     }
2902 }
2903 
2904 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
2905     if (!hci_stack->acl_packet_handler) return;
2906     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, packet, size);
2907 }
2908 
2909 static void hci_emit_sco_can_send_now(uint16_t handle){
2910     uint8_t event[4];
2911     event[0] = HCI_EVENT_SCO_CAN_SEND_NOW;
2912     event[1] = 2;
2913     little_endian_store_16(event, 2, handle);
2914     hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
2915     hci_stack->sco_packet_handler(HCI_EVENT_PACKET, handle, event, sizeof(event));
2916 }
2917 
2918 static void hci_notify_sco_can_send_now(uint16_t handle){
2919     // notify SCO sender if waiting
2920     if (hci_stack->sco_waiting_for_can_send_now){
2921         hci_stack->sco_waiting_for_can_send_now = 0;
2922         hci_emit_sco_can_send_now(handle);
2923     }
2924 }
2925 
2926 void hci_emit_state(void){
2927     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2928     uint8_t event[3];
2929     event[0] = BTSTACK_EVENT_STATE;
2930     event[1] = sizeof(event) - 2;
2931     event[2] = hci_stack->state;
2932     hci_emit_event(event, sizeof(event), 1);
2933 }
2934 
2935 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
2936     uint8_t event[13];
2937     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
2938     event[1] = sizeof(event) - 2;
2939     event[2] = status;
2940     little_endian_store_16(event, 3, conn->con_handle);
2941     bt_flip_addr(&event[5], conn->address);
2942     event[11] = 1; // ACL connection
2943     event[12] = 0; // encryption disabled
2944     hci_emit_event(event, sizeof(event), 1);
2945 }
2946 
2947 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, uint16_t conn_handle, uint8_t status){
2948     uint8_t event[21];
2949     event[0] = HCI_EVENT_LE_META;
2950     event[1] = sizeof(event) - 2;
2951     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
2952     event[3] = status;
2953     little_endian_store_16(event, 4, conn_handle);
2954     event[6] = 0; // TODO: role
2955     event[7] = address_type;
2956     bt_flip_addr(&event[8], address);
2957     little_endian_store_16(event, 14, 0); // interval
2958     little_endian_store_16(event, 16, 0); // latency
2959     little_endian_store_16(event, 18, 0); // supervision timeout
2960     event[20] = 0; // master clock accuracy
2961     hci_emit_event(event, sizeof(event), 1);
2962 }
2963 
2964 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
2965     uint8_t event[6];
2966     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
2967     event[1] = sizeof(event) - 2;
2968     event[2] = 0; // status = OK
2969     little_endian_store_16(event, 3, handle);
2970     event[5] = reason;
2971     hci_emit_event(event, sizeof(event), 1);
2972 }
2973 
2974 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
2975     if (disable_l2cap_timeouts) return;
2976     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
2977     uint8_t event[4];
2978     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
2979     event[1] = sizeof(event) - 2;
2980     little_endian_store_16(event, 2, conn->con_handle);
2981     hci_emit_event(event, sizeof(event), 1);
2982 }
2983 
2984 void hci_emit_nr_connections_changed(void){
2985     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
2986     uint8_t event[3];
2987     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
2988     event[1] = sizeof(event) - 2;
2989     event[2] = nr_hci_connections();
2990     hci_emit_event(event, sizeof(event), 1);
2991 }
2992 
2993 void hci_emit_hci_open_failed(void){
2994     log_info("BTSTACK_EVENT_POWERON_FAILED");
2995     uint8_t event[2];
2996     event[0] = BTSTACK_EVENT_POWERON_FAILED;
2997     event[1] = sizeof(event) - 2;
2998     hci_emit_event(event, sizeof(event), 1);
2999 }
3000 
3001 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
3002     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
3003     uint8_t event[3];
3004     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
3005     event[1] = sizeof(event) - 2;
3006     event[2] = enabled;
3007     hci_emit_event(event, sizeof(event), 1);
3008 }
3009 
3010 void hci_emit_remote_name_cached(bd_addr_t addr, device_name_t *name){
3011     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
3012     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
3013     event[1] = sizeof(event) - 2 - 1;
3014     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
3015     bt_flip_addr(&event[3], addr);
3016     memcpy(&event[9], name, 248);
3017 
3018     event[9+248] = 0;   // assert \0 for log_info
3019     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(addr), &event[9]);
3020 
3021     hci_emit_event(event, sizeof(event), 1);
3022 }
3023 
3024 void hci_emit_discoverable_enabled(uint8_t enabled){
3025     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
3026     uint8_t event[3];
3027     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
3028     event[1] = sizeof(event) - 2;
3029     event[2] = enabled;
3030     hci_emit_event(event, sizeof(event), 1);
3031 }
3032 
3033 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3034     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3035     uint8_t event[5];
3036     int pos = 0;
3037     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3038     event[pos++] = sizeof(event) - 2;
3039     little_endian_store_16(event, 2, con_handle);
3040     pos += 2;
3041     event[pos++] = level;
3042     hci_emit_event(event, sizeof(event), 1);
3043 }
3044 
3045 void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
3046     log_info("hci_emit_dedicated_bonding_result %u ", status);
3047     uint8_t event[9];
3048     int pos = 0;
3049     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
3050     event[pos++] = sizeof(event) - 2;
3051     event[pos++] = status;
3052     bt_flip_addr( &event[pos], address);
3053     pos += 6;
3054     hci_emit_event(event, sizeof(event), 1);
3055 }
3056 
3057 // query if remote side supports eSCO
3058 int hci_remote_eSCO_supported(hci_con_handle_t con_handle){
3059     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3060     if (!connection) return 0;
3061     return connection->remote_supported_feature_eSCO;
3062 }
3063 
3064 // query if remote side supports SSP
3065 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
3066     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3067     if (!connection) return 0;
3068     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
3069 }
3070 
3071 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
3072     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3073 }
3074 
3075 // GAP API
3076 /**
3077  * @bbrief enable/disable bonding. default is enabled
3078  * @praram enabled
3079  */
3080 void gap_set_bondable_mode(int enable){
3081     hci_stack->bondable = enable ? 1 : 0;
3082 }
3083 /**
3084  * @brief Get bondable mode.
3085  * @return 1 if bondable
3086  */
3087 int gap_get_bondable_mode(void){
3088     return hci_stack->bondable;
3089 }
3090 
3091 /**
3092  * @brief map link keys to security levels
3093  */
3094 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
3095     switch (link_key_type){
3096         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
3097             return LEVEL_4;
3098         case COMBINATION_KEY:
3099         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
3100             return LEVEL_3;
3101         default:
3102             return LEVEL_2;
3103     }
3104 }
3105 
3106 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
3107     if (!connection) return LEVEL_0;
3108     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
3109     return gap_security_level_for_link_key_type(connection->link_key_type);
3110 }
3111 
3112 
3113 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
3114     log_info("gap_mitm_protection_required_for_security_level %u", level);
3115     return level > LEVEL_2;
3116 }
3117 
3118 /**
3119  * @brief get current security level
3120  */
3121 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
3122     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3123     if (!connection) return LEVEL_0;
3124     return gap_security_level_for_connection(connection);
3125 }
3126 
3127 /**
3128  * @brief request connection to device to
3129  * @result GAP_AUTHENTICATION_RESULT
3130  */
3131 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
3132     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3133     if (!connection){
3134         hci_emit_security_level(con_handle, LEVEL_0);
3135         return;
3136     }
3137     gap_security_level_t current_level = gap_security_level(con_handle);
3138     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
3139     if (current_level >= requested_level){
3140         hci_emit_security_level(con_handle, current_level);
3141         return;
3142     }
3143 
3144     connection->requested_security_level = requested_level;
3145 
3146 #if 0
3147     // sending encryption request without a link key results in an error.
3148     // TODO: figure out how to use it properly
3149 
3150     // would enabling ecnryption suffice (>= LEVEL_2)?
3151     if (hci_stack->link_key_db){
3152         link_key_type_t link_key_type;
3153         link_key_t      link_key;
3154         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3155             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3156                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3157                 return;
3158             }
3159         }
3160     }
3161 #endif
3162 
3163     // try to authenticate connection
3164     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3165     hci_run();
3166 }
3167 
3168 /**
3169  * @brief start dedicated bonding with device. disconnect after bonding
3170  * @param device
3171  * @param request MITM protection
3172  * @result GAP_DEDICATED_BONDING_COMPLETE
3173  */
3174 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3175 
3176     // create connection state machine
3177     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3178 
3179     if (!connection){
3180         return BTSTACK_MEMORY_ALLOC_FAILED;
3181     }
3182 
3183     // delete linkn key
3184     hci_drop_link_key_for_bd_addr(device);
3185 
3186     // configure LEVEL_2/3, dedicated bonding
3187     connection->state = SEND_CREATE_CONNECTION;
3188     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
3189     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
3190     connection->bonding_flags = BONDING_DEDICATED;
3191 
3192     // wait for GAP Security Result and send GAP Dedicated Bonding complete
3193 
3194     // handle: connnection failure (connection complete != ok)
3195     // handle: authentication failure
3196     // handle: disconnect on done
3197 
3198     hci_run();
3199 
3200     return 0;
3201 }
3202 
3203 void gap_set_local_name(const char * local_name){
3204     hci_stack->local_name = local_name;
3205 }
3206 
3207 uint8_t le_central_start_scan(void){
3208     if (hci_stack->le_scanning_state == LE_SCANNING) return 0;
3209     hci_stack->le_scanning_state = LE_START_SCAN;
3210     hci_run();
3211     return 0;
3212 }
3213 
3214 uint8_t le_central_stop_scan(void){
3215     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return 0;
3216     hci_stack->le_scanning_state = LE_STOP_SCAN;
3217     hci_run();
3218     return 0;
3219 }
3220 
3221 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
3222     hci_stack->le_scan_type     = scan_type;
3223     hci_stack->le_scan_interval = scan_interval;
3224     hci_stack->le_scan_window   = scan_window;
3225     hci_run();
3226 }
3227 
3228 uint8_t le_central_connect(bd_addr_t addr, bd_addr_type_t addr_type){
3229     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3230     if (!conn){
3231         log_info("le_central_connect: no connection exists yet, creating context");
3232         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3233         if (!conn){
3234             // notify client that alloc failed
3235             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3236             log_info("le_central_connect: failed to alloc hci_connection_t");
3237             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
3238         }
3239         conn->state = SEND_CREATE_CONNECTION;
3240         log_info("le_central_connect: send create connection next");
3241         hci_run();
3242         return 0;
3243     }
3244 
3245     if (!hci_is_le_connection(conn) ||
3246         conn->state == SEND_CREATE_CONNECTION ||
3247         conn->state == SENT_CREATE_CONNECTION) {
3248         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
3249         log_error("le_central_connect: classic connection or connect is already being created");
3250         return GATT_CLIENT_IN_WRONG_STATE;
3251     }
3252 
3253     log_info("le_central_connect: context exists with state %u", conn->state);
3254     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
3255     hci_run();
3256     return 0;
3257 }
3258 
3259 // @assumption: only a single outgoing LE Connection exists
3260 static hci_connection_t * le_central_get_outgoing_connection(void){
3261     btstack_linked_item_t *it;
3262     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3263         hci_connection_t * conn = (hci_connection_t *) it;
3264         if (!hci_is_le_connection(conn)) continue;
3265         switch (conn->state){
3266             case SEND_CREATE_CONNECTION:
3267             case SENT_CREATE_CONNECTION:
3268                 return conn;
3269             default:
3270                 break;
3271         };
3272     }
3273     return NULL;
3274 }
3275 
3276 uint8_t le_central_connect_cancel(void){
3277     hci_connection_t * conn = le_central_get_outgoing_connection();
3278     if (!conn) return 0;
3279     switch (conn->state){
3280         case SEND_CREATE_CONNECTION:
3281             // skip sending create connection and emit event instead
3282             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
3283             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
3284             btstack_memory_hci_connection_free( conn );
3285             break;
3286         case SENT_CREATE_CONNECTION:
3287             // request to send cancel connection
3288             conn->state = SEND_CANCEL_CONNECTION;
3289             hci_run();
3290             break;
3291         default:
3292             break;
3293     }
3294     return 0;
3295 }
3296 
3297 /**
3298  * @brief Updates the connection parameters for a given LE connection
3299  * @param handle
3300  * @param conn_interval_min (unit: 1.25ms)
3301  * @param conn_interval_max (unit: 1.25ms)
3302  * @param conn_latency
3303  * @param supervision_timeout (unit: 10ms)
3304  * @returns 0 if ok
3305  */
3306 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3307     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3308     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3309     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3310     connection->le_conn_interval_min = conn_interval_min;
3311     connection->le_conn_interval_max = conn_interval_max;
3312     connection->le_conn_latency = conn_latency;
3313     connection->le_supervision_timeout = supervision_timeout;
3314     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
3315     hci_run();
3316     return 0;
3317 }
3318 
3319 /**
3320  * @brief Request an update of the connection parameter for a given LE connection
3321  * @param handle
3322  * @param conn_interval_min (unit: 1.25ms)
3323  * @param conn_interval_max (unit: 1.25ms)
3324  * @param conn_latency
3325  * @param supervision_timeout (unit: 10ms)
3326  * @returns 0 if ok
3327  */
3328 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3329     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3330     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3331     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3332     connection->le_conn_interval_min = conn_interval_min;
3333     connection->le_conn_interval_max = conn_interval_max;
3334     connection->le_conn_latency = conn_latency;
3335     connection->le_supervision_timeout = supervision_timeout;
3336     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
3337     hci_run();
3338     return 0;
3339 }
3340 
3341 /**
3342  * @brief Set Advertisement Data
3343  * @param advertising_data_length
3344  * @param advertising_data (max 31 octets)
3345  * @note data is not copied, pointer has to stay valid
3346  */
3347 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
3348     hci_stack->le_advertisements_data_len = advertising_data_length;
3349     hci_stack->le_advertisements_data = advertising_data;
3350     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_DATA;
3351     // disable advertisements before setting data
3352     if (hci_stack->le_advertisements_active){
3353         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
3354     }
3355     hci_run();
3356 }
3357 
3358 /**
3359  * @brief Set Advertisement Parameters
3360  * @param adv_int_min
3361  * @param adv_int_max
3362  * @param adv_type
3363  * @param own_address_type
3364  * @param direct_address_type
3365  * @param direct_address
3366  * @param channel_map
3367  * @param filter_policy
3368  *
3369  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
3370  */
3371  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
3372     uint8_t own_address_type, uint8_t direct_address_typ, bd_addr_t direct_address,
3373     uint8_t channel_map, uint8_t filter_policy) {
3374 
3375     hci_stack->le_advertisements_interval_min = adv_int_min;
3376     hci_stack->le_advertisements_interval_max = adv_int_max;
3377     hci_stack->le_advertisements_type = adv_type;
3378     hci_stack->le_advertisements_own_address_type = own_address_type;
3379     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
3380     hci_stack->le_advertisements_channel_map = channel_map;
3381     hci_stack->le_advertisements_filter_policy = filter_policy;
3382     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
3383 
3384     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3385     // disable advertisements before changing params
3386     if (hci_stack->le_advertisements_active){
3387         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
3388     }
3389     hci_run();
3390  }
3391 
3392 /**
3393  * @brief Enable/Disable Advertisements
3394  * @param enabled
3395  */
3396 void gap_advertisements_enable(int enabled){
3397     hci_stack->le_advertisements_enabled = enabled;
3398     if (enabled && !hci_stack->le_advertisements_active){
3399         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
3400     }
3401     if (!enabled && hci_stack->le_advertisements_active){
3402         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
3403     }
3404     hci_run();
3405 }
3406 
3407 
3408 uint8_t gap_disconnect(hci_con_handle_t handle){
3409     hci_connection_t * conn = hci_connection_for_handle(handle);
3410     if (!conn){
3411         hci_emit_disconnection_complete(handle, 0);
3412         return 0;
3413     }
3414     conn->state = SEND_DISCONNECT;
3415     hci_run();
3416     return 0;
3417 }
3418 
3419 /**
3420  * @brief Get connection type
3421  * @param con_handle
3422  * @result connection_type
3423  */
3424 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
3425     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
3426     if (!conn) return GAP_CONNECTION_INVALID;
3427     switch (conn->address_type){
3428         case BD_ADDR_TYPE_LE_PUBLIC:
3429         case BD_ADDR_TYPE_LE_RANDOM:
3430             return GAP_CONNECTION_LE;
3431         case BD_ADDR_TYPE_SCO:
3432             return GAP_CONNECTION_SCO;
3433         case BD_ADDR_TYPE_CLASSIC:
3434             return GAP_CONNECTION_ACL;
3435         default:
3436             return GAP_CONNECTION_INVALID;
3437     }
3438 }
3439 
3440 #ifdef ENABLE_BLE
3441 
3442 /**
3443  * @brief Auto Connection Establishment - Start Connecting to device
3444  * @param address_typ
3445  * @param address
3446  * @returns 0 if ok
3447  */
3448 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
3449     // check capacity
3450     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
3451     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3452     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
3453     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
3454     entry->address_type = address_type;
3455     memcpy(entry->address, address, 6);
3456     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
3457     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
3458     hci_run();
3459     return 0;
3460 }
3461 
3462 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
3463     btstack_linked_list_iterator_t it;
3464     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3465     while (btstack_linked_list_iterator_has_next(&it)){
3466         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3467         if (entry->address_type != address_type) continue;
3468         if (memcmp(entry->address, address, 6) != 0) continue;
3469         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3470             // remove from controller if already present
3471             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3472             continue;
3473         }
3474         // direclty remove entry from whitelist
3475         btstack_linked_list_iterator_remove(&it);
3476         btstack_memory_whitelist_entry_free(entry);
3477     }
3478 }
3479 
3480 /**
3481  * @brief Auto Connection Establishment - Stop Connecting to device
3482  * @param address_typ
3483  * @param address
3484  * @returns 0 if ok
3485  */
3486 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
3487     hci_remove_from_whitelist(address_type, address);
3488     hci_run();
3489     return 0;
3490 }
3491 
3492 /**
3493  * @brief Auto Connection Establishment - Stop everything
3494  * @note  Convenience function to stop all active auto connection attempts
3495  */
3496 void gap_auto_connection_stop_all(void){
3497     btstack_linked_list_iterator_t it;
3498     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3499     while (btstack_linked_list_iterator_has_next(&it)){
3500         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3501         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3502             // remove from controller if already present
3503             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3504             continue;
3505         }
3506         // directly remove entry from whitelist
3507         btstack_linked_list_iterator_remove(&it);
3508         btstack_memory_whitelist_entry_free(entry);
3509     }
3510     hci_run();
3511 }
3512 
3513 #endif
3514 
3515 /**
3516  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
3517  */
3518 void hci_set_sco_voice_setting(uint16_t voice_setting){
3519     hci_stack->sco_voice_setting = voice_setting;
3520 }
3521 
3522 /**
3523  * @brief Get SCO Voice Setting
3524  * @return current voice setting
3525  */
3526 uint16_t hci_get_sco_voice_setting(){
3527     return hci_stack->sco_voice_setting;
3528 }
3529 
3530 /** @brief Get SCO packet length for current SCO Voice setting
3531  *  @note  Using SCO packets of the exact length is required for USB transfer
3532  *  @return Length of SCO packets in bytes (not audio frames)
3533  */
3534 int hci_get_sco_packet_length(void){
3535     // see Core Spec for H2 USB Transfer.
3536     if (hci_stack->sco_voice_setting & 0x0020) return 51;
3537     return 27;
3538 }
3539 
3540 /**
3541  * @brief Set callback for Bluetooth Hardware Error
3542  */
3543 void hci_set_hardware_error_callback(void (*fn)(void)){
3544     hci_stack->hardware_error_callback = fn;
3545 }
3546 
3547 void hci_disconnect_all(void){
3548     btstack_linked_list_iterator_t it;
3549     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
3550     while (btstack_linked_list_iterator_has_next(&it)){
3551         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
3552         if (con->state == SENT_DISCONNECT) continue;
3553         con->state = SEND_DISCONNECT;
3554     }
3555     hci_run();
3556 }
3557