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