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