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