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