xref: /btstack/src/hci.c (revision 29af07f3ba587d5b1f1bccb11c7d8156a7dbc2c1)
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 #ifdef ENABLE_CLASSIC
1058 static void hci_replace_bd_addr_placeholder(uint8_t * data, uint16_t size){
1059     const int bd_addr_string_len = 17;
1060     int i = 0;
1061     while (i < size - bd_addr_string_len){
1062         if (memcmp(&data[i], "00:00:00:00:00:00", bd_addr_string_len)) {
1063             i++;
1064             continue;
1065         }
1066         // set real address
1067         memcpy(&data[i], bd_addr_to_str(hci_stack->local_bd_addr), bd_addr_string_len);
1068         i += bd_addr_string_len;
1069     }
1070 }
1071 #endif
1072 
1073 // assumption: hci_can_send_command_packet_now() == true
1074 static void hci_initializing_run(void){
1075     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
1076     switch (hci_stack->substate){
1077         case HCI_INIT_SEND_RESET:
1078             hci_state_reset();
1079 
1080 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1081             // prepare reset if command complete not received in 100ms
1082             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1083             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1084             btstack_run_loop_add_timer(&hci_stack->timeout);
1085 #endif
1086             // send command
1087             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1088             hci_send_cmd(&hci_reset);
1089             break;
1090         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
1091             hci_send_cmd(&hci_read_local_version_information);
1092             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
1093             break;
1094         case HCI_INIT_SEND_READ_LOCAL_NAME:
1095             hci_send_cmd(&hci_read_local_name);
1096             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1097             break;
1098 
1099 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1100         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1101             hci_state_reset();
1102             // prepare reset if command complete not received in 100ms
1103             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1104             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1105             btstack_run_loop_add_timer(&hci_stack->timeout);
1106             // send command
1107             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1108             hci_send_cmd(&hci_reset);
1109             break;
1110         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
1111             hci_state_reset();
1112             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
1113             hci_send_cmd(&hci_reset);
1114             break;
1115         case HCI_INIT_SEND_BAUD_CHANGE: {
1116             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1117             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1118             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1119             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1120             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1121             // STLC25000D: baudrate change happens within 0.5 s after command was send,
1122             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
1123             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1124                 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1125                 btstack_run_loop_add_timer(&hci_stack->timeout);
1126             }
1127             break;
1128         }
1129         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1130             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1131             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1132             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1133             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1134             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1135             break;
1136         }
1137         case HCI_INIT_CUSTOM_INIT:
1138             // Custom initialization
1139             if (hci_stack->chipset && hci_stack->chipset->next_command){
1140                 int valid_cmd = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
1141                 if (valid_cmd){
1142                     int size = 3 + hci_stack->hci_packet_buffer[2];
1143                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1144                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
1145                     switch (valid_cmd) {
1146                         case 1:
1147                         default:
1148                             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1149                             break;
1150                         case 2: // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1151                             log_info("CSR Warm Boot");
1152                             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1153                             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1154                             btstack_run_loop_add_timer(&hci_stack->timeout);
1155                             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO
1156                                 && hci_stack->config
1157                                 && hci_stack->chipset
1158                                 // && hci_stack->chipset->set_baudrate_command -- there's no such command
1159                                 && hci_stack->hci_transport->set_baudrate
1160                                 && hci_transport_uart_get_main_baud_rate()){
1161                                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1162                             } else {
1163                                hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1164                             }
1165                             break;
1166                     }
1167                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1168                     break;
1169                 }
1170                 log_info("Init script done");
1171 
1172                 // Init script download on Broadcom chipsets causes:
1173                 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION){
1174                     // - baud rate to reset, restore UART baud rate if needed
1175                     int need_baud_change = hci_stack->config
1176                         && hci_stack->chipset
1177                         && hci_stack->chipset->set_baudrate_command
1178                         && hci_stack->hci_transport->set_baudrate
1179                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1180                     if (need_baud_change) {
1181                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1182                         log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate);
1183                         hci_stack->hci_transport->set_baudrate(baud_rate);
1184                     }
1185 
1186                     // - RTS will raise during update, but manual RTS/CTS in WICED port on RedBear Duo cannot handle this
1187                     //   -> Work around: wait a few milliseconds here.
1188                     log_info("BCM delay after init script");
1189                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1190                     btstack_run_loop_set_timer(&hci_stack->timeout, 10);
1191                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1192                     btstack_run_loop_add_timer(&hci_stack->timeout);
1193                     break;
1194                 }
1195                         }
1196             // otherwise continue
1197             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1198             hci_send_cmd(&hci_read_local_supported_commands);
1199             break;
1200         case HCI_INIT_SET_BD_ADDR:
1201             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1202             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1203             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1204             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1205             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1206             break;
1207 #endif
1208 
1209         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
1210             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
1211             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1212             hci_send_cmd(&hci_read_local_supported_commands);
1213             break;
1214         case HCI_INIT_READ_BD_ADDR:
1215             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
1216             hci_send_cmd(&hci_read_bd_addr);
1217             break;
1218         case HCI_INIT_READ_BUFFER_SIZE:
1219             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
1220             hci_send_cmd(&hci_read_buffer_size);
1221             break;
1222         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
1223             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
1224             hci_send_cmd(&hci_read_local_supported_features);
1225             break;
1226 
1227 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
1228         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
1229             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
1230             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
1231             break;
1232         case HCI_INIT_HOST_BUFFER_SIZE:
1233             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
1234             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
1235                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
1236             break;
1237 #endif
1238 
1239         case HCI_INIT_SET_EVENT_MASK:
1240             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
1241             if (hci_le_supported()){
1242                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1243             } else {
1244                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1245                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1246             }
1247             break;
1248 
1249 #ifdef ENABLE_CLASSIC
1250         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1251             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
1252             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1253             break;
1254         case HCI_INIT_WRITE_PAGE_TIMEOUT:
1255             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
1256             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
1257             break;
1258         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
1259             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
1260             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1261             break;
1262         case HCI_INIT_WRITE_LOCAL_NAME: {
1263             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
1264             const char * local_name = hci_stack->local_name ? hci_stack->local_name : "BTstack 00:00:00:00:00:00";
1265             hci_reserve_packet_buffer();
1266             uint8_t * packet = hci_stack->hci_packet_buffer;
1267             // construct HCI Command and send
1268             uint16_t opcode = hci_write_local_name.opcode;
1269             hci_stack->last_cmd_opcode = opcode;
1270             packet[0] = opcode & 0xff;
1271             packet[1] = opcode >> 8;
1272             packet[2] = DEVICE_NAME_LEN;
1273             memset(&packet[3], 0, DEVICE_NAME_LEN);
1274             memcpy(&packet[3], local_name, strlen(local_name));
1275             // expand '00:00:00:00:00:00' in name with bd_addr
1276             hci_replace_bd_addr_placeholder(&packet[3], DEVICE_NAME_LEN);
1277             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
1278             break;
1279         }
1280         case HCI_INIT_WRITE_EIR_DATA: {
1281             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
1282             hci_reserve_packet_buffer();
1283             uint8_t * packet = hci_stack->hci_packet_buffer;
1284             // construct HCI Command and send
1285             uint16_t opcode = hci_write_extended_inquiry_response.opcode;
1286             hci_stack->last_cmd_opcode = opcode;
1287             packet[0] = opcode & 0xff;
1288             packet[1] = opcode >> 8;
1289             packet[2] = 1 + 240;
1290             packet[3] = 0;  // FEC not required
1291             memcpy(&packet[4], hci_stack->eir_data, 240);
1292             // expand '00:00:00:00:00:00' in name with bd_addr
1293             hci_replace_bd_addr_placeholder(&packet[4], 240);
1294             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
1295             break;
1296         }
1297         case HCI_INIT_WRITE_INQUIRY_MODE:
1298             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
1299             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1300             break;
1301         case HCI_INIT_WRITE_SCAN_ENABLE:
1302             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1303             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
1304             break;
1305         // only sent if ENABLE_SCO_OVER_HCI is defined
1306         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1307             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1308             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1309             break;
1310         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1311             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1312             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1313             break;
1314         // only sent if ENABLE_SCO_OVER_HCI and manufacturer is Broadcom
1315         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1316             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1317             log_info("BCM: Route SCO data via HCI transport");
1318             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
1319             break;
1320 
1321 #endif
1322 #ifdef ENABLE_BLE
1323         // LE INIT
1324         case HCI_INIT_LE_READ_BUFFER_SIZE:
1325             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
1326             hci_send_cmd(&hci_le_read_buffer_size);
1327             break;
1328         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
1329             // LE Supported Host = 1, Simultaneous Host = 0
1330             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
1331             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1332             break;
1333 #endif
1334 
1335 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1336         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
1337             hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
1338             hci_send_cmd(&hci_le_read_maximum_data_length);
1339             break;
1340         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
1341             hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
1342             hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1343             break;
1344 #endif
1345 
1346 #ifdef ENABLE_LE_CENTRAL
1347         case HCI_INIT_READ_WHITE_LIST_SIZE:
1348             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
1349             hci_send_cmd(&hci_le_read_white_list_size);
1350             break;
1351         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1352             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, own address type, accept all advs
1353             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1354             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, hci_stack->le_own_addr_type, 0);
1355             break;
1356 #endif
1357         default:
1358             return;
1359     }
1360 }
1361 
1362 static void hci_init_done(void){
1363     // done. tell the app
1364     log_info("hci_init_done -> HCI_STATE_WORKING");
1365     hci_stack->state = HCI_STATE_WORKING;
1366     hci_emit_state();
1367     hci_run();
1368 }
1369 
1370 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
1371     UNUSED(size);
1372 
1373     uint8_t command_completed = 0;
1374 
1375     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1376         uint16_t opcode = little_endian_read_16(packet,3);
1377         if (opcode == hci_stack->last_cmd_opcode){
1378             command_completed = 1;
1379             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
1380         } else {
1381             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
1382         }
1383     }
1384 
1385     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
1386         uint8_t  status = packet[2];
1387         uint16_t opcode = little_endian_read_16(packet,4);
1388         if (opcode == hci_stack->last_cmd_opcode){
1389             if (status){
1390                 command_completed = 1;
1391                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
1392             } else {
1393                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
1394             }
1395         } else {
1396             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1397         }
1398     }
1399 
1400 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1401 
1402     // Vendor == CSR
1403     if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1404         // TODO: track actual command
1405         command_completed = 1;
1406     }
1407 
1408     // Vendor == Toshiba
1409     if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1410         // TODO: track actual command
1411         command_completed = 1;
1412     }
1413 
1414     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1415     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1416     //
1417     // HCI Reset
1418     // Timeout 100 ms
1419     // HCI Reset
1420     // Command Complete Reset
1421     // HCI Read Local Version Information
1422     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1423     // hang...
1424     //
1425     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1426     if (!command_completed
1427             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1428             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
1429 
1430         uint16_t opcode = little_endian_read_16(packet,3);
1431         if (opcode == hci_reset.opcode){
1432             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1433             return;
1434         }
1435     }
1436 
1437     // CSR & H5
1438     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1439     if (!command_completed
1440             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1441             && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){
1442 
1443         uint16_t opcode = little_endian_read_16(packet,3);
1444         if (opcode == hci_reset.opcode){
1445             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1446             return;
1447         }
1448     }
1449 
1450     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
1451     // fix: Correct substate and behave as command below
1452     if (command_completed){
1453         switch (hci_stack->substate){
1454             case HCI_INIT_SEND_RESET:
1455                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1456                 break;
1457             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1458                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1459                 break;
1460             default:
1461                 break;
1462         }
1463     }
1464 
1465 #endif
1466 
1467     if (!command_completed) return;
1468 
1469     int need_baud_change = 0;
1470     int need_addr_change = 0;
1471 
1472 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1473     need_baud_change = hci_stack->config
1474                         && hci_stack->chipset
1475                         && hci_stack->chipset->set_baudrate_command
1476                         && hci_stack->hci_transport->set_baudrate
1477                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1478 
1479     need_addr_change = hci_stack->custom_bd_addr_set
1480                         && hci_stack->chipset
1481                         && hci_stack->chipset->set_bd_addr_command;
1482 #endif
1483 
1484     switch(hci_stack->substate){
1485 
1486 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1487         case HCI_INIT_SEND_RESET:
1488             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
1489             // fix: just correct substate and behave as command below
1490             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1491             btstack_run_loop_remove_timer(&hci_stack->timeout);
1492             break;
1493         case HCI_INIT_W4_SEND_RESET:
1494             btstack_run_loop_remove_timer(&hci_stack->timeout);
1495             break;
1496         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
1497             log_info("Received local name, need baud change %d", need_baud_change);
1498             if (need_baud_change){
1499                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
1500                 return;
1501             }
1502             // skip baud change
1503             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1504             return;
1505         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1506             // for STLC2500D, baud rate change already happened.
1507             // for others, baud rate gets changed now
1508             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
1509                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1510                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1511                 hci_stack->hci_transport->set_baudrate(baud_rate);
1512             }
1513             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1514             return;
1515         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1516             btstack_run_loop_remove_timer(&hci_stack->timeout);
1517             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1518             return;
1519         case HCI_INIT_W4_CUSTOM_INIT:
1520             // repeat custom init
1521             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1522             return;
1523 #else
1524         case HCI_INIT_W4_SEND_RESET:
1525             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1526             return ;
1527 #endif
1528 
1529         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1530             if (need_baud_change && hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION){
1531                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1532                 return;
1533             }
1534             if (need_addr_change){
1535                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1536                 return;
1537             }
1538             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1539             return;
1540 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1541         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
1542             if (need_baud_change){
1543                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1544                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1545                 hci_stack->hci_transport->set_baudrate(baud_rate);
1546             }
1547             if (need_addr_change){
1548                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1549                 return;
1550             }
1551             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1552             return;
1553         case HCI_INIT_W4_SET_BD_ADDR:
1554             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
1555             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
1556             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
1557                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
1558                 return;
1559             }
1560             // skipping st warm boot
1561             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1562             return;
1563         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
1564             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1565             return;
1566 #endif
1567         case HCI_INIT_W4_READ_BD_ADDR:
1568             // only read buffer size if supported
1569             if (hci_stack->local_supported_commands[0] & 0x01) {
1570                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
1571                 return;
1572             }
1573             // skipping read buffer size
1574             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1575             return;
1576         case HCI_INIT_W4_SET_EVENT_MASK:
1577             // skip Classic init commands for LE only chipsets
1578             if (!hci_classic_supported()){
1579 #ifdef ENABLE_BLE
1580                 if (hci_le_supported()){
1581                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
1582                     return;
1583                 }
1584 #endif
1585                 log_error("Neither BR/EDR nor LE supported");
1586                 hci_init_done();
1587                 return;
1588             }
1589             if (!gap_ssp_supported()){
1590                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
1591                 return;
1592             }
1593             break;
1594 #ifdef ENABLE_BLE
1595         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1596             // skip write le host if not supported (e.g. on LE only EM9301)
1597             if (hci_stack->local_supported_commands[0] & 0x02) break;
1598             // explicit fall through to reduce repetitions
1599 
1600 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1601         case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED:
1602             if ((hci_stack->local_supported_commands[0] & 0x30) == 0x30){
1603                 hci_stack->substate = HCI_INIT_LE_READ_MAX_DATA_LENGTH;
1604                 return;
1605             }
1606             // explicit fall through to reduce repetitions
1607 #endif
1608 
1609 #ifdef ENABLE_LE_CENTRAL
1610             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1611 #else
1612             hci_init_done();
1613 #endif
1614             return;
1615 #endif
1616 
1617         case HCI_INIT_W4_WRITE_LOCAL_NAME:
1618             // skip write eir data if no eir data set
1619             if (hci_stack->eir_data) break;
1620             hci_stack->substate = HCI_INIT_WRITE_INQUIRY_MODE;
1621             return;
1622 
1623 #ifdef ENABLE_SCO_OVER_HCI
1624         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1625             // skip write synchronous flow control if not supported
1626             if (hci_stack->local_supported_commands[0] & 0x04) break;
1627             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1628             // explicit fall through to reduce repetitions
1629 
1630         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1631             // skip write default erroneous data reporting if not supported
1632             if (hci_stack->local_supported_commands[0] & 0x08) break;
1633             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1634             // explicit fall through to reduce repetitions
1635 
1636         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1637             // skip bcm set sco pcm config on non-Broadcom chipsets
1638             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break;
1639             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1640             // explicit fall through to reduce repetitions
1641 
1642         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1643             if (!hci_le_supported()){
1644                 // SKIP LE init for Classic only configuration
1645                 hci_init_done();
1646                 return;
1647             }
1648             break;
1649 
1650 #else /* !ENABLE_SCO_OVER_HCI */
1651 
1652         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1653 #ifdef ENABLE_BLE
1654             if (hci_le_supported()){
1655                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
1656                 return;
1657             }
1658 #endif
1659             // SKIP LE init for Classic only configuration
1660             hci_init_done();
1661             return;
1662 #endif /* ENABLE_SCO_OVER_HCI */
1663 
1664         // Response to command before init done state -> init done
1665         case (HCI_INIT_DONE-1):
1666             hci_init_done();
1667             return;
1668 
1669         default:
1670             break;
1671     }
1672     hci_initializing_next_state();
1673 }
1674 
1675 static void event_handler(uint8_t *packet, int size){
1676 
1677     uint16_t event_length = packet[1];
1678 
1679     // assert packet is complete
1680     if (size != event_length + 2){
1681         log_error("hci.c: event_handler called with event packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
1682         return;
1683     }
1684 
1685     bd_addr_t addr;
1686     bd_addr_type_t addr_type;
1687     hci_con_handle_t handle;
1688     hci_connection_t * conn;
1689     int i;
1690 #ifdef ENABLE_CLASSIC
1691     uint8_t link_type;
1692 #endif
1693 
1694     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
1695 
1696     switch (hci_event_packet_get_type(packet)) {
1697 
1698         case HCI_EVENT_COMMAND_COMPLETE:
1699             // get num cmd packets - limit to 1 to reduce complexity
1700             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
1701 
1702             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
1703                 if (packet[5]) break;
1704                 // terminate, name 248 chars
1705                 packet[6+248] = 0;
1706                 log_info("local name: %s", &packet[6]);
1707             }
1708             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1709                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1710                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1711                     uint16_t acl_len = little_endian_read_16(packet, 6);
1712                     uint16_t sco_len = packet[8];
1713 
1714                     // determine usable ACL/SCO payload size
1715                     hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
1716                     hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
1717 
1718                     hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1719                     hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1720 
1721                     log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
1722                              acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1723                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1724                 }
1725             }
1726 #ifdef ENABLE_BLE
1727             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1728                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1729                 hci_stack->le_acl_packets_total_num  = packet[8];
1730                 // determine usable ACL payload size
1731                 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1732                     hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1733                 }
1734                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1735             }
1736 #endif
1737 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1738             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_maximum_data_length)){
1739                 hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
1740                 hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
1741                 log_info("hci_le_read_maximum_data_length: tx octets %u, tx time %u us", hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1742             }
1743 #endif
1744 #ifdef ENABLE_LE_CENTRAL
1745             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1746                 hci_stack->le_whitelist_capacity = packet[6];
1747                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1748             }
1749 #endif
1750             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1751                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1752 				hci_stack->local_bd_addr);
1753                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1754                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1755 #ifdef ENABLE_CLASSIC
1756                 if (hci_stack->link_key_db){
1757                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1758                 }
1759 #endif
1760             }
1761 #ifdef ENABLE_CLASSIC
1762             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1763                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1764             }
1765             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_inquiry_cancel)){
1766                 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
1767                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1768                     uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1769                     hci_emit_event(event, sizeof(event), 1);
1770                 }
1771             }
1772 #endif
1773 
1774             // Note: HCI init checks
1775             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1776                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1777 
1778 #ifdef ENABLE_CLASSIC
1779                 // determine usable ACL packet types based on host buffer size and supported features
1780                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1781                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
1782 #endif
1783                 // Classic/LE
1784                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1785             }
1786             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1787                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1788                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1789                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1790                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1791                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1792                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1793             }
1794             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1795                 hci_stack->local_supported_commands[0] =
1796                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7
1797                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6
1798                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4
1799                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08)      |  // bit 3 = Octet 18, bit 3
1800                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x01) << 4 |  // bit 4 = Octet 34, bit 0
1801                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x08) << 2;   // bit 5 = Octet 35, bit 3
1802                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1803             }
1804 #ifdef ENABLE_CLASSIC
1805             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1806                 if (packet[5] == 0){
1807                     hci_stack->synchronous_flow_control_enabled = 1;
1808                 }
1809             }
1810 #endif
1811             break;
1812 
1813         case HCI_EVENT_COMMAND_STATUS:
1814             // get num cmd packets - limit to 1 to reduce complexity
1815             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
1816             break;
1817 
1818         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1819             int offset = 3;
1820             for (i=0; i<packet[2];i++){
1821                 handle = little_endian_read_16(packet, offset);
1822                 offset += 2;
1823                 uint16_t num_packets = little_endian_read_16(packet, offset);
1824                 offset += 2;
1825 
1826                 conn = hci_connection_for_handle(handle);
1827                 if (!conn){
1828                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1829                     continue;
1830                 }
1831 
1832                 if (conn->address_type == BD_ADDR_TYPE_SCO){
1833 #ifdef ENABLE_CLASSIC
1834                     if (conn->num_sco_packets_sent >= num_packets){
1835                         conn->num_sco_packets_sent -= num_packets;
1836                     } else {
1837                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1838                         conn->num_sco_packets_sent = 0;
1839                     }
1840                     hci_notify_if_sco_can_send_now();
1841 #endif
1842                 } else {
1843                     if (conn->num_acl_packets_sent >= num_packets){
1844                         conn->num_acl_packets_sent -= num_packets;
1845                     } else {
1846                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
1847                         conn->num_acl_packets_sent = 0;
1848                     }
1849                 }
1850                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1851             }
1852             break;
1853         }
1854 
1855 #ifdef ENABLE_CLASSIC
1856         case HCI_EVENT_INQUIRY_COMPLETE:
1857             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
1858                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1859                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1860                 hci_emit_event(event, sizeof(event), 1);
1861             }
1862             break;
1863         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1864             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
1865                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
1866             }
1867             break;
1868         case HCI_EVENT_CONNECTION_REQUEST:
1869             reverse_bd_addr(&packet[2], addr);
1870             // TODO: eval COD 8-10
1871             link_type = packet[11];
1872             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1873             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
1874             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1875             if (!conn) {
1876                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1877             }
1878             if (!conn) {
1879                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1880                 hci_stack->decline_reason = 0x0d;
1881                 bd_addr_copy(hci_stack->decline_addr, addr);
1882                 break;
1883             }
1884             conn->role  = HCI_ROLE_SLAVE;
1885             conn->state = RECEIVED_CONNECTION_REQUEST;
1886             // store info about eSCO
1887             if (link_type == 0x02){
1888                 conn->remote_supported_feature_eSCO = 1;
1889             }
1890             hci_run();
1891             break;
1892 
1893         case HCI_EVENT_CONNECTION_COMPLETE:
1894             // Connection management
1895             reverse_bd_addr(&packet[5], addr);
1896             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1897             addr_type = BD_ADDR_TYPE_CLASSIC;
1898             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1899             if (conn) {
1900                 if (!packet[2]){
1901                     conn->state = OPEN;
1902                     conn->con_handle = little_endian_read_16(packet, 3);
1903                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1904 
1905                     // restart timer
1906                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1907                     btstack_run_loop_add_timer(&conn->timeout);
1908 
1909                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1910 
1911                     hci_emit_nr_connections_changed();
1912                 } else {
1913                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1914                     uint8_t status = packet[2];
1915                     bd_addr_t bd_address;
1916                     memcpy(&bd_address, conn->address, 6);
1917 
1918                     // connection failed, remove entry
1919                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1920                     btstack_memory_hci_connection_free( conn );
1921 
1922                     // notify client if dedicated bonding
1923                     if (notify_dedicated_bonding_failed){
1924                         log_info("hci notify_dedicated_bonding_failed");
1925                         hci_emit_dedicated_bonding_result(bd_address, status);
1926                     }
1927 
1928                     // if authentication error, also delete link key
1929                     if (packet[2] == 0x05) {
1930                         gap_drop_link_key_for_bd_addr(addr);
1931                     }
1932                 }
1933             }
1934             break;
1935 
1936         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1937             reverse_bd_addr(&packet[5], addr);
1938             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1939             if (packet[2]){
1940                 // connection failed
1941                 break;
1942             }
1943             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1944             if (!conn) {
1945                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1946             }
1947             if (!conn) {
1948                 break;
1949             }
1950             conn->state = OPEN;
1951             conn->con_handle = little_endian_read_16(packet, 3);
1952 
1953 #ifdef ENABLE_SCO_OVER_HCI
1954             // update SCO
1955             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
1956                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1957             }
1958 #endif
1959             break;
1960 
1961         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1962             handle = little_endian_read_16(packet, 3);
1963             conn = hci_connection_for_handle(handle);
1964             if (!conn) break;
1965             if (!packet[2]){
1966                 uint8_t * features = &packet[5];
1967                 if (features[6] & (1 << 3)){
1968                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1969                 }
1970                 if (features[3] & (1<<7)){
1971                     conn->remote_supported_feature_eSCO = 1;
1972                 }
1973             }
1974             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1975             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
1976             if (conn->bonding_flags & BONDING_DEDICATED){
1977                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1978             }
1979             break;
1980 
1981         case HCI_EVENT_LINK_KEY_REQUEST:
1982             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1983             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1984             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1985             if (hci_stack->bondable && !hci_stack->link_key_db) break;
1986             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1987             hci_run();
1988             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1989             return;
1990 
1991         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1992             reverse_bd_addr(&packet[2], addr);
1993             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1994             if (!conn) break;
1995             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1996             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1997             // Change Connection Encryption keeps link key type
1998             if (link_key_type != CHANGED_COMBINATION_KEY){
1999                 conn->link_key_type = link_key_type;
2000             }
2001             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2002             // still forward event to allow dismiss of pairing dialog
2003             break;
2004         }
2005 
2006         case HCI_EVENT_PIN_CODE_REQUEST:
2007             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
2008             // non-bondable mode: pin code negative reply will be sent
2009             if (!hci_stack->bondable){
2010                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
2011                 hci_run();
2012                 return;
2013             }
2014             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
2015             if (!hci_stack->link_key_db) break;
2016             hci_event_pin_code_request_get_bd_addr(packet, addr);
2017             hci_stack->link_key_db->delete_link_key(addr);
2018             break;
2019 
2020         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2021             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
2022             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
2023             break;
2024 
2025         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2026             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2027             if (!hci_stack->ssp_auto_accept) break;
2028             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
2029             break;
2030 
2031         case HCI_EVENT_USER_PASSKEY_REQUEST:
2032             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2033             if (!hci_stack->ssp_auto_accept) break;
2034             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
2035             break;
2036 #endif
2037 
2038         case HCI_EVENT_ENCRYPTION_CHANGE:
2039             handle = little_endian_read_16(packet, 3);
2040             conn = hci_connection_for_handle(handle);
2041             if (!conn) break;
2042             if (packet[2] == 0) {
2043                 if (packet[5]){
2044                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
2045                 } else {
2046                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
2047                 }
2048             }
2049 #ifdef ENABLE_CLASSIC
2050             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2051 #endif
2052             break;
2053 
2054 #ifdef ENABLE_CLASSIC
2055         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2056             handle = little_endian_read_16(packet, 3);
2057             conn = hci_connection_for_handle(handle);
2058             if (!conn) break;
2059 
2060             // dedicated bonding: send result and disconnect
2061             if (conn->bonding_flags & BONDING_DEDICATED){
2062                 conn->bonding_flags &= ~BONDING_DEDICATED;
2063                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2064                 conn->bonding_status = packet[2];
2065                 break;
2066             }
2067 
2068             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
2069                 // link key sufficient for requested security
2070                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2071                 break;
2072             }
2073             // not enough
2074             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2075             break;
2076 #endif
2077 
2078         // HCI_EVENT_DISCONNECTION_COMPLETE
2079         // has been split, to first notify stack before shutting connection down
2080         // see end of function, too.
2081         case HCI_EVENT_DISCONNECTION_COMPLETE:
2082             if (packet[2]) break;   // status != 0
2083             handle = little_endian_read_16(packet, 3);
2084             // drop outgoing ACL fragments if it is for closed connection
2085             if (hci_stack->acl_fragmentation_total_size > 0) {
2086                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
2087                     log_info("hci: drop fragmented ACL data for closed connection");
2088                      hci_stack->acl_fragmentation_total_size = 0;
2089                      hci_stack->acl_fragmentation_pos = 0;
2090                 }
2091             }
2092 
2093             // re-enable advertisements for le connections if active
2094             conn = hci_connection_for_handle(handle);
2095             if (!conn) break;
2096 #ifdef ENABLE_BLE
2097 #ifdef ENABLE_LE_PERIPHERAL
2098             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
2099                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2100             }
2101 #endif
2102 #endif
2103             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2104             break;
2105 
2106         case HCI_EVENT_HARDWARE_ERROR:
2107             log_error("Hardware Error: 0x%02x", packet[2]);
2108             if (hci_stack->hardware_error_callback){
2109                 (*hci_stack->hardware_error_callback)(packet[2]);
2110             } else {
2111                 // if no special requests, just reboot stack
2112                 hci_power_control_off();
2113                 hci_power_control_on();
2114             }
2115             break;
2116 
2117 #ifdef ENABLE_CLASSIC
2118         case HCI_EVENT_ROLE_CHANGE:
2119             if (packet[2]) break;   // status != 0
2120             handle = little_endian_read_16(packet, 3);
2121             conn = hci_connection_for_handle(handle);
2122             if (!conn) break;       // no conn
2123             conn->role = packet[9];
2124             break;
2125 #endif
2126 
2127         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2128             // release packet buffer only for asynchronous transport and if there are not further fragements
2129             if (hci_transport_synchronous()) {
2130                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2131                 return; // instead of break: to avoid re-entering hci_run()
2132             }
2133             if (hci_stack->acl_fragmentation_total_size) break;
2134             hci_release_packet_buffer();
2135 
2136             // L2CAP receives this event via the hci_emit_event below
2137 
2138 #ifdef ENABLE_CLASSIC
2139             // For SCO, we do the can_send_now_check here
2140             hci_notify_if_sco_can_send_now();
2141 #endif
2142             break;
2143 
2144 #ifdef ENABLE_CLASSIC
2145         case HCI_EVENT_SCO_CAN_SEND_NOW:
2146             // For SCO, we do the can_send_now_check here
2147             hci_notify_if_sco_can_send_now();
2148             return;
2149 
2150         // explode inquriy results for easier consumption
2151         case HCI_EVENT_INQUIRY_RESULT:
2152         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
2153         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
2154             gap_inquiry_explode(packet);
2155             break;
2156 #endif
2157 
2158 #ifdef ENABLE_BLE
2159         case HCI_EVENT_LE_META:
2160             switch (packet[2]){
2161 #ifdef ENABLE_LE_CENTRAL
2162                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
2163                     // log_info("advertising report received");
2164                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
2165                     le_handle_advertisement_report(packet, size);
2166                     break;
2167 #endif
2168                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
2169                     // Connection management
2170                     reverse_bd_addr(&packet[8], addr);
2171                     addr_type = (bd_addr_type_t)packet[7];
2172                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2173                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2174 #ifdef ENABLE_LE_CENTRAL
2175                     // if auto-connect, remove from whitelist in both roles
2176                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
2177                         hci_remove_from_whitelist(addr_type, addr);
2178                     }
2179                     // handle error: error is reported only to the initiator -> outgoing connection
2180                     if (packet[3]){
2181                         // outgoing connection establishment is done
2182                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2183                         // remove entry
2184                         if (conn){
2185                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2186                             btstack_memory_hci_connection_free( conn );
2187                         }
2188                         break;
2189                     }
2190 #endif
2191                     // on success, both hosts receive connection complete event
2192                     if (packet[6] == HCI_ROLE_MASTER){
2193 #ifdef ENABLE_LE_CENTRAL
2194                         // if we're master, it was an outgoing connection and we're done with it
2195                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2196 #endif
2197                     } else {
2198 #ifdef ENABLE_LE_PERIPHERAL
2199                         // if we're slave, it was an incoming connection, advertisements have stopped
2200                         hci_stack->le_advertisements_active = 0;
2201                         // try to re-enable them
2202                         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2203 #endif
2204                     }
2205                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2206                     if (!conn){
2207                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2208                     }
2209                     // no memory, sorry.
2210                     if (!conn){
2211                         break;
2212                     }
2213 
2214                     conn->state = OPEN;
2215                     conn->role  = packet[6];
2216                     conn->con_handle = little_endian_read_16(packet, 4);
2217 
2218                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2219 
2220                     // restart timer
2221                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2222                     // btstack_run_loop_add_timer(&conn->timeout);
2223 
2224                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2225 
2226                     hci_emit_nr_connections_changed();
2227                     break;
2228 
2229             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2230 
2231                 default:
2232                     break;
2233             }
2234             break;
2235 #endif
2236         default:
2237             break;
2238     }
2239 
2240     // handle BT initialization
2241     if (hci_stack->state == HCI_STATE_INITIALIZING){
2242         hci_initializing_event_handler(packet, size);
2243     }
2244 
2245     // help with BT sleep
2246     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2247         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2248         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2249         hci_initializing_next_state();
2250     }
2251 
2252     // notify upper stack
2253 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2254 
2255     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2256     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2257         if (!packet[2]){
2258             handle = little_endian_read_16(packet, 3);
2259             hci_connection_t * aConn = hci_connection_for_handle(handle);
2260             if (aConn) {
2261                 uint8_t status = aConn->bonding_status;
2262                 uint16_t flags = aConn->bonding_flags;
2263                 bd_addr_t bd_address;
2264                 memcpy(&bd_address, aConn->address, 6);
2265                 hci_shutdown_connection(aConn);
2266                 // connection struct is gone, don't access anymore
2267                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2268                     hci_emit_dedicated_bonding_result(bd_address, status);
2269                 }
2270             }
2271         }
2272     }
2273 
2274 	// execute main loop
2275 	hci_run();
2276 }
2277 
2278 #ifdef ENABLE_CLASSIC
2279 static void sco_handler(uint8_t * packet, uint16_t size){
2280     if (!hci_stack->sco_packet_handler) return;
2281     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2282 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2283     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2284     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
2285     if (conn){
2286         conn->num_packets_completed++;
2287         hci_stack->host_completed_packets = 1;
2288         hci_run();
2289     }
2290 #endif
2291 }
2292 #endif
2293 
2294 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2295     hci_dump_packet(packet_type, 1, packet, size);
2296     switch (packet_type) {
2297         case HCI_EVENT_PACKET:
2298             event_handler(packet, size);
2299             break;
2300         case HCI_ACL_DATA_PACKET:
2301             acl_handler(packet, size);
2302             break;
2303 #ifdef ENABLE_CLASSIC
2304         case HCI_SCO_DATA_PACKET:
2305             sco_handler(packet, size);
2306             break;
2307 #endif
2308         default:
2309             break;
2310     }
2311 }
2312 
2313 /**
2314  * @brief Add event packet handler.
2315  */
2316 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2317     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2318 }
2319 
2320 
2321 /** Register HCI packet handlers */
2322 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2323     hci_stack->acl_packet_handler = handler;
2324 }
2325 
2326 #ifdef ENABLE_CLASSIC
2327 /**
2328  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2329  */
2330 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2331     hci_stack->sco_packet_handler = handler;
2332 }
2333 #endif
2334 
2335 static void hci_state_reset(void){
2336     // no connections yet
2337     hci_stack->connections = NULL;
2338 
2339     // keep discoverable/connectable as this has been requested by the client(s)
2340     // hci_stack->discoverable = 0;
2341     // hci_stack->connectable = 0;
2342     // hci_stack->bondable = 1;
2343     // hci_stack->own_addr_type = 0;
2344 
2345     // buffer is free
2346     hci_stack->hci_packet_buffer_reserved = 0;
2347 
2348     // no pending cmds
2349     hci_stack->decline_reason = 0;
2350     hci_stack->new_scan_enable_value = 0xff;
2351 
2352     // LE
2353 #ifdef ENABLE_BLE
2354     memset(hci_stack->le_random_address, 0, 6);
2355     hci_stack->le_random_address_set = 0;
2356 #endif
2357 #ifdef ENABLE_LE_CENTRAL
2358     hci_stack->le_scanning_state = LE_SCAN_IDLE;
2359     hci_stack->le_scan_type = 0xff;
2360     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2361     hci_stack->le_whitelist = 0;
2362     hci_stack->le_whitelist_capacity = 0;
2363 
2364     // connection parameter to use for outgoing connections
2365     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
2366     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
2367     hci_stack->le_connection_latency      = 4;         // 4
2368     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
2369     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
2370     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
2371 #endif
2372 
2373     // connection parameter range used to answer connection parameter update requests in l2cap
2374     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2375     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2376     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2377     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2378     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2379     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2380 }
2381 
2382 #ifdef ENABLE_CLASSIC
2383 /**
2384  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2385  */
2386 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2387     // store and open remote device db
2388     hci_stack->link_key_db = link_key_db;
2389     if (hci_stack->link_key_db) {
2390         hci_stack->link_key_db->open();
2391     }
2392 }
2393 #endif
2394 
2395 void hci_init(const hci_transport_t *transport, const void *config){
2396 
2397 #ifdef HAVE_MALLOC
2398     if (!hci_stack) {
2399         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2400     }
2401 #else
2402     hci_stack = &hci_stack_static;
2403 #endif
2404     memset(hci_stack, 0, sizeof(hci_stack_t));
2405 
2406     // reference to use transport layer implementation
2407     hci_stack->hci_transport = transport;
2408 
2409     // reference to used config
2410     hci_stack->config = config;
2411 
2412     // setup pointer for outgoing packet buffer
2413     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2414 
2415     // max acl payload size defined in config.h
2416     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2417 
2418     // register packet handlers with transport
2419     transport->register_packet_handler(&packet_handler);
2420 
2421     hci_stack->state = HCI_STATE_OFF;
2422 
2423     // class of device
2424     hci_stack->class_of_device = 0x007a020c; // Smartphone
2425 
2426     // bondable by default
2427     hci_stack->bondable = 1;
2428 
2429     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2430     hci_stack->ssp_enable = 1;
2431     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2432     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2433     hci_stack->ssp_auto_accept = 1;
2434 
2435     // voice setting - signed 16 bit pcm data with CVSD over the air
2436     hci_stack->sco_voice_setting = 0x60;
2437 
2438     hci_state_reset();
2439 }
2440 
2441 /**
2442  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2443  */
2444 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2445     hci_stack->chipset = chipset_driver;
2446 
2447     // reset chipset driver - init is also called on power_up
2448     if (hci_stack->chipset && hci_stack->chipset->init){
2449         hci_stack->chipset->init(hci_stack->config);
2450     }
2451 }
2452 
2453 /**
2454  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2455  */
2456 void hci_set_control(const btstack_control_t *hardware_control){
2457     // references to used control implementation
2458     hci_stack->control = hardware_control;
2459     // init with transport config
2460     hardware_control->init(hci_stack->config);
2461 }
2462 
2463 void hci_close(void){
2464     // close remote device db
2465     if (hci_stack->link_key_db) {
2466         hci_stack->link_key_db->close();
2467     }
2468 
2469     btstack_linked_list_iterator_t lit;
2470     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2471     while (btstack_linked_list_iterator_has_next(&lit)){
2472         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2473         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2474         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2475         hci_shutdown_connection(connection);
2476     }
2477 
2478     hci_power_control(HCI_POWER_OFF);
2479 
2480 #ifdef HAVE_MALLOC
2481     free(hci_stack);
2482 #endif
2483     hci_stack = NULL;
2484 }
2485 
2486 #ifdef ENABLE_CLASSIC
2487 void gap_set_class_of_device(uint32_t class_of_device){
2488     hci_stack->class_of_device = class_of_device;
2489 }
2490 
2491 void hci_disable_l2cap_timeout_check(void){
2492     disable_l2cap_timeouts = 1;
2493 }
2494 #endif
2495 
2496 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2497 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2498 void hci_set_bd_addr(bd_addr_t addr){
2499     memcpy(hci_stack->custom_bd_addr, addr, 6);
2500     hci_stack->custom_bd_addr_set = 1;
2501 }
2502 #endif
2503 
2504 // State-Module-Driver overview
2505 // state                    module  low-level
2506 // HCI_STATE_OFF             off      close
2507 // HCI_STATE_INITIALIZING,   on       open
2508 // HCI_STATE_WORKING,        on       open
2509 // HCI_STATE_HALTING,        on       open
2510 // HCI_STATE_SLEEPING,    off/sleep   close
2511 // HCI_STATE_FALLING_ASLEEP  on       open
2512 
2513 static int hci_power_control_on(void){
2514 
2515     // power on
2516     int err = 0;
2517     if (hci_stack->control && hci_stack->control->on){
2518         err = (*hci_stack->control->on)();
2519     }
2520     if (err){
2521         log_error( "POWER_ON failed");
2522         hci_emit_hci_open_failed();
2523         return err;
2524     }
2525 
2526     // int chipset driver
2527     if (hci_stack->chipset && hci_stack->chipset->init){
2528         hci_stack->chipset->init(hci_stack->config);
2529     }
2530 
2531     // init transport
2532     if (hci_stack->hci_transport->init){
2533         hci_stack->hci_transport->init(hci_stack->config);
2534     }
2535 
2536     // open transport
2537     err = hci_stack->hci_transport->open();
2538     if (err){
2539         log_error( "HCI_INIT failed, turning Bluetooth off again");
2540         if (hci_stack->control && hci_stack->control->off){
2541             (*hci_stack->control->off)();
2542         }
2543         hci_emit_hci_open_failed();
2544         return err;
2545     }
2546     return 0;
2547 }
2548 
2549 static void hci_power_control_off(void){
2550 
2551     log_info("hci_power_control_off");
2552 
2553     // close low-level device
2554     hci_stack->hci_transport->close();
2555 
2556     log_info("hci_power_control_off - hci_transport closed");
2557 
2558     // power off
2559     if (hci_stack->control && hci_stack->control->off){
2560         (*hci_stack->control->off)();
2561     }
2562 
2563     log_info("hci_power_control_off - control closed");
2564 
2565     hci_stack->state = HCI_STATE_OFF;
2566 }
2567 
2568 static void hci_power_control_sleep(void){
2569 
2570     log_info("hci_power_control_sleep");
2571 
2572 #if 0
2573     // don't close serial port during sleep
2574 
2575     // close low-level device
2576     hci_stack->hci_transport->close(hci_stack->config);
2577 #endif
2578 
2579     // sleep mode
2580     if (hci_stack->control && hci_stack->control->sleep){
2581         (*hci_stack->control->sleep)();
2582     }
2583 
2584     hci_stack->state = HCI_STATE_SLEEPING;
2585 }
2586 
2587 static int hci_power_control_wake(void){
2588 
2589     log_info("hci_power_control_wake");
2590 
2591     // wake on
2592     if (hci_stack->control && hci_stack->control->wake){
2593         (*hci_stack->control->wake)();
2594     }
2595 
2596 #if 0
2597     // open low-level device
2598     int err = hci_stack->hci_transport->open(hci_stack->config);
2599     if (err){
2600         log_error( "HCI_INIT failed, turning Bluetooth off again");
2601         if (hci_stack->control && hci_stack->control->off){
2602             (*hci_stack->control->off)();
2603         }
2604         hci_emit_hci_open_failed();
2605         return err;
2606     }
2607 #endif
2608 
2609     return 0;
2610 }
2611 
2612 static void hci_power_transition_to_initializing(void){
2613     // set up state machine
2614     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2615     hci_stack->hci_packet_buffer_reserved = 0;
2616     hci_stack->state = HCI_STATE_INITIALIZING;
2617     hci_stack->substate = HCI_INIT_SEND_RESET;
2618 }
2619 
2620 int hci_power_control(HCI_POWER_MODE power_mode){
2621 
2622     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2623 
2624     int err = 0;
2625     switch (hci_stack->state){
2626 
2627         case HCI_STATE_OFF:
2628             switch (power_mode){
2629                 case HCI_POWER_ON:
2630                     err = hci_power_control_on();
2631                     if (err) {
2632                         log_error("hci_power_control_on() error %d", err);
2633                         return err;
2634                     }
2635                     hci_power_transition_to_initializing();
2636                     break;
2637                 case HCI_POWER_OFF:
2638                     // do nothing
2639                     break;
2640                 case HCI_POWER_SLEEP:
2641                     // do nothing (with SLEEP == OFF)
2642                     break;
2643             }
2644             break;
2645 
2646         case HCI_STATE_INITIALIZING:
2647             switch (power_mode){
2648                 case HCI_POWER_ON:
2649                     // do nothing
2650                     break;
2651                 case HCI_POWER_OFF:
2652                     // no connections yet, just turn it off
2653                     hci_power_control_off();
2654                     break;
2655                 case HCI_POWER_SLEEP:
2656                     // no connections yet, just turn it off
2657                     hci_power_control_sleep();
2658                     break;
2659             }
2660             break;
2661 
2662         case HCI_STATE_WORKING:
2663             switch (power_mode){
2664                 case HCI_POWER_ON:
2665                     // do nothing
2666                     break;
2667                 case HCI_POWER_OFF:
2668                     // see hci_run
2669                     hci_stack->state = HCI_STATE_HALTING;
2670                     break;
2671                 case HCI_POWER_SLEEP:
2672                     // see hci_run
2673                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2674                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2675                     break;
2676             }
2677             break;
2678 
2679         case HCI_STATE_HALTING:
2680             switch (power_mode){
2681                 case HCI_POWER_ON:
2682                     hci_power_transition_to_initializing();
2683                     break;
2684                 case HCI_POWER_OFF:
2685                     // do nothing
2686                     break;
2687                 case HCI_POWER_SLEEP:
2688                     // see hci_run
2689                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2690                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2691                     break;
2692             }
2693             break;
2694 
2695         case HCI_STATE_FALLING_ASLEEP:
2696             switch (power_mode){
2697                 case HCI_POWER_ON:
2698 
2699 #ifdef HAVE_PLATFORM_IPHONE_OS
2700                     // nothing to do, if H4 supports power management
2701                     if (btstack_control_iphone_power_management_enabled()){
2702                         hci_stack->state = HCI_STATE_INITIALIZING;
2703                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2704                         break;
2705                     }
2706 #endif
2707                     hci_power_transition_to_initializing();
2708                     break;
2709                 case HCI_POWER_OFF:
2710                     // see hci_run
2711                     hci_stack->state = HCI_STATE_HALTING;
2712                     break;
2713                 case HCI_POWER_SLEEP:
2714                     // do nothing
2715                     break;
2716             }
2717             break;
2718 
2719         case HCI_STATE_SLEEPING:
2720             switch (power_mode){
2721                 case HCI_POWER_ON:
2722 
2723 #ifdef HAVE_PLATFORM_IPHONE_OS
2724                     // nothing to do, if H4 supports power management
2725                     if (btstack_control_iphone_power_management_enabled()){
2726                         hci_stack->state = HCI_STATE_INITIALIZING;
2727                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2728                         hci_update_scan_enable();
2729                         break;
2730                     }
2731 #endif
2732                     err = hci_power_control_wake();
2733                     if (err) return err;
2734                     hci_power_transition_to_initializing();
2735                     break;
2736                 case HCI_POWER_OFF:
2737                     hci_stack->state = HCI_STATE_HALTING;
2738                     break;
2739                 case HCI_POWER_SLEEP:
2740                     // do nothing
2741                     break;
2742             }
2743             break;
2744     }
2745 
2746     // create internal event
2747 	hci_emit_state();
2748 
2749 	// trigger next/first action
2750 	hci_run();
2751 
2752     return 0;
2753 }
2754 
2755 
2756 #ifdef ENABLE_CLASSIC
2757 
2758 static void hci_update_scan_enable(void){
2759     // 2 = page scan, 1 = inq scan
2760     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2761     hci_run();
2762 }
2763 
2764 void gap_discoverable_control(uint8_t enable){
2765     if (enable) enable = 1; // normalize argument
2766 
2767     if (hci_stack->discoverable == enable){
2768         hci_emit_discoverable_enabled(hci_stack->discoverable);
2769         return;
2770     }
2771 
2772     hci_stack->discoverable = enable;
2773     hci_update_scan_enable();
2774 }
2775 
2776 void gap_connectable_control(uint8_t enable){
2777     if (enable) enable = 1; // normalize argument
2778 
2779     // don't emit event
2780     if (hci_stack->connectable == enable) return;
2781 
2782     hci_stack->connectable = enable;
2783     hci_update_scan_enable();
2784 }
2785 #endif
2786 
2787 void gap_local_bd_addr(bd_addr_t address_buffer){
2788     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
2789 }
2790 
2791 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2792 static void hci_host_num_completed_packets(void){
2793 
2794     // create packet manually as arrays are not supported and num_commands should not get reduced
2795     hci_reserve_packet_buffer();
2796     uint8_t * packet = hci_get_outgoing_packet_buffer();
2797 
2798     uint16_t size = 0;
2799     uint16_t num_handles = 0;
2800     packet[size++] = 0x35;
2801     packet[size++] = 0x0c;
2802     size++;  // skip param len
2803     size++;  // skip num handles
2804 
2805     // add { handle, packets } entries
2806     btstack_linked_item_t * it;
2807     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
2808         hci_connection_t * connection = (hci_connection_t *) it;
2809         if (connection->num_packets_completed){
2810             little_endian_store_16(packet, size, connection->con_handle);
2811             size += 2;
2812             little_endian_store_16(packet, size, connection->num_packets_completed);
2813             size += 2;
2814             //
2815             num_handles++;
2816             connection->num_packets_completed = 0;
2817         }
2818     }
2819 
2820     packet[2] = size - 3;
2821     packet[3] = num_handles;
2822 
2823     hci_stack->host_completed_packets = 0;
2824 
2825     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2826     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2827 
2828     // release packet buffer for synchronous transport implementations
2829     if (hci_transport_synchronous()){
2830         hci_stack->hci_packet_buffer_reserved = 0;
2831     }
2832 }
2833 #endif
2834 
2835 static void hci_run(void){
2836 
2837     // log_info("hci_run: entered");
2838     btstack_linked_item_t * it;
2839 
2840     // send continuation fragments first, as they block the prepared packet buffer
2841     if (hci_stack->acl_fragmentation_total_size > 0) {
2842         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2843         hci_connection_t *connection = hci_connection_for_handle(con_handle);
2844         if (connection) {
2845             if (hci_can_send_prepared_acl_packet_now(con_handle)){
2846                 hci_send_acl_packet_fragments(connection);
2847                 return;
2848             }
2849         } else {
2850             // connection gone -> discard further fragments
2851             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
2852             hci_stack->acl_fragmentation_total_size = 0;
2853             hci_stack->acl_fragmentation_pos = 0;
2854         }
2855     }
2856 
2857 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2858     // send host num completed packets next as they don't require num_cmd_packets > 0
2859     if (!hci_can_send_comand_packet_transport()) return;
2860     if (hci_stack->host_completed_packets){
2861         hci_host_num_completed_packets();
2862         return;
2863     }
2864 #endif
2865 
2866     if (!hci_can_send_command_packet_now()) return;
2867 
2868     // global/non-connection oriented commands
2869 
2870 #ifdef ENABLE_CLASSIC
2871     // decline incoming connections
2872     if (hci_stack->decline_reason){
2873         uint8_t reason = hci_stack->decline_reason;
2874         hci_stack->decline_reason = 0;
2875         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2876         return;
2877     }
2878     // send scan enable
2879     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
2880         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
2881         hci_stack->new_scan_enable_value = 0xff;
2882         return;
2883     }
2884     // start/stop inquiry
2885     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX){
2886         uint8_t duration = hci_stack->inquiry_state;
2887         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2888         hci_send_cmd(&hci_inquiry, HCI_INQUIRY_LAP, duration, 0);
2889         return;
2890     }
2891     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
2892         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
2893         hci_send_cmd(&hci_inquiry_cancel);
2894         return;
2895     }
2896     // remote name request
2897     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
2898         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
2899         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
2900             hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
2901         return;
2902     }
2903     // pairing
2904     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
2905         uint8_t state = hci_stack->gap_pairing_state;
2906         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
2907         switch (state){
2908             case GAP_PAIRING_STATE_SEND_PIN:
2909                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, strlen(hci_stack->gap_pairing_pin), hci_stack->gap_pairing_pin);
2910                 break;
2911             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
2912                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
2913                 break;
2914             case GAP_PAIRING_STATE_SEND_PASSKEY:
2915                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_passkey);
2916                 break;
2917             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
2918                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
2919                 break;
2920             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
2921                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
2922                 break;
2923             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
2924                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
2925                 break;
2926             default:
2927                 break;
2928         }
2929         return;
2930     }
2931 #endif
2932 
2933 #ifdef ENABLE_BLE
2934     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
2935     if ((hci_stack->state == HCI_STATE_WORKING)
2936     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
2937 
2938 #ifdef ENABLE_LE_CENTRAL
2939         // handle le scan
2940         switch(hci_stack->le_scanning_state){
2941             case LE_START_SCAN:
2942                 hci_stack->le_scanning_state = LE_SCANNING;
2943                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
2944                 return;
2945 
2946             case LE_STOP_SCAN:
2947                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
2948                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
2949                 return;
2950             default:
2951                 break;
2952         }
2953         if (hci_stack->le_scan_type != 0xff){
2954             // defaults: active scanning, accept all advertisement packets
2955             int scan_type = hci_stack->le_scan_type;
2956             hci_stack->le_scan_type = 0xff;
2957             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);
2958             return;
2959         }
2960 #endif
2961 #ifdef ENABLE_LE_PERIPHERAL
2962         // le advertisement control
2963         if (hci_stack->le_advertisements_todo){
2964             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
2965         }
2966         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
2967             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
2968             hci_send_cmd(&hci_le_set_advertise_enable, 0);
2969             return;
2970         }
2971         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
2972             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
2973             hci_send_cmd(&hci_le_set_advertising_parameters,
2974                  hci_stack->le_advertisements_interval_min,
2975                  hci_stack->le_advertisements_interval_max,
2976                  hci_stack->le_advertisements_type,
2977                  hci_stack->le_own_addr_type,
2978                  hci_stack->le_advertisements_direct_address_type,
2979                  hci_stack->le_advertisements_direct_address,
2980                  hci_stack->le_advertisements_channel_map,
2981                  hci_stack->le_advertisements_filter_policy);
2982             return;
2983         }
2984         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
2985             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
2986             uint8_t adv_data_clean[31];
2987             memset(adv_data_clean, 0, sizeof(adv_data_clean));
2988             memcpy(adv_data_clean, hci_stack->le_advertisements_data, hci_stack->le_advertisements_data_len);
2989             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
2990             return;
2991         }
2992         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
2993             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
2994             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len,
2995                 hci_stack->le_scan_response_data);
2996             return;
2997         }
2998         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
2999             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
3000             hci_send_cmd(&hci_le_set_advertise_enable, 1);
3001             return;
3002         }
3003 #endif
3004 
3005 #ifdef ENABLE_LE_CENTRAL
3006         //
3007         // LE Whitelist Management
3008         //
3009 
3010         // check if whitelist needs modification
3011         btstack_linked_list_iterator_t lit;
3012         int modification_pending = 0;
3013         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3014         while (btstack_linked_list_iterator_has_next(&lit)){
3015             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3016             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3017                 modification_pending = 1;
3018                 break;
3019             }
3020         }
3021 
3022         if (modification_pending){
3023             // stop connnecting if modification pending
3024             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
3025                 hci_send_cmd(&hci_le_create_connection_cancel);
3026                 return;
3027             }
3028 
3029             // add/remove entries
3030             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3031             while (btstack_linked_list_iterator_has_next(&lit)){
3032                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3033                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
3034                     entry->state = LE_WHITELIST_ON_CONTROLLER;
3035                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3036                     return;
3037 
3038                 }
3039                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
3040                     bd_addr_t address;
3041                     bd_addr_type_t address_type = entry->address_type;
3042                     memcpy(address, entry->address, 6);
3043                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3044                     btstack_memory_whitelist_entry_free(entry);
3045                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
3046                     return;
3047                 }
3048             }
3049         }
3050 
3051         // start connecting
3052         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
3053             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
3054             bd_addr_t null_addr;
3055             memset(null_addr, 0, 6);
3056             hci_send_cmd(&hci_le_create_connection,
3057                  0x0060,    // scan interval: 60 ms
3058                  0x0030,    // scan interval: 30 ms
3059                  1,         // use whitelist
3060                  0,         // peer address type
3061                  null_addr, // peer bd addr
3062                  hci_stack->le_own_addr_type, // our addr type:
3063                  hci_stack->le_connection_interval_min,    // conn interval min
3064                  hci_stack->le_connection_interval_max,    // conn interval max
3065                  hci_stack->le_connection_latency,         // conn latency
3066                  hci_stack->le_supervision_timeout,        // conn latency
3067                  hci_stack->le_minimum_ce_length,          // min ce length
3068                  hci_stack->le_maximum_ce_length           // max ce length
3069                 );
3070             return;
3071         }
3072 #endif
3073     }
3074 #endif
3075 
3076     // send pending HCI commands
3077     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3078         hci_connection_t * connection = (hci_connection_t *) it;
3079 
3080         switch(connection->state){
3081             case SEND_CREATE_CONNECTION:
3082                 switch(connection->address_type){
3083 #ifdef ENABLE_CLASSIC
3084                     case BD_ADDR_TYPE_CLASSIC:
3085                         log_info("sending hci_create_connection");
3086                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
3087                         break;
3088 #endif
3089                     default:
3090 #ifdef ENABLE_BLE
3091 #ifdef ENABLE_LE_CENTRAL
3092                         log_info("sending hci_le_create_connection");
3093                         hci_send_cmd(&hci_le_create_connection,
3094                              0x0060,    // scan interval: 60 ms
3095                              0x0030,    // scan interval: 30 ms
3096                              0,         // don't use whitelist
3097                              connection->address_type, // peer address type
3098                              connection->address,      // peer bd addr
3099                              hci_stack->le_own_addr_type, // our addr type:
3100                              hci_stack->le_connection_interval_min,    // conn interval min
3101                              hci_stack->le_connection_interval_max,    // conn interval max
3102                              hci_stack->le_connection_latency,         // conn latency
3103                              hci_stack->le_supervision_timeout,        // conn latency
3104                              hci_stack->le_minimum_ce_length,          // min ce length
3105                              hci_stack->le_maximum_ce_length          // max ce length
3106                              );
3107                         connection->state = SENT_CREATE_CONNECTION;
3108 #endif
3109 #endif
3110                         break;
3111                 }
3112                 return;
3113 
3114 #ifdef ENABLE_CLASSIC
3115             case RECEIVED_CONNECTION_REQUEST:
3116                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
3117                 connection->state = ACCEPTED_CONNECTION_REQUEST;
3118                 connection->role  = HCI_ROLE_SLAVE;
3119                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
3120                     hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
3121                 }
3122                 return;
3123 #endif
3124 
3125 #ifdef ENABLE_BLE
3126 #ifdef ENABLE_LE_CENTRAL
3127             case SEND_CANCEL_CONNECTION:
3128                 connection->state = SENT_CANCEL_CONNECTION;
3129                 hci_send_cmd(&hci_le_create_connection_cancel);
3130                 return;
3131 #endif
3132 #endif
3133             case SEND_DISCONNECT:
3134                 connection->state = SENT_DISCONNECT;
3135                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
3136                 return;
3137 
3138             default:
3139                 break;
3140         }
3141 
3142 #ifdef ENABLE_CLASSIC
3143         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
3144             log_info("responding to link key request");
3145             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
3146             link_key_t link_key;
3147             link_key_type_t link_key_type;
3148             if ( hci_stack->link_key_db
3149               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
3150               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
3151                connection->link_key_type = link_key_type;
3152                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
3153             } else {
3154                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
3155             }
3156             return;
3157         }
3158 
3159         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
3160             log_info("denying to pin request");
3161             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
3162             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
3163             return;
3164         }
3165 
3166         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
3167             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
3168             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
3169             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3170                 // tweak authentication requirements
3171                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3172                 if (connection->bonding_flags & BONDING_DEDICATED){
3173                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3174                 }
3175                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
3176                     authreq |= 1;
3177                 }
3178                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3179             } else {
3180                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3181             }
3182             return;
3183         }
3184 
3185         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3186             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
3187             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3188             return;
3189         }
3190 
3191         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3192             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
3193             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3194             return;
3195         }
3196 
3197         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
3198             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
3199             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3200             return;
3201         }
3202 
3203         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3204             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
3205             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
3206             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
3207             return;
3208         }
3209 
3210         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
3211             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3212             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3213             return;
3214         }
3215 
3216         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3217             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3218             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3219             return;
3220         }
3221 #endif
3222 
3223         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
3224             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
3225             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
3226             return;
3227         }
3228 
3229 #ifdef ENABLE_BLE
3230         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
3231             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3232 
3233             uint16_t connection_interval_min = connection->le_conn_interval_min;
3234             connection->le_conn_interval_min = 0;
3235             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
3236                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3237                 0x0000, 0xffff);
3238         }
3239 #endif
3240     }
3241 
3242     hci_connection_t * connection;
3243     switch (hci_stack->state){
3244         case HCI_STATE_INITIALIZING:
3245             hci_initializing_run();
3246             break;
3247 
3248         case HCI_STATE_HALTING:
3249 
3250             log_info("HCI_STATE_HALTING");
3251 
3252             // free whitelist entries
3253 #ifdef ENABLE_BLE
3254 #ifdef ENABLE_LE_CENTRAL
3255             {
3256                 btstack_linked_list_iterator_t lit;
3257                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3258                 while (btstack_linked_list_iterator_has_next(&lit)){
3259                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3260                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3261                     btstack_memory_whitelist_entry_free(entry);
3262                 }
3263             }
3264 #endif
3265 #endif
3266             // close all open connections
3267             connection =  (hci_connection_t *) hci_stack->connections;
3268             if (connection){
3269                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
3270                 if (!hci_can_send_command_packet_now()) return;
3271 
3272                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
3273 
3274                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
3275                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
3276 
3277                 // ... which would be ignored anyway as we shutdown (free) the connection now
3278                 hci_shutdown_connection(connection);
3279 
3280                 // finally, send the disconnect command
3281                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
3282                 return;
3283             }
3284             log_info("HCI_STATE_HALTING, calling off");
3285 
3286             // switch mode
3287             hci_power_control_off();
3288 
3289             log_info("HCI_STATE_HALTING, emitting state");
3290             hci_emit_state();
3291             log_info("HCI_STATE_HALTING, done");
3292             break;
3293 
3294         case HCI_STATE_FALLING_ASLEEP:
3295             switch(hci_stack->substate) {
3296                 case HCI_FALLING_ASLEEP_DISCONNECT:
3297                     log_info("HCI_STATE_FALLING_ASLEEP");
3298                     // close all open connections
3299                     connection =  (hci_connection_t *) hci_stack->connections;
3300 
3301 #ifdef HAVE_PLATFORM_IPHONE_OS
3302                     // don't close connections, if H4 supports power management
3303                     if (btstack_control_iphone_power_management_enabled()){
3304                         connection = NULL;
3305                     }
3306 #endif
3307                     if (connection){
3308 
3309                         // send disconnect
3310                         if (!hci_can_send_command_packet_now()) return;
3311 
3312                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3313                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3314 
3315                         // send disconnected event right away - causes higher layer connections to get closed, too.
3316                         hci_shutdown_connection(connection);
3317                         return;
3318                     }
3319 
3320                     if (hci_classic_supported()){
3321                         // disable page and inquiry scan
3322                         if (!hci_can_send_command_packet_now()) return;
3323 
3324                         log_info("HCI_STATE_HALTING, disabling inq scans");
3325                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3326 
3327                         // continue in next sub state
3328                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3329                         break;
3330                     }
3331                     // no break - fall through for ble-only chips
3332 
3333                 case HCI_FALLING_ASLEEP_COMPLETE:
3334                     log_info("HCI_STATE_HALTING, calling sleep");
3335 #ifdef HAVE_PLATFORM_IPHONE_OS
3336                     // don't actually go to sleep, if H4 supports power management
3337                     if (btstack_control_iphone_power_management_enabled()){
3338                         // SLEEP MODE reached
3339                         hci_stack->state = HCI_STATE_SLEEPING;
3340                         hci_emit_state();
3341                         break;
3342                     }
3343 #endif
3344                     // switch mode
3345                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3346                     hci_emit_state();
3347                     break;
3348 
3349                 default:
3350                     break;
3351             }
3352             break;
3353 
3354         default:
3355             break;
3356     }
3357 }
3358 
3359 int hci_send_cmd_packet(uint8_t *packet, int size){
3360     // house-keeping
3361 
3362     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3363         hci_stack->loopback_mode = packet[3];
3364     }
3365 
3366 #ifdef ENABLE_CLASSIC
3367     bd_addr_t addr;
3368     hci_connection_t * conn;
3369 
3370     // create_connection?
3371     if (IS_COMMAND(packet, hci_create_connection)){
3372         reverse_bd_addr(&packet[3], addr);
3373         log_info("Create_connection to %s", bd_addr_to_str(addr));
3374 
3375         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3376         if (!conn){
3377             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3378             if (!conn){
3379                 // notify client that alloc failed
3380                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3381                 return 0; // don't sent packet to controller
3382             }
3383             conn->state = SEND_CREATE_CONNECTION;
3384         }
3385         log_info("conn state %u", conn->state);
3386         switch (conn->state){
3387             // if connection active exists
3388             case OPEN:
3389                 // and OPEN, emit connection complete command, don't send to controller
3390                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3391                 return 0;
3392             case SEND_CREATE_CONNECTION:
3393                 // connection created by hci, e.g. dedicated bonding
3394                 break;
3395             default:
3396                 // otherwise, just ignore as it is already in the open process
3397                 return 0;
3398         }
3399         conn->state = SENT_CREATE_CONNECTION;
3400     }
3401 
3402     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3403         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3404     }
3405     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3406         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3407     }
3408 
3409     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3410         if (hci_stack->link_key_db){
3411             reverse_bd_addr(&packet[3], addr);
3412             hci_stack->link_key_db->delete_link_key(addr);
3413         }
3414     }
3415 
3416     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3417     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3418         reverse_bd_addr(&packet[3], addr);
3419         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3420         if (conn){
3421             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3422         }
3423     }
3424 
3425     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3426     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3427     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3428     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3429         reverse_bd_addr(&packet[3], addr);
3430         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3431         if (conn){
3432             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3433         }
3434     }
3435 
3436 #ifdef ENABLE_SCO_OVER_HCI
3437     // setup_synchronous_connection? Voice setting at offset 22
3438     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3439         // TODO: compare to current setting if sco connection already active
3440         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3441     }
3442     // accept_synchronus_connection? Voice setting at offset 18
3443     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3444         // TODO: compare to current setting if sco connection already active
3445         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3446     }
3447 #endif
3448 #endif
3449 
3450 #ifdef ENABLE_BLE
3451 #ifdef ENABLE_LE_PERIPHERAL
3452     if (IS_COMMAND(packet, hci_le_set_random_address)){
3453         hci_stack->le_random_address_set = 1;
3454         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3455     }
3456     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3457         hci_stack->le_advertisements_active = packet[3];
3458     }
3459 #endif
3460 #ifdef ENABLE_LE_CENTRAL
3461     if (IS_COMMAND(packet, hci_le_create_connection)){
3462         // white list used?
3463         uint8_t initiator_filter_policy = packet[7];
3464         switch (initiator_filter_policy){
3465             case 0:
3466                 // whitelist not used
3467                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3468                 break;
3469             case 1:
3470                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3471                 break;
3472             default:
3473                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3474                 break;
3475         }
3476     }
3477     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3478         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3479     }
3480 #endif
3481 #endif
3482 
3483     hci_stack->num_cmd_packets--;
3484 
3485     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3486     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3487 
3488     // release packet buffer for synchronous transport implementations
3489     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
3490         hci_stack->hci_packet_buffer_reserved = 0;
3491     }
3492 
3493     return err;
3494 }
3495 
3496 // disconnect because of security block
3497 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3498     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3499     if (!connection) return;
3500     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3501 }
3502 
3503 
3504 // Configure Secure Simple Pairing
3505 
3506 #ifdef ENABLE_CLASSIC
3507 
3508 // enable will enable SSP during init
3509 void gap_ssp_set_enable(int enable){
3510     hci_stack->ssp_enable = enable;
3511 }
3512 
3513 static int hci_local_ssp_activated(void){
3514     return gap_ssp_supported() && hci_stack->ssp_enable;
3515 }
3516 
3517 // if set, BTstack will respond to io capability request using authentication requirement
3518 void gap_ssp_set_io_capability(int io_capability){
3519     hci_stack->ssp_io_capability = io_capability;
3520 }
3521 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3522     hci_stack->ssp_authentication_requirement = authentication_requirement;
3523 }
3524 
3525 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3526 void gap_ssp_set_auto_accept(int auto_accept){
3527     hci_stack->ssp_auto_accept = auto_accept;
3528 }
3529 #endif
3530 
3531 // va_list part of hci_send_cmd
3532 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3533     if (!hci_can_send_command_packet_now()){
3534         log_error("hci_send_cmd called but cannot send packet now");
3535         return 0;
3536     }
3537 
3538     // for HCI INITIALIZATION
3539     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3540     hci_stack->last_cmd_opcode = cmd->opcode;
3541 
3542     hci_reserve_packet_buffer();
3543     uint8_t * packet = hci_stack->hci_packet_buffer;
3544     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3545     return hci_send_cmd_packet(packet, size);
3546 }
3547 
3548 /**
3549  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3550  */
3551 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3552     va_list argptr;
3553     va_start(argptr, cmd);
3554     int res = hci_send_cmd_va_arg(cmd, argptr);
3555     va_end(argptr);
3556     return res;
3557 }
3558 
3559 // Create various non-HCI events.
3560 // TODO: generalize, use table similar to hci_create_command
3561 
3562 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3563     // dump packet
3564     if (dump) {
3565         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3566     }
3567 
3568     // dispatch to all event handlers
3569     btstack_linked_list_iterator_t it;
3570     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3571     while (btstack_linked_list_iterator_has_next(&it)){
3572         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3573         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3574     }
3575 }
3576 
3577 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3578     if (!hci_stack->acl_packet_handler) return;
3579     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3580 }
3581 
3582 #ifdef ENABLE_CLASSIC
3583 static void hci_notify_if_sco_can_send_now(void){
3584     // notify SCO sender if waiting
3585     if (!hci_stack->sco_waiting_for_can_send_now) return;
3586     if (hci_can_send_sco_packet_now()){
3587         hci_stack->sco_waiting_for_can_send_now = 0;
3588         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3589         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3590         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3591     }
3592 }
3593 
3594 // parsing end emitting has been merged to reduce code size
3595 static void gap_inquiry_explode(uint8_t * packet){
3596     uint8_t event[15+GAP_INQUIRY_MAX_NAME_LEN];
3597 
3598     uint8_t * eir_data;
3599     ad_context_t context;
3600     const uint8_t * name;
3601     uint8_t         name_len;
3602 
3603     int event_type = hci_event_packet_get_type(packet);
3604     int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1;    // 2 for old event, 1 otherwise
3605     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
3606 
3607     // event[1] is set at the end
3608     int i;
3609     for (i=0; i<num_responses;i++){
3610         memset(event, 0, sizeof(event));
3611         event[0] = GAP_EVENT_INQUIRY_RESULT;
3612         uint8_t event_size = 18;    // if name is not set by EIR
3613 
3614         memcpy(&event[2],  &packet[3 +                                             i*6], 6); // bd_addr
3615         event[8] =          packet[3 + num_responses*(6)                         + i*1];     // page_scan_repetition_mode
3616         memcpy(&event[9],  &packet[3 + num_responses*(6+1+num_reserved_fields)   + i*3], 3); // class of device
3617         memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset
3618 
3619         switch (event_type){
3620             case HCI_EVENT_INQUIRY_RESULT:
3621                 // 14,15,16,17 = 0, size 18
3622                 break;
3623             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3624                 event[14] = 1;
3625                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3626                 // 16,17 = 0, size 18
3627                 break;
3628             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3629                 event[14] = 1;
3630                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3631                 // for EIR packets, there is only one reponse in it
3632                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
3633                 name = NULL;
3634                 // EIR data is 240 bytes in EIR event
3635                 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
3636                     uint8_t data_type    = ad_iterator_get_data_type(&context);
3637                     uint8_t data_size    = ad_iterator_get_data_len(&context);
3638                     const uint8_t * data = ad_iterator_get_data(&context);
3639                     // Prefer Complete Local Name over Shortend Local Name
3640                     switch (data_type){
3641                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
3642                             if (name) continue;
3643                             /* explicit fall-through */
3644                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
3645                             name = data;
3646                             name_len = data_size;
3647                             break;
3648                         default:
3649                             break;
3650                     }
3651                 }
3652                 if (name){
3653                     event[16] = 1;
3654                     // truncate name if needed
3655                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
3656                     event[17] = len;
3657                     memcpy(&event[18], name, len);
3658                     event_size += len;
3659                 }
3660                 break;
3661         }
3662         event[1] = event_size - 2;
3663         hci_emit_event(event, event_size, 1);
3664     }
3665 }
3666 #endif
3667 
3668 void hci_emit_state(void){
3669     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3670     uint8_t event[3];
3671     event[0] = BTSTACK_EVENT_STATE;
3672     event[1] = sizeof(event) - 2;
3673     event[2] = hci_stack->state;
3674     hci_emit_event(event, sizeof(event), 1);
3675 }
3676 
3677 #ifdef ENABLE_CLASSIC
3678 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3679     uint8_t event[13];
3680     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3681     event[1] = sizeof(event) - 2;
3682     event[2] = status;
3683     little_endian_store_16(event, 3, con_handle);
3684     reverse_bd_addr(address, &event[5]);
3685     event[11] = 1; // ACL connection
3686     event[12] = 0; // encryption disabled
3687     hci_emit_event(event, sizeof(event), 1);
3688 }
3689 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3690     if (disable_l2cap_timeouts) return;
3691     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3692     uint8_t event[4];
3693     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3694     event[1] = sizeof(event) - 2;
3695     little_endian_store_16(event, 2, conn->con_handle);
3696     hci_emit_event(event, sizeof(event), 1);
3697 }
3698 #endif
3699 
3700 #ifdef ENABLE_BLE
3701 #ifdef ENABLE_LE_CENTRAL
3702 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3703     uint8_t event[21];
3704     event[0] = HCI_EVENT_LE_META;
3705     event[1] = sizeof(event) - 2;
3706     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
3707     event[3] = status;
3708     little_endian_store_16(event, 4, con_handle);
3709     event[6] = 0; // TODO: role
3710     event[7] = address_type;
3711     reverse_bd_addr(address, &event[8]);
3712     little_endian_store_16(event, 14, 0); // interval
3713     little_endian_store_16(event, 16, 0); // latency
3714     little_endian_store_16(event, 18, 0); // supervision timeout
3715     event[20] = 0; // master clock accuracy
3716     hci_emit_event(event, sizeof(event), 1);
3717 }
3718 #endif
3719 #endif
3720 
3721 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
3722     uint8_t event[6];
3723     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
3724     event[1] = sizeof(event) - 2;
3725     event[2] = 0; // status = OK
3726     little_endian_store_16(event, 3, con_handle);
3727     event[5] = reason;
3728     hci_emit_event(event, sizeof(event), 1);
3729 }
3730 
3731 static void hci_emit_nr_connections_changed(void){
3732     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
3733     uint8_t event[3];
3734     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3735     event[1] = sizeof(event) - 2;
3736     event[2] = nr_hci_connections();
3737     hci_emit_event(event, sizeof(event), 1);
3738 }
3739 
3740 static void hci_emit_hci_open_failed(void){
3741     log_info("BTSTACK_EVENT_POWERON_FAILED");
3742     uint8_t event[2];
3743     event[0] = BTSTACK_EVENT_POWERON_FAILED;
3744     event[1] = sizeof(event) - 2;
3745     hci_emit_event(event, sizeof(event), 1);
3746 }
3747 
3748 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
3749     log_info("hci_emit_dedicated_bonding_result %u ", status);
3750     uint8_t event[9];
3751     int pos = 0;
3752     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
3753     event[pos++] = sizeof(event) - 2;
3754     event[pos++] = status;
3755     reverse_bd_addr(address, &event[pos]);
3756     hci_emit_event(event, sizeof(event), 1);
3757 }
3758 
3759 
3760 #ifdef ENABLE_CLASSIC
3761 
3762 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3763     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3764     uint8_t event[5];
3765     int pos = 0;
3766     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3767     event[pos++] = sizeof(event) - 2;
3768     little_endian_store_16(event, 2, con_handle);
3769     pos += 2;
3770     event[pos++] = level;
3771     hci_emit_event(event, sizeof(event), 1);
3772 }
3773 
3774 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
3775     if (!connection) return LEVEL_0;
3776     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
3777     return gap_security_level_for_link_key_type(connection->link_key_type);
3778 }
3779 
3780 static void hci_emit_discoverable_enabled(uint8_t enabled){
3781     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
3782     uint8_t event[3];
3783     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
3784     event[1] = sizeof(event) - 2;
3785     event[2] = enabled;
3786     hci_emit_event(event, sizeof(event), 1);
3787 }
3788 
3789 #ifdef ENABLE_CLASSIC
3790 // query if remote side supports eSCO
3791 int hci_remote_esco_supported(hci_con_handle_t con_handle){
3792     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3793     if (!connection) return 0;
3794     return connection->remote_supported_feature_eSCO;
3795 }
3796 
3797 // query if remote side supports SSP
3798 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
3799     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3800     if (!connection) return 0;
3801     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
3802 }
3803 
3804 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
3805     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3806 }
3807 #endif
3808 
3809 // GAP API
3810 /**
3811  * @bbrief enable/disable bonding. default is enabled
3812  * @praram enabled
3813  */
3814 void gap_set_bondable_mode(int enable){
3815     hci_stack->bondable = enable ? 1 : 0;
3816 }
3817 /**
3818  * @brief Get bondable mode.
3819  * @return 1 if bondable
3820  */
3821 int gap_get_bondable_mode(void){
3822     return hci_stack->bondable;
3823 }
3824 
3825 /**
3826  * @brief map link keys to security levels
3827  */
3828 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
3829     switch (link_key_type){
3830         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
3831             return LEVEL_4;
3832         case COMBINATION_KEY:
3833         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
3834             return LEVEL_3;
3835         default:
3836             return LEVEL_2;
3837     }
3838 }
3839 
3840 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
3841     log_info("gap_mitm_protection_required_for_security_level %u", level);
3842     return level > LEVEL_2;
3843 }
3844 
3845 /**
3846  * @brief get current security level
3847  */
3848 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
3849     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3850     if (!connection) return LEVEL_0;
3851     return gap_security_level_for_connection(connection);
3852 }
3853 
3854 /**
3855  * @brief request connection to device to
3856  * @result GAP_AUTHENTICATION_RESULT
3857  */
3858 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
3859     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3860     if (!connection){
3861         hci_emit_security_level(con_handle, LEVEL_0);
3862         return;
3863     }
3864     gap_security_level_t current_level = gap_security_level(con_handle);
3865     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
3866     if (current_level >= requested_level){
3867         hci_emit_security_level(con_handle, current_level);
3868         return;
3869     }
3870 
3871     connection->requested_security_level = requested_level;
3872 
3873 #if 0
3874     // sending encryption request without a link key results in an error.
3875     // TODO: figure out how to use it properly
3876 
3877     // would enabling ecnryption suffice (>= LEVEL_2)?
3878     if (hci_stack->link_key_db){
3879         link_key_type_t link_key_type;
3880         link_key_t      link_key;
3881         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3882             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3883                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3884                 return;
3885             }
3886         }
3887     }
3888 #endif
3889 
3890     // try to authenticate connection
3891     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3892     hci_run();
3893 }
3894 
3895 /**
3896  * @brief start dedicated bonding with device. disconnect after bonding
3897  * @param device
3898  * @param request MITM protection
3899  * @result GAP_DEDICATED_BONDING_COMPLETE
3900  */
3901 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3902 
3903     // create connection state machine
3904     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3905 
3906     if (!connection){
3907         return BTSTACK_MEMORY_ALLOC_FAILED;
3908     }
3909 
3910     // delete linkn key
3911     gap_drop_link_key_for_bd_addr(device);
3912 
3913     // configure LEVEL_2/3, dedicated bonding
3914     connection->state = SEND_CREATE_CONNECTION;
3915     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
3916     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
3917     connection->bonding_flags = BONDING_DEDICATED;
3918 
3919     // wait for GAP Security Result and send GAP Dedicated Bonding complete
3920 
3921     // handle: connnection failure (connection complete != ok)
3922     // handle: authentication failure
3923     // handle: disconnect on done
3924 
3925     hci_run();
3926 
3927     return 0;
3928 }
3929 #endif
3930 
3931 void gap_set_local_name(const char * local_name){
3932     hci_stack->local_name = local_name;
3933 }
3934 
3935 
3936 #ifdef ENABLE_BLE
3937 
3938 #ifdef ENABLE_LE_CENTRAL
3939 void gap_start_scan(void){
3940     if (hci_stack->le_scanning_state == LE_SCANNING) return;
3941     hci_stack->le_scanning_state = LE_START_SCAN;
3942     hci_run();
3943 }
3944 
3945 void gap_stop_scan(void){
3946     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return;
3947     hci_stack->le_scanning_state = LE_STOP_SCAN;
3948     hci_run();
3949 }
3950 
3951 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
3952     hci_stack->le_scan_type     = scan_type;
3953     hci_stack->le_scan_interval = scan_interval;
3954     hci_stack->le_scan_window   = scan_window;
3955     hci_run();
3956 }
3957 
3958 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
3959     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3960     if (!conn){
3961         log_info("gap_connect: no connection exists yet, creating context");
3962         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3963         if (!conn){
3964             // notify client that alloc failed
3965             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3966             log_info("gap_connect: failed to alloc hci_connection_t");
3967             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
3968         }
3969         conn->state = SEND_CREATE_CONNECTION;
3970         log_info("gap_connect: send create connection next");
3971         hci_run();
3972         return 0;
3973     }
3974 
3975     if (!hci_is_le_connection(conn) ||
3976         conn->state == SEND_CREATE_CONNECTION ||
3977         conn->state == SENT_CREATE_CONNECTION) {
3978         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
3979         log_error("gap_connect: classic connection or connect is already being created");
3980         return GATT_CLIENT_IN_WRONG_STATE;
3981     }
3982 
3983     log_info("gap_connect: context exists with state %u", conn->state);
3984     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
3985     hci_run();
3986     return 0;
3987 }
3988 
3989 // @assumption: only a single outgoing LE Connection exists
3990 static hci_connection_t * gap_get_outgoing_connection(void){
3991     btstack_linked_item_t *it;
3992     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3993         hci_connection_t * conn = (hci_connection_t *) it;
3994         if (!hci_is_le_connection(conn)) continue;
3995         switch (conn->state){
3996             case SEND_CREATE_CONNECTION:
3997             case SENT_CREATE_CONNECTION:
3998                 return conn;
3999             default:
4000                 break;
4001         };
4002     }
4003     return NULL;
4004 }
4005 
4006 uint8_t gap_connect_cancel(void){
4007     hci_connection_t * conn = gap_get_outgoing_connection();
4008     if (!conn) return 0;
4009     switch (conn->state){
4010         case SEND_CREATE_CONNECTION:
4011             // skip sending create connection and emit event instead
4012             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
4013             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
4014             btstack_memory_hci_connection_free( conn );
4015             break;
4016         case SENT_CREATE_CONNECTION:
4017             // request to send cancel connection
4018             conn->state = SEND_CANCEL_CONNECTION;
4019             hci_run();
4020             break;
4021         default:
4022             break;
4023     }
4024     return 0;
4025 }
4026 #endif
4027 
4028 #ifdef ENABLE_LE_CENTRAL
4029 /**
4030  * @brief Set connection parameters for outgoing connections
4031  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
4032  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
4033  * @param conn_latency, default: 4
4034  * @param supervision_timeout (unit: 10ms), default: 720 ms
4035  * @param min_ce_length (unit: 0.625ms), default: 10 ms
4036  * @param max_ce_length (unit: 0.625ms), default: 30 ms
4037  */
4038 
4039 void gap_set_connection_parameters(uint16_t conn_interval_min, uint16_t conn_interval_max,
4040     uint16_t conn_latency, uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
4041     hci_stack->le_connection_interval_min = conn_interval_min;
4042     hci_stack->le_connection_interval_max = conn_interval_max;
4043     hci_stack->le_connection_latency = conn_latency;
4044     hci_stack->le_supervision_timeout = supervision_timeout;
4045     hci_stack->le_minimum_ce_length = min_ce_length;
4046     hci_stack->le_maximum_ce_length = max_ce_length;
4047 }
4048 #endif
4049 
4050 /**
4051  * @brief Updates the connection parameters for a given LE connection
4052  * @param handle
4053  * @param conn_interval_min (unit: 1.25ms)
4054  * @param conn_interval_max (unit: 1.25ms)
4055  * @param conn_latency
4056  * @param supervision_timeout (unit: 10ms)
4057  * @returns 0 if ok
4058  */
4059 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4060     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4061     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4062     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4063     connection->le_conn_interval_min = conn_interval_min;
4064     connection->le_conn_interval_max = conn_interval_max;
4065     connection->le_conn_latency = conn_latency;
4066     connection->le_supervision_timeout = supervision_timeout;
4067     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
4068     hci_run();
4069     return 0;
4070 }
4071 
4072 /**
4073  * @brief Request an update of the connection parameter for a given LE connection
4074  * @param handle
4075  * @param conn_interval_min (unit: 1.25ms)
4076  * @param conn_interval_max (unit: 1.25ms)
4077  * @param conn_latency
4078  * @param supervision_timeout (unit: 10ms)
4079  * @returns 0 if ok
4080  */
4081 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4082     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4083     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4084     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4085     connection->le_conn_interval_min = conn_interval_min;
4086     connection->le_conn_interval_max = conn_interval_max;
4087     connection->le_conn_latency = conn_latency;
4088     connection->le_supervision_timeout = supervision_timeout;
4089     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
4090     hci_run();
4091     return 0;
4092 }
4093 
4094 #ifdef ENABLE_LE_PERIPHERAL
4095 
4096 static void gap_advertisments_changed(void){
4097     // disable advertisements before updating adv, scan data, or adv params
4098     if (hci_stack->le_advertisements_active){
4099         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
4100     }
4101     hci_run();
4102 }
4103 
4104 /**
4105  * @brief Set Advertisement Data
4106  * @param advertising_data_length
4107  * @param advertising_data (max 31 octets)
4108  * @note data is not copied, pointer has to stay valid
4109  */
4110 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
4111     hci_stack->le_advertisements_data_len = advertising_data_length;
4112     hci_stack->le_advertisements_data = advertising_data;
4113     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4114     gap_advertisments_changed();
4115 }
4116 
4117 /**
4118  * @brief Set Scan Response Data
4119  * @param advertising_data_length
4120  * @param advertising_data (max 31 octets)
4121  * @note data is not copied, pointer has to stay valid
4122  */
4123 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
4124     hci_stack->le_scan_response_data_len = scan_response_data_length;
4125     hci_stack->le_scan_response_data = scan_response_data;
4126     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4127     gap_advertisments_changed();
4128 }
4129 
4130 /**
4131  * @brief Set Advertisement Parameters
4132  * @param adv_int_min
4133  * @param adv_int_max
4134  * @param adv_type
4135  * @param direct_address_type
4136  * @param direct_address
4137  * @param channel_map
4138  * @param filter_policy
4139  *
4140  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
4141  */
4142  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4143     uint8_t direct_address_typ, bd_addr_t direct_address,
4144     uint8_t channel_map, uint8_t filter_policy) {
4145 
4146     hci_stack->le_advertisements_interval_min = adv_int_min;
4147     hci_stack->le_advertisements_interval_max = adv_int_max;
4148     hci_stack->le_advertisements_type = adv_type;
4149     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
4150     hci_stack->le_advertisements_channel_map = channel_map;
4151     hci_stack->le_advertisements_filter_policy = filter_policy;
4152     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
4153 
4154     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4155     gap_advertisments_changed();
4156  }
4157 
4158 /**
4159  * @brief Enable/Disable Advertisements
4160  * @param enabled
4161  */
4162 void gap_advertisements_enable(int enabled){
4163     hci_stack->le_advertisements_enabled = enabled;
4164     if (enabled && !hci_stack->le_advertisements_active){
4165         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
4166     }
4167     if (!enabled && hci_stack->le_advertisements_active){
4168         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
4169     }
4170     hci_run();
4171 }
4172 
4173 #endif
4174 
4175 void hci_le_set_own_address_type(uint8_t own_address_type){
4176     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
4177     if (own_address_type == hci_stack->le_own_addr_type) return;
4178     hci_stack->le_own_addr_type = own_address_type;
4179 
4180 #ifdef ENABLE_LE_PERIPHERAL
4181     // update advertisement parameters, too
4182     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4183     gap_advertisments_changed();
4184 #endif
4185 #ifdef ENABLE_LE_CENTRAL
4186     // note: we don't update scan parameters or modify ongoing connection attempts
4187 #endif
4188 }
4189 
4190 #endif
4191 
4192 uint8_t gap_disconnect(hci_con_handle_t handle){
4193     hci_connection_t * conn = hci_connection_for_handle(handle);
4194     if (!conn){
4195         hci_emit_disconnection_complete(handle, 0);
4196         return 0;
4197     }
4198     conn->state = SEND_DISCONNECT;
4199     hci_run();
4200     return 0;
4201 }
4202 
4203 /**
4204  * @brief Get connection type
4205  * @param con_handle
4206  * @result connection_type
4207  */
4208 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
4209     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4210     if (!conn) return GAP_CONNECTION_INVALID;
4211     switch (conn->address_type){
4212         case BD_ADDR_TYPE_LE_PUBLIC:
4213         case BD_ADDR_TYPE_LE_RANDOM:
4214             return GAP_CONNECTION_LE;
4215         case BD_ADDR_TYPE_SCO:
4216             return GAP_CONNECTION_SCO;
4217         case BD_ADDR_TYPE_CLASSIC:
4218             return GAP_CONNECTION_ACL;
4219         default:
4220             return GAP_CONNECTION_INVALID;
4221     }
4222 }
4223 
4224 #ifdef ENABLE_BLE
4225 
4226 #ifdef ENABLE_LE_CENTRAL
4227 /**
4228  * @brief Auto Connection Establishment - Start Connecting to device
4229  * @param address_typ
4230  * @param address
4231  * @returns 0 if ok
4232  */
4233 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
4234     // check capacity
4235     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
4236     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
4237     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
4238     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
4239     entry->address_type = address_type;
4240     memcpy(entry->address, address, 6);
4241     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4242     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
4243     hci_run();
4244     return 0;
4245 }
4246 
4247 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
4248     btstack_linked_list_iterator_t it;
4249     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4250     while (btstack_linked_list_iterator_has_next(&it)){
4251         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4252         if (entry->address_type != address_type) continue;
4253         if (memcmp(entry->address, address, 6) != 0) continue;
4254         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4255             // remove from controller if already present
4256             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4257             continue;
4258         }
4259         // direclty remove entry from whitelist
4260         btstack_linked_list_iterator_remove(&it);
4261         btstack_memory_whitelist_entry_free(entry);
4262     }
4263 }
4264 
4265 /**
4266  * @brief Auto Connection Establishment - Stop Connecting to device
4267  * @param address_typ
4268  * @param address
4269  * @returns 0 if ok
4270  */
4271 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
4272     hci_remove_from_whitelist(address_type, address);
4273     hci_run();
4274     return 0;
4275 }
4276 
4277 /**
4278  * @brief Auto Connection Establishment - Stop everything
4279  * @note  Convenience function to stop all active auto connection attempts
4280  */
4281 void gap_auto_connection_stop_all(void){
4282     btstack_linked_list_iterator_t it;
4283     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4284     while (btstack_linked_list_iterator_has_next(&it)){
4285         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4286         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4287             // remove from controller if already present
4288             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4289             continue;
4290         }
4291         // directly remove entry from whitelist
4292         btstack_linked_list_iterator_remove(&it);
4293         btstack_memory_whitelist_entry_free(entry);
4294     }
4295     hci_run();
4296 }
4297 #endif
4298 #endif
4299 
4300 #ifdef ENABLE_CLASSIC
4301 /**
4302  * @brief Set Extended Inquiry Response data
4303  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
4304  * @note has to be done before stack starts up
4305  */
4306 void gap_set_extended_inquiry_response(const uint8_t * data){
4307     hci_stack->eir_data = data;
4308 }
4309 
4310 /**
4311  * @brief Start GAP Classic Inquiry
4312  * @param duration in 1.28s units
4313  * @return 0 if ok
4314  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
4315  */
4316 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
4317     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4318     if (duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN || duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX){
4319         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
4320     }
4321     hci_stack->inquiry_state = duration_in_1280ms_units;
4322     hci_run();
4323     return 0;
4324 }
4325 
4326 /**
4327  * @brief Stop GAP Classic Inquiry
4328  * @returns 0 if ok
4329  */
4330 int gap_inquiry_stop(void){
4331     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN || hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX) {
4332         // emit inquiry complete event, before it even started
4333         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
4334         hci_emit_event(event, sizeof(event), 1);
4335         return 0;
4336     }
4337     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
4338     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
4339     hci_run();
4340     return 0;
4341 }
4342 
4343 
4344 /**
4345  * @brief Remote Name Request
4346  * @param addr
4347  * @param page_scan_repetition_mode
4348  * @param clock_offset only used when bit 15 is set
4349  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
4350  */
4351 int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
4352     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4353     memcpy(hci_stack->remote_name_addr, addr, 6);
4354     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
4355     hci_stack->remote_name_clock_offset = clock_offset;
4356     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
4357     hci_run();
4358     return 0;
4359 }
4360 
4361 static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){
4362     hci_stack->gap_pairing_state = state;
4363     memcpy(hci_stack->gap_pairing_addr, addr, 6);
4364     hci_run();
4365     return 0;
4366 }
4367 
4368 /**
4369  * @brief Legacy Pairing Pin Code Response
4370  * @param addr
4371  * @param pin
4372  * @return 0 if ok
4373  */
4374 int gap_pin_code_response(bd_addr_t addr, const char * pin){
4375     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4376     hci_stack->gap_pairing_pin = pin;
4377     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
4378 }
4379 
4380 /**
4381  * @brief Abort Legacy Pairing
4382  * @param addr
4383  * @param pin
4384  * @return 0 if ok
4385  */
4386 int gap_pin_code_negative(bd_addr_t addr){
4387     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4388     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
4389 }
4390 
4391 /**
4392  * @brief SSP Passkey Response
4393  * @param addr
4394  * @param passkey
4395  * @return 0 if ok
4396  */
4397 int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){
4398     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4399     hci_stack->gap_pairing_passkey = passkey;
4400     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
4401 }
4402 
4403 /**
4404  * @brief Abort SSP Passkey Entry/Pairing
4405  * @param addr
4406  * @param pin
4407  * @return 0 if ok
4408  */
4409 int gap_ssp_passkey_negative(bd_addr_t addr){
4410     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4411     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
4412 }
4413 
4414 /**
4415  * @brief Accept SSP Numeric Comparison
4416  * @param addr
4417  * @param passkey
4418  * @return 0 if ok
4419  */
4420 int gap_ssp_confirmation_response(bd_addr_t addr){
4421     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4422     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
4423 }
4424 
4425 /**
4426  * @brief Abort SSP Numeric Comparison/Pairing
4427  * @param addr
4428  * @param pin
4429  * @return 0 if ok
4430  */
4431 int gap_ssp_confirmation_negative(bd_addr_t addr){
4432     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4433     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
4434 }
4435 
4436 /**
4437  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
4438  * @param inquiry_mode see bluetooth_defines.h
4439  */
4440 void hci_set_inquiry_mode(inquiry_mode_t mode){
4441     hci_stack->inquiry_mode = mode;
4442 }
4443 
4444 /**
4445  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
4446  */
4447 void hci_set_sco_voice_setting(uint16_t voice_setting){
4448     hci_stack->sco_voice_setting = voice_setting;
4449 }
4450 
4451 /**
4452  * @brief Get SCO Voice Setting
4453  * @return current voice setting
4454  */
4455 uint16_t hci_get_sco_voice_setting(void){
4456     return hci_stack->sco_voice_setting;
4457 }
4458 
4459 /** @brief Get SCO packet length for current SCO Voice setting
4460  *  @note  Using SCO packets of the exact length is required for USB transfer
4461  *  @return Length of SCO packets in bytes (not audio frames)
4462  */
4463 int hci_get_sco_packet_length(void){
4464     // see Core Spec for H2 USB Transfer.
4465     if (hci_stack->sco_voice_setting & 0x0020) return 51;
4466     return 27;
4467 }
4468 #endif
4469 
4470 
4471 HCI_STATE hci_get_state(void){
4472     return hci_stack->state;
4473 }
4474 
4475 
4476 /**
4477  * @brief Set callback for Bluetooth Hardware Error
4478  */
4479 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
4480     hci_stack->hardware_error_callback = fn;
4481 }
4482 
4483 void hci_disconnect_all(void){
4484     btstack_linked_list_iterator_t it;
4485     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4486     while (btstack_linked_list_iterator_has_next(&it)){
4487         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4488         if (con->state == SENT_DISCONNECT) continue;
4489         con->state = SEND_DISCONNECT;
4490     }
4491     hci_run();
4492 }
4493 
4494 uint16_t hci_get_manufacturer(void){
4495     return hci_stack->manufacturer;
4496 }
4497