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