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