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