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