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