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