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