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