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