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