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