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