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