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