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