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