xref: /btstack/src/hci.c (revision 55597469a76c95fba779a0a01477ef0cdf7217d2)
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 /*
39  *  hci.c
40  *
41  *  Created by Matthias Ringwald on 4/29/09.
42  *
43  */
44 
45 #include "btstack_config.h"
46 
47 
48 #ifdef HAVE_EMBEDDED_TICK
49 #include "btstack_run_loop_embedded.h"
50 #endif
51 
52 #ifdef HAVE_PLATFORM_IPHONE_OS
53 #include "../port/ios/src/btstack_control_iphone.h"
54 #endif
55 
56 #ifdef ENABLE_BLE
57 #include "gap.h"
58 #endif
59 
60 #include <stdarg.h>
61 #include <string.h>
62 #include <stdio.h>
63 #include <inttypes.h>
64 
65 #include "btstack_debug.h"
66 #include "btstack_event.h"
67 #include "btstack_linked_list.h"
68 #include "btstack_memory.h"
69 #include "gap.h"
70 #include "hci.h"
71 #include "hci_cmd.h"
72 #include "hci_dump.h"
73 
74 
75 #define HCI_CONNECTION_TIMEOUT_MS 10000
76 #define HCI_RESET_RESEND_TIMEOUT_MS 200
77 
78 // prototypes
79 static void hci_update_scan_enable(void);
80 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
81 static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
82 static void hci_connection_timestamp(hci_connection_t *connection);
83 static int  hci_power_control_on(void);
84 static void hci_power_control_off(void);
85 static void hci_state_reset(void);
86 static void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status);
87 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
88 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
89 static void hci_emit_nr_connections_changed(void);
90 static void hci_emit_hci_open_failed(void);
91 static void hci_emit_discoverable_enabled(uint8_t enabled);
92 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
93 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
94 static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
95 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
96 static void hci_notify_if_sco_can_send_now(void);
97 static void hci_run(void);
98 static int  hci_is_le_connection(hci_connection_t * connection);
99 static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
100 static int  hci_local_ssp_activated(void);
101 static int  hci_remote_ssp_supported(hci_con_handle_t con_handle);
102 
103 #ifdef ENABLE_BLE
104 // called from test/ble_client/advertising_data_parser.c
105 void le_handle_advertisement_report(uint8_t *packet, int size);
106 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address);
107 #endif
108 
109 // the STACK is here
110 #ifndef HAVE_MALLOC
111 static hci_stack_t   hci_stack_static;
112 #endif
113 static hci_stack_t * hci_stack = NULL;
114 
115 // test helper
116 static uint8_t disable_l2cap_timeouts = 0;
117 
118 /**
119  * create connection for given address
120  *
121  * @return connection OR NULL, if no memory left
122  */
123 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
124     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
125     hci_connection_t * conn = btstack_memory_hci_connection_get();
126     if (!conn) return NULL;
127     memset(conn, 0, sizeof(hci_connection_t));
128     bd_addr_copy(conn->address, addr);
129     conn->address_type = addr_type;
130     conn->con_handle = 0xffff;
131     conn->authentication_flags = AUTH_FLAGS_NONE;
132     conn->bonding_flags = 0;
133     conn->requested_security_level = LEVEL_0;
134     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
135     btstack_run_loop_set_timer_context(&conn->timeout, conn);
136     hci_connection_timestamp(conn);
137     conn->acl_recombination_length = 0;
138     conn->acl_recombination_pos = 0;
139     conn->num_acl_packets_sent = 0;
140     conn->num_sco_packets_sent = 0;
141     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
142     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
143     return conn;
144 }
145 
146 
147 /**
148  * get le connection parameter range
149 *
150  * @return le connection parameter range struct
151  */
152 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
153     *range = hci_stack->le_connection_parameter_range;
154 }
155 
156 /**
157  * set le connection parameter range
158  *
159  */
160 
161 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
162     hci_stack->le_connection_parameter_range = *range;
163 }
164 
165 /**
166  * get hci connections iterator
167  *
168  * @return hci connections iterator
169  */
170 
171 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
172     btstack_linked_list_iterator_init(it, &hci_stack->connections);
173 }
174 
175 /**
176  * get connection for a given handle
177  *
178  * @return connection OR NULL, if not found
179  */
180 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
181     btstack_linked_list_iterator_t it;
182     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
183     while (btstack_linked_list_iterator_has_next(&it)){
184         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
185         if ( item->con_handle == con_handle ) {
186             return item;
187         }
188     }
189     return NULL;
190 }
191 
192 /**
193  * get connection for given address
194  *
195  * @return connection OR NULL, if not found
196  */
197 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t  addr, bd_addr_type_t addr_type){
198     btstack_linked_list_iterator_t it;
199     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
200     while (btstack_linked_list_iterator_has_next(&it)){
201         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
202         if (connection->address_type != addr_type)  continue;
203         if (memcmp(addr, connection->address, 6) != 0) continue;
204         return connection;
205     }
206     return NULL;
207 }
208 
209 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
210     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
211 #ifdef HAVE_EMBEDDED_TICK
212     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
213         // connections might be timed out
214         hci_emit_l2cap_check_timeout(connection);
215     }
216 #else
217     if (btstack_run_loop_get_time_ms() > connection->timestamp + HCI_CONNECTION_TIMEOUT_MS){
218         // connections might be timed out
219         hci_emit_l2cap_check_timeout(connection);
220     }
221 #endif
222 }
223 
224 static void hci_connection_timestamp(hci_connection_t *connection){
225 #ifdef HAVE_EMBEDDED_TICK
226     connection->timestamp = btstack_run_loop_embedded_get_ticks();
227 #else
228     connection->timestamp = btstack_run_loop_get_time_ms();
229 #endif
230 }
231 
232 
233 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
234     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
235 }
236 
237 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
238     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
239 }
240 
241 
242 /**
243  * add authentication flags and reset timer
244  * @note: assumes classic connection
245  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
246  */
247 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
248     bd_addr_t addr;
249     reverse_bd_addr(bd_addr, addr);
250     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
251     if (conn) {
252         connectionSetAuthenticationFlags(conn, flags);
253         hci_connection_timestamp(conn);
254     }
255 }
256 
257 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
258     hci_connection_t * conn = hci_connection_for_handle(handle);
259     if (!conn) return 0;
260     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
261     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
262     return 0;
263 }
264 
265 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
266     if (!hci_stack->link_key_db) return;
267     hci_stack->link_key_db->delete_link_key(addr);
268 }
269 
270 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
271     if (!hci_stack->link_key_db) return;
272     hci_stack->link_key_db->put_link_key(addr, link_key, type);
273 }
274 
275 static int hci_is_le_connection(hci_connection_t * connection){
276     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
277     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
278 }
279 
280 /**
281  * count connections
282  */
283 static int nr_hci_connections(void){
284     int count = 0;
285     btstack_linked_item_t *it;
286     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
287     return count;
288 }
289 
290 static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
291 
292     int num_packets_sent_classic = 0;
293     int num_packets_sent_le = 0;
294 
295     btstack_linked_item_t *it;
296     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
297         hci_connection_t * connection = (hci_connection_t *) it;
298         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
299             num_packets_sent_classic += connection->num_acl_packets_sent;
300         } else {
301             num_packets_sent_le += connection->num_acl_packets_sent;
302         }
303     }
304     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
305     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
306     int free_slots_le = 0;
307 
308     if (free_slots_classic < 0){
309         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);
310         return 0;
311     }
312 
313     if (hci_stack->le_acl_packets_total_num){
314         // if we have LE slots, they are used
315         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
316         if (free_slots_le < 0){
317             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);
318             return 0;
319         }
320     } else {
321         // otherwise, classic slots are used for LE, too
322         free_slots_classic -= num_packets_sent_le;
323         if (free_slots_classic < 0){
324             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);
325             return 0;
326         }
327     }
328 
329     switch (address_type){
330         case BD_ADDR_TYPE_UNKNOWN:
331             log_error("hci_number_free_acl_slots: unknown address type");
332             return 0;
333 
334         case BD_ADDR_TYPE_CLASSIC:
335             return free_slots_classic;
336 
337         default:
338            if (hci_stack->le_acl_packets_total_num){
339                return free_slots_le;
340            }
341            return free_slots_classic;
342     }
343 }
344 
345 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
346     // get connection type
347     hci_connection_t * connection = hci_connection_for_handle(con_handle);
348     if (!connection){
349         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
350         return 0;
351     }
352     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
353 }
354 
355 static int hci_number_free_sco_slots(void){
356     int num_sco_packets_sent = 0;
357     btstack_linked_item_t *it;
358     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
359         hci_connection_t * connection = (hci_connection_t *) it;
360         num_sco_packets_sent += connection->num_sco_packets_sent;
361     }
362     if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
363         log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
364         return 0;
365     }
366     // log_info("hci_number_free_sco_slots u", handle, num_sco_packets_sent);
367     return hci_stack->sco_packets_total_num - num_sco_packets_sent;
368 }
369 
370 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
371 int hci_can_send_command_packet_now(void){
372     if (hci_stack->hci_packet_buffer_reserved) return 0;
373 
374     // check for async hci transport implementations
375     if (hci_stack->hci_transport->can_send_packet_now){
376         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
377             return 0;
378         }
379     }
380 
381     return hci_stack->num_cmd_packets > 0;
382 }
383 
384 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
385     // check for async hci transport implementations
386     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
387     return hci_stack->hci_transport->can_send_packet_now(packet_type);
388 }
389 
390 static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
391     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
392     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
393 }
394 
395 int hci_can_send_acl_classic_packet_now(void){
396     if (hci_stack->hci_packet_buffer_reserved) return 0;
397     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_CLASSIC);
398 }
399 
400 int hci_can_send_acl_le_packet_now(void){
401     if (hci_stack->hci_packet_buffer_reserved) return 0;
402     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
403 }
404 
405 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
406     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
407     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
408 }
409 
410 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
411     if (hci_stack->hci_packet_buffer_reserved) return 0;
412     return hci_can_send_prepared_acl_packet_now(con_handle);
413 }
414 
415 int hci_can_send_prepared_sco_packet_now(void){
416     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
417     if (!hci_stack->synchronous_flow_control_enabled) return 1;
418     return hci_number_free_sco_slots() > 0;
419 }
420 
421 int hci_can_send_sco_packet_now(void){
422     if (hci_stack->hci_packet_buffer_reserved) return 0;
423     return hci_can_send_prepared_sco_packet_now();
424 }
425 
426 void hci_request_sco_can_send_now_event(void){
427     hci_stack->sco_waiting_for_can_send_now = 1;
428     hci_notify_if_sco_can_send_now();
429 }
430 
431 // used for internal checks in l2cap.c
432 int hci_is_packet_buffer_reserved(void){
433     return hci_stack->hci_packet_buffer_reserved;
434 }
435 
436 // reserves outgoing packet buffer. @returns 1 if successful
437 int hci_reserve_packet_buffer(void){
438     if (hci_stack->hci_packet_buffer_reserved) {
439         log_error("hci_reserve_packet_buffer called but buffer already reserved");
440         return 0;
441     }
442     hci_stack->hci_packet_buffer_reserved = 1;
443     return 1;
444 }
445 
446 void hci_release_packet_buffer(void){
447     hci_stack->hci_packet_buffer_reserved = 0;
448 }
449 
450 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
451 static int hci_transport_synchronous(void){
452     return hci_stack->hci_transport->can_send_packet_now == NULL;
453 }
454 
455 static int hci_send_acl_packet_fragments(hci_connection_t *connection){
456 
457     // 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);
458 
459     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
460     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
461     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
462         max_acl_data_packet_length = hci_stack->le_data_packets_length;
463     }
464 
465     // testing: reduce buffer to minimum
466     // max_acl_data_packet_length = 52;
467 
468     log_debug("hci_send_acl_packet_fragments entered");
469 
470     int err;
471     // multiple packets could be send on a synchronous HCI transport
472     while (1){
473 
474         log_debug("hci_send_acl_packet_fragments loop entered");
475 
476         // get current data
477         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
478         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
479         int more_fragments = 0;
480 
481         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
482         if (current_acl_data_packet_length > max_acl_data_packet_length){
483             more_fragments = 1;
484             current_acl_data_packet_length = max_acl_data_packet_length;
485         }
486 
487         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
488         if (acl_header_pos > 0){
489             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
490             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
491             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
492         }
493 
494         // update header len
495         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
496 
497         // count packet
498         connection->num_acl_packets_sent++;
499         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %u)", more_fragments);
500 
501         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
502         if (more_fragments){
503             // update start of next fragment to send
504             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
505         } else {
506             // done
507             hci_stack->acl_fragmentation_pos = 0;
508             hci_stack->acl_fragmentation_total_size = 0;
509         }
510 
511         // send packet
512         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
513         const int size = current_acl_data_packet_length + 4;
514         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
515         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
516 
517         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %u)", more_fragments);
518 
519         // done yet?
520         if (!more_fragments) break;
521 
522         // can send more?
523         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
524     }
525 
526     log_debug("hci_send_acl_packet_fragments loop over");
527 
528     // release buffer now for synchronous transport
529     if (hci_transport_synchronous()){
530         hci_release_packet_buffer();
531         // notify upper stack that it might be possible to send again
532         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
533         hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
534     }
535 
536     return err;
537 }
538 
539 // pre: caller has reserved the packet buffer
540 int hci_send_acl_packet_buffer(int size){
541 
542     // log_info("hci_send_acl_packet_buffer size %u", size);
543 
544     if (!hci_stack->hci_packet_buffer_reserved) {
545         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
546         return 0;
547     }
548 
549     uint8_t * packet = hci_stack->hci_packet_buffer;
550     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
551 
552     // check for free places on Bluetooth module
553     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
554         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
555         hci_release_packet_buffer();
556         return BTSTACK_ACL_BUFFERS_FULL;
557     }
558 
559     hci_connection_t *connection = hci_connection_for_handle( con_handle);
560     if (!connection) {
561         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
562         hci_release_packet_buffer();
563         return 0;
564     }
565     hci_connection_timestamp(connection);
566 
567     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
568 
569     // setup data
570     hci_stack->acl_fragmentation_total_size = size;
571     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
572 
573     return hci_send_acl_packet_fragments(connection);
574 }
575 
576 // pre: caller has reserved the packet buffer
577 int hci_send_sco_packet_buffer(int size){
578 
579     // log_info("hci_send_acl_packet_buffer size %u", size);
580 
581     if (!hci_stack->hci_packet_buffer_reserved) {
582         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
583         return 0;
584     }
585 
586     uint8_t * packet = hci_stack->hci_packet_buffer;
587 
588     // skip checks in loopback mode
589     if (!hci_stack->loopback_mode){
590         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
591 
592         // check for free places on Bluetooth module
593         if (!hci_can_send_prepared_sco_packet_now()) {
594             log_error("hci_send_sco_packet_buffer called but no free ACL buffers on controller");
595             hci_release_packet_buffer();
596             return BTSTACK_ACL_BUFFERS_FULL;
597         }
598 
599         // track send packet in connection struct
600         hci_connection_t *connection = hci_connection_for_handle( con_handle);
601         if (!connection) {
602             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
603             hci_release_packet_buffer();
604             return 0;
605         }
606         connection->num_sco_packets_sent++;
607     }
608 
609     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
610     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
611 
612     if (hci_transport_synchronous()){
613         hci_release_packet_buffer();
614         // notify upper stack that it might be possible to send again
615         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
616         hci_emit_event(&event[0], sizeof(event), 0);    // don't dump
617     }
618 
619     return err;
620 }
621 
622 static void acl_handler(uint8_t *packet, int size){
623 
624     // log_info("acl_handler: size %u", size);
625 
626     // get info
627     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
628     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
629     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
630     uint16_t acl_length         = READ_ACL_LENGTH(packet);
631 
632     // ignore non-registered handle
633     if (!conn){
634         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
635         return;
636     }
637 
638     // assert packet is complete
639     if (acl_length + 4 != size){
640         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
641         return;
642     }
643 
644     // update idle timestamp
645     hci_connection_timestamp(conn);
646 
647     // handle different packet types
648     switch (acl_flags & 0x03) {
649 
650         case 0x01: // continuation fragment
651 
652             // sanity checks
653             if (conn->acl_recombination_pos == 0) {
654                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
655                 return;
656             }
657             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
658                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
659                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
660                 conn->acl_recombination_pos = 0;
661                 return;
662             }
663 
664             // append fragment payload (header already stored)
665             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
666             conn->acl_recombination_pos += acl_length;
667 
668             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
669             //        conn->acl_recombination_pos, conn->acl_recombination_length);
670 
671             // forward complete L2CAP packet if complete.
672             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
673                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
674                 // reset recombination buffer
675                 conn->acl_recombination_length = 0;
676                 conn->acl_recombination_pos = 0;
677             }
678             break;
679 
680         case 0x02: { // first fragment
681 
682             // sanity check
683             if (conn->acl_recombination_pos) {
684                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
685                 conn->acl_recombination_pos = 0;
686             }
687 
688             // peek into L2CAP packet!
689             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
690 
691             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
692 
693             // compare fragment size to L2CAP packet size
694             if (acl_length >= l2cap_length + 4){
695                 // forward fragment as L2CAP packet
696                 hci_emit_acl_packet(packet, acl_length + 4);
697             } else {
698 
699                 if (acl_length > HCI_ACL_BUFFER_SIZE){
700                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
701                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
702                     return;
703                 }
704 
705                 // store first fragment and tweak acl length for complete package
706                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
707                 conn->acl_recombination_pos    = acl_length + 4;
708                 conn->acl_recombination_length = l2cap_length;
709                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
710             }
711             break;
712 
713         }
714         default:
715             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
716             return;
717     }
718 
719     // execute main loop
720     hci_run();
721 }
722 
723 static void hci_shutdown_connection(hci_connection_t *conn){
724     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
725 
726     btstack_run_loop_remove_timer(&conn->timeout);
727 
728     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
729     btstack_memory_hci_connection_free( conn );
730 
731     // now it's gone
732     hci_emit_nr_connections_changed();
733 }
734 
735 static const uint16_t packet_type_sizes[] = {
736     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
737     HCI_ACL_DH1_SIZE, 0, 0, 0,
738     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
739     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
740 };
741 static const uint8_t  packet_type_feature_requirement_bit[] = {
742      0, // 3 slot packets
743      1, // 5 slot packets
744     25, // EDR 2 mpbs
745     26, // EDR 3 mbps
746     39, // 3 slot EDR packts
747     40, // 5 slot EDR packet
748 };
749 static const uint16_t packet_type_feature_packet_mask[] = {
750     0x0f00, // 3 slot packets
751     0xf000, // 5 slot packets
752     0x1102, // EDR 2 mpbs
753     0x2204, // EDR 3 mbps
754     0x0300, // 3 slot EDR packts
755     0x3000, // 5 slot EDR packet
756 };
757 
758 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
759     // enable packet types based on size
760     uint16_t packet_types = 0;
761     unsigned int i;
762     for (i=0;i<16;i++){
763         if (packet_type_sizes[i] == 0) continue;
764         if (packet_type_sizes[i] <= buffer_size){
765             packet_types |= 1 << i;
766         }
767     }
768     // disable packet types due to missing local supported features
769     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
770         int bit_idx = packet_type_feature_requirement_bit[i];
771         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
772         if (feature_set) continue;
773         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
774         packet_types &= ~packet_type_feature_packet_mask[i];
775     }
776     // flip bits for "may not be used"
777     packet_types ^= 0x3306;
778     return packet_types;
779 }
780 
781 uint16_t hci_usable_acl_packet_types(void){
782     return hci_stack->packet_types;
783 }
784 
785 uint8_t* hci_get_outgoing_packet_buffer(void){
786     // hci packet buffer is >= acl data packet length
787     return hci_stack->hci_packet_buffer;
788 }
789 
790 uint16_t hci_max_acl_data_packet_length(void){
791     return hci_stack->acl_data_packet_length;
792 }
793 
794 int hci_non_flushable_packet_boundary_flag_supported(void){
795     // No. 54, byte 6, bit 6
796     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
797 }
798 
799 static int gap_ssp_supported(void){
800     // No. 51, byte 6, bit 3
801     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
802 }
803 
804 static int hci_classic_supported(void){
805     // No. 37, byte 4, bit 5, = No BR/EDR Support
806     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
807 }
808 
809 static int hci_le_supported(void){
810 #ifdef ENABLE_BLE
811     // No. 37, byte 4, bit 6 = LE Supported (Controller)
812     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
813 #else
814     return 0;
815 #endif
816 }
817 
818 // get addr type and address used in advertisement packets
819 void gap_advertisements_get_address(uint8_t * addr_type, bd_addr_t  addr){
820     *addr_type = hci_stack->adv_addr_type;
821     if (hci_stack->adv_addr_type){
822         memcpy(addr, hci_stack->adv_address, 6);
823     } else {
824         memcpy(addr, hci_stack->local_bd_addr, 6);
825     }
826 }
827 
828 #ifdef ENABLE_BLE
829 void le_handle_advertisement_report(uint8_t *packet, int size){
830     int offset = 3;
831     int num_reports = packet[offset];
832     offset += 1;
833 
834     int i;
835     // log_info("HCI: handle adv report with num reports: %d", num_reports);
836     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
837     for (i=0; i<num_reports;i++){
838         uint8_t data_length = packet[offset + 8];
839         uint8_t event_size = 10 + data_length;
840         int pos = 0;
841         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
842         event[pos++] = event_size;
843         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
844         offset += 8;
845         pos += 8;
846         event[pos++] = packet[offset + 1 + data_length]; // rssi
847         event[pos++] = packet[offset++]; //data_length;
848         memcpy(&event[pos], &packet[offset], data_length);
849         pos += data_length;
850         offset += data_length + 1; // rssi
851         hci_emit_event(event, pos, 1);
852     }
853 }
854 #endif
855 
856 static uint32_t hci_transport_uart_get_main_baud_rate(void){
857     if (!hci_stack->config) return 0;
858     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
859     // Limit baud rate for Broadcom chipsets to 3 mbps
860     if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION && baud_rate > 3000000){
861         baud_rate = 3000000;
862     }
863     return baud_rate;
864 }
865 
866 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
867     switch (hci_stack->substate){
868         case HCI_INIT_W4_SEND_RESET:
869             log_info("Resend HCI Reset");
870             hci_stack->substate = HCI_INIT_SEND_RESET;
871             hci_stack->num_cmd_packets = 1;
872             hci_run();
873             break;
874         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
875             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
876             if (hci_stack->hci_transport->reset_link){
877                 hci_stack->hci_transport->reset_link();
878             }
879             // NOTE: explicit fallthrough to HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT
880         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
881             log_info("Resend HCI Reset - CSR Warm Boot");
882             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
883             hci_stack->num_cmd_packets = 1;
884             hci_run();
885             break;
886         case HCI_INIT_W4_SEND_BAUD_CHANGE: {
887 			uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
888             log_info("Local baud rate change to %"PRIu32"(timeout handler)", baud_rate);
889             hci_stack->hci_transport->set_baudrate(baud_rate);
890             // For CSR, HCI Reset is sent on new baud rate
891             if (hci_stack->manufacturer == COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
892                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
893                 hci_run();
894             }
895             break;
896         }
897         default:
898             break;
899     }
900 }
901 
902 static void hci_initializing_next_state(void){
903     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
904 }
905 
906 // assumption: hci_can_send_command_packet_now() == true
907 static void hci_initializing_run(void){
908     log_info("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
909     switch (hci_stack->substate){
910         case HCI_INIT_SEND_RESET:
911             hci_state_reset();
912 
913 #ifndef HAVE_PLATFORM_IPHONE_OS
914             // prepare reset if command complete not received in 100ms
915             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
916             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
917             btstack_run_loop_add_timer(&hci_stack->timeout);
918 #endif
919             // send command
920             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
921             hci_send_cmd(&hci_reset);
922             break;
923         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
924             hci_send_cmd(&hci_read_local_version_information);
925             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
926             break;
927         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
928             hci_state_reset();
929             // prepare reset if command complete not received in 100ms
930             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
931             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
932             btstack_run_loop_add_timer(&hci_stack->timeout);
933             // send command
934             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
935             hci_send_cmd(&hci_reset);
936             break;
937         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
938             hci_state_reset();
939             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
940             hci_send_cmd(&hci_reset);
941             break;
942         case HCI_INIT_SEND_BAUD_CHANGE: {
943             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
944             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
945             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
946             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
947             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
948             // STLC25000D: baudrate change happens within 0.5 s after command was send,
949             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
950             if (hci_stack->manufacturer == COMPANY_ID_ST_MICROELECTRONICS){
951                 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
952                 btstack_run_loop_add_timer(&hci_stack->timeout);
953             }
954             break;
955         }
956         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
957             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
958             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
959             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
960             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
961             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
962             break;
963         }
964         case HCI_INIT_CUSTOM_INIT:
965             log_info("Custom init");
966             // Custom initialization
967             if (hci_stack->chipset && hci_stack->chipset->next_command){
968                 int valid_cmd = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
969                 if (valid_cmd){
970                     int size = 3 + hci_stack->hci_packet_buffer[2];
971                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
972                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
973                     switch (valid_cmd) {
974                         case 1:
975                         default:
976                             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
977                             break;
978                         case 2: // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
979                             log_info("CSR Warm Boot");
980                             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
981                             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
982                             btstack_run_loop_add_timer(&hci_stack->timeout);
983                             if (hci_stack->manufacturer == COMPANY_ID_CAMBRIDGE_SILICON_RADIO
984                                 && hci_stack->config
985                                 && hci_stack->chipset
986                                 // && hci_stack->chipset->set_baudrate_command -- there's no such command
987                                 && hci_stack->hci_transport->set_baudrate
988                                 && hci_transport_uart_get_main_baud_rate()){
989                                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
990                             } else {
991                                hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
992                             }
993                             break;
994                     }
995                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
996                     break;
997                 }
998                 log_info("hci_run: init script done");
999 
1000                 // Init script download causes baud rate to reset on Broadcom chipsets, restore UART baud rate if needed
1001                 if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION){
1002                     int need_baud_change = hci_stack->config
1003                         && hci_stack->chipset
1004                         && hci_stack->chipset->set_baudrate_command
1005                         && hci_stack->hci_transport->set_baudrate
1006                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1007                     if (need_baud_change) {
1008                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1009                         log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate);
1010                         hci_stack->hci_transport->set_baudrate(baud_rate);
1011                     }
1012                 }
1013             }
1014             // otherwise continue
1015             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1016             hci_send_cmd(&hci_read_local_supported_commands);
1017             break;
1018         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
1019             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
1020             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1021             hci_send_cmd(&hci_read_local_supported_commands);
1022             break;
1023         case HCI_INIT_SET_BD_ADDR:
1024             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1025             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1026             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1027             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1028             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1029             break;
1030         case HCI_INIT_READ_BD_ADDR:
1031             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
1032             hci_send_cmd(&hci_read_bd_addr);
1033             break;
1034         case HCI_INIT_READ_BUFFER_SIZE:
1035             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
1036             hci_send_cmd(&hci_read_buffer_size);
1037             break;
1038         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
1039             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
1040             hci_send_cmd(&hci_read_local_supported_features);
1041             break;
1042         case HCI_INIT_SET_EVENT_MASK:
1043             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
1044             if (hci_le_supported()){
1045                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1046             } else {
1047                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1048                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1049             }
1050             break;
1051         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1052             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
1053             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1054             break;
1055         case HCI_INIT_WRITE_PAGE_TIMEOUT:
1056             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
1057             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
1058             break;
1059         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
1060             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
1061             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1062             break;
1063         case HCI_INIT_WRITE_LOCAL_NAME:
1064             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
1065             if (hci_stack->local_name){
1066                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
1067             } else {
1068                 char local_name[30];
1069                 // BTstack-11:22:33:44:55:66
1070                 strcpy(local_name, "BTstack ");
1071                 strcat(local_name, bd_addr_to_str(hci_stack->local_bd_addr));
1072                 log_info("---> Name %s", local_name);
1073                 hci_send_cmd(&hci_write_local_name, local_name);
1074             }
1075             break;
1076         case HCI_INIT_WRITE_SCAN_ENABLE:
1077             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1078             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
1079             break;
1080         // only sent if ENABLE_SCO_OVER_HCI is defined
1081         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1082             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1083             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1084             break;
1085         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1086             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1087             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1088             break;
1089 #ifdef ENABLE_BLE
1090         // LE INIT
1091         case HCI_INIT_LE_READ_BUFFER_SIZE:
1092             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
1093             hci_send_cmd(&hci_le_read_buffer_size);
1094             break;
1095         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
1096             // LE Supported Host = 1, Simultaneous Host = 0
1097             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
1098             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1099             break;
1100         case HCI_INIT_READ_WHITE_LIST_SIZE:
1101             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
1102             hci_send_cmd(&hci_le_read_white_list_size);
1103             break;
1104         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1105             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs
1106             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1107             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0);
1108             break;
1109 #endif
1110         default:
1111             return;
1112     }
1113 }
1114 
1115 static void hci_init_done(void){
1116     // done. tell the app
1117     log_info("hci_init_done -> HCI_STATE_WORKING");
1118     hci_stack->state = HCI_STATE_WORKING;
1119     hci_emit_state();
1120     hci_run();
1121 }
1122 
1123 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
1124     uint8_t command_completed = 0;
1125 
1126     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1127         uint16_t opcode = little_endian_read_16(packet,3);
1128         if (opcode == hci_stack->last_cmd_opcode){
1129             command_completed = 1;
1130             log_info("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
1131         } else {
1132             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
1133         }
1134     }
1135 
1136     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
1137         uint8_t  status = packet[2];
1138         uint16_t opcode = little_endian_read_16(packet,4);
1139         if (opcode == hci_stack->last_cmd_opcode){
1140             if (status){
1141                 command_completed = 1;
1142                 log_error("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
1143             } else {
1144                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
1145             }
1146         } else {
1147             log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1148         }
1149     }
1150 
1151     // Vendor == CSR
1152     if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1153         // TODO: track actual command
1154         command_completed = 1;
1155     }
1156 
1157     // Vendor == Toshiba
1158     if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1159         // TODO: track actual command
1160         command_completed = 1;
1161     }
1162 
1163     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1164     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1165     //
1166     // HCI Reset
1167     // Timeout 100 ms
1168     // HCI Reset
1169     // Command Complete Reset
1170     // HCI Read Local Version Information
1171     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1172     // hang...
1173     //
1174     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1175     if (!command_completed
1176             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1177             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
1178 
1179         uint16_t opcode = little_endian_read_16(packet,3);
1180         if (opcode == hci_reset.opcode){
1181             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1182             return;
1183         }
1184     }
1185 
1186     // CSR & H5
1187     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1188     if (!command_completed
1189             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1190             && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){
1191 
1192         uint16_t opcode = little_endian_read_16(packet,3);
1193         if (opcode == hci_reset.opcode){
1194             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1195             return;
1196         }
1197     }
1198 
1199     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
1200     // fix: Correct substate and behave as command below
1201     if (command_completed){
1202         switch (hci_stack->substate){
1203             case HCI_INIT_SEND_RESET:
1204                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1205                 break;
1206             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1207                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1208                 break;
1209             default:
1210                 break;
1211         }
1212     }
1213 
1214 
1215     if (!command_completed) return;
1216 
1217     int need_baud_change = hci_stack->config
1218                         && hci_stack->chipset
1219                         && hci_stack->chipset->set_baudrate_command
1220                         && hci_stack->hci_transport->set_baudrate
1221                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1222 
1223     int need_addr_change = hci_stack->custom_bd_addr_set
1224                         && hci_stack->chipset
1225                         && hci_stack->chipset->set_bd_addr_command;
1226 
1227     switch(hci_stack->substate){
1228         case HCI_INIT_SEND_RESET:
1229             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
1230             // fix: just correct substate and behave as command below
1231             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1232             btstack_run_loop_remove_timer(&hci_stack->timeout);
1233             break;
1234         case HCI_INIT_W4_SEND_RESET:
1235             btstack_run_loop_remove_timer(&hci_stack->timeout);
1236             break;
1237         case HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION:
1238             log_info("Received local version info, need baud change %u", need_baud_change);
1239             if (need_baud_change){
1240                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
1241                 return;
1242             }
1243             // skip baud change
1244             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1245             return;
1246         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1247             // for STLC2500D, baud rate change already happened.
1248             // for others, baud rate gets changed now
1249             if (hci_stack->manufacturer != COMPANY_ID_ST_MICROELECTRONICS){
1250                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1251                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1252                 hci_stack->hci_transport->set_baudrate(baud_rate);
1253             }
1254             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1255             return;
1256         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1257             btstack_run_loop_remove_timer(&hci_stack->timeout);
1258             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1259             return;
1260         case HCI_INIT_W4_CUSTOM_INIT:
1261             // repeat custom init
1262             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1263             return;
1264         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1265             if (need_baud_change && hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION){
1266                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1267                 return;
1268             }
1269             if (need_addr_change){
1270                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1271                 return;
1272             }
1273             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1274             return;
1275         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM: {
1276             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1277             log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1278             hci_stack->hci_transport->set_baudrate(baud_rate);
1279             if (need_addr_change){
1280                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1281                 return;
1282             }
1283             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1284             return;
1285         }
1286         case HCI_INIT_W4_SET_BD_ADDR:
1287             // for STLC2500D, bd addr change only gets active after sending reset command
1288             if (hci_stack->manufacturer == COMPANY_ID_ST_MICROELECTRONICS){
1289                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
1290                 return;
1291             }
1292             // skipping st warm boot
1293             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1294             return;
1295         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
1296             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1297             return;
1298         case HCI_INIT_W4_READ_BD_ADDR:
1299             // only read buffer size if supported
1300             if (hci_stack->local_supported_commands[0] & 0x01) {
1301                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
1302                 return;
1303             }
1304             // skipping read buffer size
1305             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1306             return;
1307         case HCI_INIT_W4_SET_EVENT_MASK:
1308             // skip Classic init commands for LE only chipsets
1309             if (!hci_classic_supported()){
1310                 if (hci_le_supported()){
1311                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
1312                     return;
1313                 } else {
1314                     log_error("Neither BR/EDR nor LE supported");
1315                     hci_init_done();
1316                     return;
1317                 }
1318             }
1319             if (!gap_ssp_supported()){
1320                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
1321                 return;
1322             }
1323             break;
1324         case HCI_INIT_W4_WRITE_PAGE_TIMEOUT:
1325             break;
1326         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1327             // skip write le host if not supported (e.g. on LE only EM9301)
1328             if (hci_stack->local_supported_commands[0] & 0x02) break;
1329             hci_stack->substate = HCI_INIT_LE_SET_SCAN_PARAMETERS;
1330             return;
1331 
1332 #ifdef ENABLE_SCO_OVER_HCI
1333         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1334         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1335             break;
1336         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1337             if (!hci_le_supported()){
1338                 // SKIP LE init for Classic only configuration
1339                 hci_init_done();
1340                 return;
1341             }
1342             break;
1343 #else
1344         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1345             if (!hci_le_supported()){
1346                 // SKIP LE init for Classic only configuration
1347                 hci_init_done();
1348                 return;
1349             }
1350 #endif
1351             break;
1352         // Response to command before init done state -> init done
1353         case (HCI_INIT_DONE-1):
1354             hci_init_done();
1355             return;
1356 
1357         default:
1358             break;
1359     }
1360     hci_initializing_next_state();
1361 }
1362 
1363 static void event_handler(uint8_t *packet, int size){
1364 
1365     uint16_t event_length = packet[1];
1366 
1367     // assert packet is complete
1368     if (size != event_length + 2){
1369         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
1370         return;
1371     }
1372 
1373     bd_addr_t addr;
1374     bd_addr_type_t addr_type;
1375     uint8_t link_type;
1376     hci_con_handle_t handle;
1377     hci_connection_t * conn;
1378     int i;
1379 
1380     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
1381 
1382     switch (hci_event_packet_get_type(packet)) {
1383 
1384         case HCI_EVENT_COMMAND_COMPLETE:
1385             // get num cmd packets
1386             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]);
1387             hci_stack->num_cmd_packets = packet[2];
1388 
1389             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1390                 // from offset 5
1391                 // status
1392                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1393                 hci_stack->acl_data_packet_length = little_endian_read_16(packet, 6);
1394                 hci_stack->sco_data_packet_length = packet[8];
1395                 hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1396                 hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1397 
1398                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1399                     // determine usable ACL payload size
1400                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
1401                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1402                     }
1403                     log_info("hci_read_buffer_size: acl used size %u, count %u / sco size %u, count %u",
1404                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1405                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1406                 }
1407             }
1408 #ifdef ENABLE_BLE
1409             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1410                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1411                 hci_stack->le_acl_packets_total_num  = packet[8];
1412                     // determine usable ACL payload size
1413                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1414                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1415                     }
1416                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1417             }
1418             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1419                 hci_stack->le_whitelist_capacity = little_endian_read_16(packet, 6);
1420                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1421             }
1422 #endif
1423             // Dump local address
1424             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1425                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1426 				hci_stack->local_bd_addr);
1427                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1428                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1429                 if (hci_stack->link_key_db){
1430                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1431                 }
1432             }
1433             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1434                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1435             }
1436             // Note: HCI init checks
1437             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1438                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1439 
1440                 // determine usable ACL packet types based on host buffer size and supported features
1441                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1442                 log_info("packet types %04x", hci_stack->packet_types);
1443 
1444                 // Classic/LE
1445                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1446             }
1447             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1448                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1449                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1450                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1451                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1452                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1453                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1454                 // notify app
1455                 if (hci_stack->local_version_information_callback){
1456                     hci_stack->local_version_information_callback(packet);
1457                 }
1458             }
1459             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1460                 hci_stack->local_supported_commands[0] =
1461                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0X80) >> 7 |  // Octet 14, bit 7
1462                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5;   // Octet 24, bit 6
1463             }
1464             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1465                 if (packet[5] == 0){
1466                     hci_stack->synchronous_flow_control_enabled = 1;
1467                 }
1468             }
1469             break;
1470 
1471         case HCI_EVENT_COMMAND_STATUS:
1472             // get num cmd packets
1473             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]);
1474             hci_stack->num_cmd_packets = packet[3];
1475             break;
1476 
1477         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1478             int offset = 3;
1479             for (i=0; i<packet[2];i++){
1480                 handle = little_endian_read_16(packet, offset);
1481                 offset += 2;
1482                 uint16_t num_packets = little_endian_read_16(packet, offset);
1483                 offset += 2;
1484 
1485                 conn = hci_connection_for_handle(handle);
1486                 if (!conn){
1487                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1488                     continue;
1489                 }
1490 
1491                 if (conn->address_type == BD_ADDR_TYPE_SCO){
1492                     if (conn->num_sco_packets_sent >= num_packets){
1493                         conn->num_sco_packets_sent -= num_packets;
1494                     } else {
1495                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1496                         conn->num_sco_packets_sent = 0;
1497                     }
1498                     hci_notify_if_sco_can_send_now();
1499                 } else {
1500                     if (conn->num_acl_packets_sent >= num_packets){
1501                         conn->num_acl_packets_sent -= num_packets;
1502                     } else {
1503                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
1504                         conn->num_acl_packets_sent = 0;
1505                     }
1506                 }
1507                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1508             }
1509             break;
1510         }
1511         case HCI_EVENT_CONNECTION_REQUEST:
1512             reverse_bd_addr(&packet[2], addr);
1513             // TODO: eval COD 8-10
1514             link_type = packet[11];
1515             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1516             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
1517             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1518             if (!conn) {
1519                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1520             }
1521             if (!conn) {
1522                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1523                 hci_stack->decline_reason = 0x0d;
1524                 bd_addr_copy(hci_stack->decline_addr, addr);
1525                 break;
1526             }
1527             conn->role  = HCI_ROLE_SLAVE;
1528             conn->state = RECEIVED_CONNECTION_REQUEST;
1529             // store info about eSCO
1530             if (link_type == 0x02){
1531                 conn->remote_supported_feature_eSCO = 1;
1532             }
1533             hci_run();
1534             break;
1535 
1536         case HCI_EVENT_CONNECTION_COMPLETE:
1537             // Connection management
1538             reverse_bd_addr(&packet[5], addr);
1539             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1540             addr_type = BD_ADDR_TYPE_CLASSIC;
1541             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1542             if (conn) {
1543                 if (!packet[2]){
1544                     conn->state = OPEN;
1545                     conn->con_handle = little_endian_read_16(packet, 3);
1546                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1547 
1548                     // restart timer
1549                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1550                     btstack_run_loop_add_timer(&conn->timeout);
1551 
1552                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1553 
1554                     hci_emit_nr_connections_changed();
1555                 } else {
1556                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1557                     uint8_t status = packet[2];
1558                     bd_addr_t bd_address;
1559                     memcpy(&bd_address, conn->address, 6);
1560 
1561                     // connection failed, remove entry
1562                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1563                     btstack_memory_hci_connection_free( conn );
1564 
1565                     // notify client if dedicated bonding
1566                     if (notify_dedicated_bonding_failed){
1567                         log_info("hci notify_dedicated_bonding_failed");
1568                         hci_emit_dedicated_bonding_result(bd_address, status);
1569                     }
1570 
1571                     // if authentication error, also delete link key
1572                     if (packet[2] == 0x05) {
1573                         gap_drop_link_key_for_bd_addr(addr);
1574                     }
1575                 }
1576             }
1577             break;
1578 
1579         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1580             reverse_bd_addr(&packet[5], addr);
1581             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1582             if (packet[2]){
1583                 // connection failed
1584                 break;
1585             }
1586             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1587             if (!conn) {
1588                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1589             }
1590             if (!conn) {
1591                 break;
1592             }
1593             conn->state = OPEN;
1594             conn->con_handle = little_endian_read_16(packet, 3);
1595             break;
1596 
1597         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1598             handle = little_endian_read_16(packet, 3);
1599             conn = hci_connection_for_handle(handle);
1600             if (!conn) break;
1601             if (!packet[2]){
1602                 uint8_t * features = &packet[5];
1603                 if (features[6] & (1 << 3)){
1604                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1605                 }
1606                 if (features[3] & (1<<7)){
1607                     conn->remote_supported_feature_eSCO = 1;
1608                 }
1609             }
1610             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1611             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
1612             if (conn->bonding_flags & BONDING_DEDICATED){
1613                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1614             }
1615             break;
1616 
1617         case HCI_EVENT_LINK_KEY_REQUEST:
1618             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1619             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1620             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1621             if (hci_stack->bondable && !hci_stack->link_key_db) break;
1622             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1623             hci_run();
1624             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1625             return;
1626 
1627         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1628             reverse_bd_addr(&packet[2], addr);
1629             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1630             if (!conn) break;
1631             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1632             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1633             // Change Connection Encryption keeps link key type
1634             if (link_key_type != CHANGED_COMBINATION_KEY){
1635                 conn->link_key_type = link_key_type;
1636             }
1637             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
1638             // still forward event to allow dismiss of pairing dialog
1639             break;
1640         }
1641 
1642         case HCI_EVENT_PIN_CODE_REQUEST:
1643             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1644             // non-bondable mode: pin code negative reply will be sent
1645             if (!hci_stack->bondable){
1646                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1647                 hci_run();
1648                 return;
1649             }
1650             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1651             if (!hci_stack->link_key_db) break;
1652             hci_event_pin_code_request_get_bd_addr(packet, addr);
1653             hci_stack->link_key_db->delete_link_key(addr);
1654             break;
1655 
1656         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1657             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1658             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1659             break;
1660 
1661         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
1662             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1663             if (!hci_stack->ssp_auto_accept) break;
1664             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1665             break;
1666 
1667         case HCI_EVENT_USER_PASSKEY_REQUEST:
1668             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1669             if (!hci_stack->ssp_auto_accept) break;
1670             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1671             break;
1672 
1673         case HCI_EVENT_ENCRYPTION_CHANGE:
1674             handle = little_endian_read_16(packet, 3);
1675             conn = hci_connection_for_handle(handle);
1676             if (!conn) break;
1677             if (packet[2] == 0) {
1678                 if (packet[5]){
1679                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1680                 } else {
1681                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1682                 }
1683             }
1684             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1685             break;
1686 
1687         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1688             handle = little_endian_read_16(packet, 3);
1689             conn = hci_connection_for_handle(handle);
1690             if (!conn) break;
1691 
1692             // dedicated bonding: send result and disconnect
1693             if (conn->bonding_flags & BONDING_DEDICATED){
1694                 conn->bonding_flags &= ~BONDING_DEDICATED;
1695                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1696                 conn->bonding_status = packet[2];
1697                 break;
1698             }
1699 
1700             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1701                 // link key sufficient for requested security
1702                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1703                 break;
1704             }
1705             // not enough
1706             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1707             break;
1708 
1709         // HCI_EVENT_DISCONNECTION_COMPLETE
1710         // has been split, to first notify stack before shutting connection down
1711         // see end of function, too.
1712         case HCI_EVENT_DISCONNECTION_COMPLETE:
1713             if (packet[2]) break;   // status != 0
1714             handle = little_endian_read_16(packet, 3);
1715             conn = hci_connection_for_handle(handle);
1716             if (!conn) break;       // no conn struct anymore
1717             // re-enable advertisements for le connections if active
1718             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
1719                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
1720             }
1721             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1722             break;
1723 
1724         case HCI_EVENT_HARDWARE_ERROR:
1725             if (hci_stack->hardware_error_callback){
1726                 (*hci_stack->hardware_error_callback)();
1727             } else {
1728                 // if no special requests, just reboot stack
1729                 hci_power_control_off();
1730                 hci_power_control_on();
1731             }
1732             break;
1733 
1734         case HCI_EVENT_ROLE_CHANGE:
1735             if (packet[2]) break;   // status != 0
1736             handle = little_endian_read_16(packet, 3);
1737             conn = hci_connection_for_handle(handle);
1738             if (!conn) break;       // no conn
1739             conn->role = packet[9];
1740             break;
1741 
1742         case HCI_EVENT_TRANSPORT_PACKET_SENT:
1743             // release packet buffer only for asynchronous transport and if there are not further fragements
1744             if (hci_transport_synchronous()) {
1745                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
1746                 return; // instead of break: to avoid re-entering hci_run()
1747             }
1748             if (hci_stack->acl_fragmentation_total_size) break;
1749             hci_release_packet_buffer();
1750 
1751             // L2CAP receives this event via the hci_emit_event below
1752 
1753             // For SCO, we do the can_send_now_check here
1754             hci_notify_if_sco_can_send_now();
1755             break;
1756 
1757         case HCI_EVENT_SCO_CAN_SEND_NOW:
1758             // For SCO, we do the can_send_now_check here
1759             hci_notify_if_sco_can_send_now();
1760             return;
1761 
1762 #ifdef ENABLE_BLE
1763         case HCI_EVENT_LE_META:
1764             switch (packet[2]){
1765                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1766                     // log_info("advertising report received");
1767                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1768                     le_handle_advertisement_report(packet, size);
1769                     break;
1770                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1771                     // Connection management
1772                     reverse_bd_addr(&packet[8], addr);
1773                     addr_type = (bd_addr_type_t)packet[7];
1774                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
1775                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1776                     // if auto-connect, remove from whitelist in both roles
1777                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
1778                         hci_remove_from_whitelist(addr_type, addr);
1779                     }
1780                     // handle error: error is reported only to the initiator -> outgoing connection
1781                     if (packet[3]){
1782                         // outgoing connection establishment is done
1783                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
1784                         // remove entry
1785                         if (conn){
1786                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1787                             btstack_memory_hci_connection_free( conn );
1788                         }
1789                         break;
1790                     }
1791                     // on success, both hosts receive connection complete event
1792                     if (packet[6] == HCI_ROLE_MASTER){
1793                         // if we're master, it was an outgoing connection and we're done with it
1794                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
1795                     } else {
1796                         // if we're slave, it was an incoming connection, advertisements have stopped
1797                         hci_stack->le_advertisements_active = 0;
1798                     }
1799                     // LE connections are auto-accepted, so just create a connection if there isn't one already
1800                     if (!conn){
1801                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1802                     }
1803                     // no memory, sorry.
1804                     if (!conn){
1805                         break;
1806                     }
1807 
1808                     conn->state = OPEN;
1809                     conn->role  = packet[6];
1810                     conn->con_handle = little_endian_read_16(packet, 4);
1811 
1812                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
1813 
1814                     // restart timer
1815                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1816                     // btstack_run_loop_add_timer(&conn->timeout);
1817 
1818                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1819 
1820                     hci_emit_nr_connections_changed();
1821                     break;
1822 
1823             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
1824 
1825                 default:
1826                     break;
1827             }
1828             break;
1829 #endif
1830         default:
1831             break;
1832     }
1833 
1834     // handle BT initialization
1835     if (hci_stack->state == HCI_STATE_INITIALIZING){
1836         hci_initializing_event_handler(packet, size);
1837     }
1838 
1839     // help with BT sleep
1840     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
1841         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
1842         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1843         hci_initializing_next_state();
1844     }
1845 
1846     // notify upper stack
1847 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
1848 
1849     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
1850     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
1851         if (!packet[2]){
1852             handle = little_endian_read_16(packet, 3);
1853             hci_connection_t * aConn = hci_connection_for_handle(handle);
1854             if (aConn) {
1855                 uint8_t status = aConn->bonding_status;
1856                 uint16_t flags = aConn->bonding_flags;
1857                 bd_addr_t bd_address;
1858                 memcpy(&bd_address, aConn->address, 6);
1859                 hci_shutdown_connection(aConn);
1860                 // connection struct is gone, don't access anymore
1861                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
1862                     hci_emit_dedicated_bonding_result(bd_address, status);
1863                 }
1864             }
1865         }
1866     }
1867 
1868 	// execute main loop
1869 	hci_run();
1870 }
1871 
1872 static void sco_handler(uint8_t * packet, uint16_t size){
1873     if (!hci_stack->sco_packet_handler) return;
1874     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
1875 }
1876 
1877 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1878     hci_dump_packet(packet_type, 1, packet, size);
1879     switch (packet_type) {
1880         case HCI_EVENT_PACKET:
1881             event_handler(packet, size);
1882             break;
1883         case HCI_ACL_DATA_PACKET:
1884             acl_handler(packet, size);
1885             break;
1886         case HCI_SCO_DATA_PACKET:
1887             sco_handler(packet, size);
1888         default:
1889             break;
1890     }
1891 }
1892 
1893 /**
1894  * @brief Add event packet handler.
1895  */
1896 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
1897     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
1898 }
1899 
1900 
1901 /** Register HCI packet handlers */
1902 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
1903     hci_stack->acl_packet_handler = handler;
1904 }
1905 
1906 /**
1907  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
1908  */
1909 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
1910     hci_stack->sco_packet_handler = handler;
1911 }
1912 
1913 static void hci_state_reset(void){
1914     // no connections yet
1915     hci_stack->connections = NULL;
1916 
1917     // keep discoverable/connectable as this has been requested by the client(s)
1918     // hci_stack->discoverable = 0;
1919     // hci_stack->connectable = 0;
1920     // hci_stack->bondable = 1;
1921 
1922     // buffer is free
1923     hci_stack->hci_packet_buffer_reserved = 0;
1924 
1925     // no pending cmds
1926     hci_stack->decline_reason = 0;
1927     hci_stack->new_scan_enable_value = 0xff;
1928 
1929     // LE
1930     hci_stack->adv_addr_type = 0;
1931     memset(hci_stack->adv_address, 0, 6);
1932     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1933     hci_stack->le_scan_type = 0xff;
1934     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
1935     hci_stack->le_whitelist = 0;
1936     hci_stack->le_whitelist_capacity = 0;
1937     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
1938     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
1939     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
1940     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
1941     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
1942     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
1943 }
1944 
1945 /**
1946  * @brief Configure Bluetooth hardware control. Has to be called before power on.
1947  */
1948 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
1949     // store and open remote device db
1950     hci_stack->link_key_db = link_key_db;
1951     if (hci_stack->link_key_db) {
1952         hci_stack->link_key_db->open();
1953     }
1954 }
1955 
1956 void hci_init(const hci_transport_t *transport, const void *config){
1957 
1958 #ifdef HAVE_MALLOC
1959     if (!hci_stack) {
1960         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
1961     }
1962 #else
1963     hci_stack = &hci_stack_static;
1964 #endif
1965     memset(hci_stack, 0, sizeof(hci_stack_t));
1966 
1967     // reference to use transport layer implementation
1968     hci_stack->hci_transport = transport;
1969 
1970     // reference to used config
1971     hci_stack->config = config;
1972 
1973     // max acl payload size defined in config.h
1974     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1975 
1976     // register packet handlers with transport
1977     transport->register_packet_handler(&packet_handler);
1978 
1979     hci_stack->state = HCI_STATE_OFF;
1980 
1981     // class of device
1982     hci_stack->class_of_device = 0x007a020c; // Smartphone
1983 
1984     // bondable by default
1985     hci_stack->bondable = 1;
1986 
1987     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
1988     hci_stack->ssp_enable = 1;
1989     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1990     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
1991     hci_stack->ssp_auto_accept = 1;
1992 
1993     // voice setting - signed 8 bit pcm data with CVSD over the air
1994     hci_stack->sco_voice_setting = 0x40;
1995 
1996     hci_state_reset();
1997 }
1998 
1999 /**
2000  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2001  */
2002 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2003     hci_stack->chipset = chipset_driver;
2004 
2005     // reset chipset driver - init is also called on power_up
2006     if (hci_stack->chipset && hci_stack->chipset->init){
2007         hci_stack->chipset->init(hci_stack->config);
2008     }
2009 }
2010 
2011 /**
2012  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2013  */
2014 void hci_set_control(const btstack_control_t *hardware_control){
2015     // references to used control implementation
2016     hci_stack->control = hardware_control;
2017     // init with transport config
2018     hardware_control->init(hci_stack->config);
2019 }
2020 
2021 void hci_close(void){
2022     // close remote device db
2023     if (hci_stack->link_key_db) {
2024         hci_stack->link_key_db->close();
2025     }
2026     while (hci_stack->connections) {
2027         // cancel all l2cap connections
2028         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
2029         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
2030     }
2031     hci_power_control(HCI_POWER_OFF);
2032 
2033 #ifdef HAVE_MALLOC
2034     free(hci_stack);
2035 #endif
2036     hci_stack = NULL;
2037 }
2038 
2039 void gap_set_class_of_device(uint32_t class_of_device){
2040     hci_stack->class_of_device = class_of_device;
2041 }
2042 
2043 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2044 void hci_set_bd_addr(bd_addr_t addr){
2045     memcpy(hci_stack->custom_bd_addr, addr, 6);
2046     hci_stack->custom_bd_addr_set = 1;
2047 }
2048 
2049 void hci_disable_l2cap_timeout_check(void){
2050     disable_l2cap_timeouts = 1;
2051 }
2052 // State-Module-Driver overview
2053 // state                    module  low-level
2054 // HCI_STATE_OFF             off      close
2055 // HCI_STATE_INITIALIZING,   on       open
2056 // HCI_STATE_WORKING,        on       open
2057 // HCI_STATE_HALTING,        on       open
2058 // HCI_STATE_SLEEPING,    off/sleep   close
2059 // HCI_STATE_FALLING_ASLEEP  on       open
2060 
2061 static int hci_power_control_on(void){
2062 
2063     // power on
2064     int err = 0;
2065     if (hci_stack->control && hci_stack->control->on){
2066         err = (*hci_stack->control->on)();
2067     }
2068     if (err){
2069         log_error( "POWER_ON failed");
2070         hci_emit_hci_open_failed();
2071         return err;
2072     }
2073 
2074     // int chipset driver
2075     if (hci_stack->chipset && hci_stack->chipset->init){
2076         hci_stack->chipset->init(hci_stack->config);
2077     }
2078 
2079     // init transport
2080     if (hci_stack->hci_transport->init){
2081         hci_stack->hci_transport->init(hci_stack->config);
2082     }
2083 
2084     // open transport
2085     err = hci_stack->hci_transport->open();
2086     if (err){
2087         log_error( "HCI_INIT failed, turning Bluetooth off again");
2088         if (hci_stack->control && hci_stack->control->off){
2089             (*hci_stack->control->off)();
2090         }
2091         hci_emit_hci_open_failed();
2092         return err;
2093     }
2094     return 0;
2095 }
2096 
2097 static void hci_power_control_off(void){
2098 
2099     log_info("hci_power_control_off");
2100 
2101     // close low-level device
2102     hci_stack->hci_transport->close();
2103 
2104     log_info("hci_power_control_off - hci_transport closed");
2105 
2106     // power off
2107     if (hci_stack->control && hci_stack->control->off){
2108         (*hci_stack->control->off)();
2109     }
2110 
2111     log_info("hci_power_control_off - control closed");
2112 
2113     hci_stack->state = HCI_STATE_OFF;
2114 }
2115 
2116 static void hci_power_control_sleep(void){
2117 
2118     log_info("hci_power_control_sleep");
2119 
2120 #if 0
2121     // don't close serial port during sleep
2122 
2123     // close low-level device
2124     hci_stack->hci_transport->close(hci_stack->config);
2125 #endif
2126 
2127     // sleep mode
2128     if (hci_stack->control && hci_stack->control->sleep){
2129         (*hci_stack->control->sleep)();
2130     }
2131 
2132     hci_stack->state = HCI_STATE_SLEEPING;
2133 }
2134 
2135 static int hci_power_control_wake(void){
2136 
2137     log_info("hci_power_control_wake");
2138 
2139     // wake on
2140     if (hci_stack->control && hci_stack->control->wake){
2141         (*hci_stack->control->wake)();
2142     }
2143 
2144 #if 0
2145     // open low-level device
2146     int err = hci_stack->hci_transport->open(hci_stack->config);
2147     if (err){
2148         log_error( "HCI_INIT failed, turning Bluetooth off again");
2149         if (hci_stack->control && hci_stack->control->off){
2150             (*hci_stack->control->off)();
2151         }
2152         hci_emit_hci_open_failed();
2153         return err;
2154     }
2155 #endif
2156 
2157     return 0;
2158 }
2159 
2160 static void hci_power_transition_to_initializing(void){
2161     // set up state machine
2162     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2163     hci_stack->hci_packet_buffer_reserved = 0;
2164     hci_stack->state = HCI_STATE_INITIALIZING;
2165     hci_stack->substate = HCI_INIT_SEND_RESET;
2166 }
2167 
2168 int hci_power_control(HCI_POWER_MODE power_mode){
2169 
2170     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
2171 
2172     int err = 0;
2173     switch (hci_stack->state){
2174 
2175         case HCI_STATE_OFF:
2176             switch (power_mode){
2177                 case HCI_POWER_ON:
2178                     err = hci_power_control_on();
2179                     if (err) {
2180                         log_error("hci_power_control_on() error %u", err);
2181                         return err;
2182                     }
2183                     hci_power_transition_to_initializing();
2184                     break;
2185                 case HCI_POWER_OFF:
2186                     // do nothing
2187                     break;
2188                 case HCI_POWER_SLEEP:
2189                     // do nothing (with SLEEP == OFF)
2190                     break;
2191             }
2192             break;
2193 
2194         case HCI_STATE_INITIALIZING:
2195             switch (power_mode){
2196                 case HCI_POWER_ON:
2197                     // do nothing
2198                     break;
2199                 case HCI_POWER_OFF:
2200                     // no connections yet, just turn it off
2201                     hci_power_control_off();
2202                     break;
2203                 case HCI_POWER_SLEEP:
2204                     // no connections yet, just turn it off
2205                     hci_power_control_sleep();
2206                     break;
2207             }
2208             break;
2209 
2210         case HCI_STATE_WORKING:
2211             switch (power_mode){
2212                 case HCI_POWER_ON:
2213                     // do nothing
2214                     break;
2215                 case HCI_POWER_OFF:
2216                     // see hci_run
2217                     hci_stack->state = HCI_STATE_HALTING;
2218                     break;
2219                 case HCI_POWER_SLEEP:
2220                     // see hci_run
2221                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2222                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2223                     break;
2224             }
2225             break;
2226 
2227         case HCI_STATE_HALTING:
2228             switch (power_mode){
2229                 case HCI_POWER_ON:
2230                     hci_power_transition_to_initializing();
2231                     break;
2232                 case HCI_POWER_OFF:
2233                     // do nothing
2234                     break;
2235                 case HCI_POWER_SLEEP:
2236                     // see hci_run
2237                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2238                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2239                     break;
2240             }
2241             break;
2242 
2243         case HCI_STATE_FALLING_ASLEEP:
2244             switch (power_mode){
2245                 case HCI_POWER_ON:
2246 
2247 #ifdef HAVE_PLATFORM_IPHONE_OS
2248                     // nothing to do, if H4 supports power management
2249                     if (btstack_control_iphone_power_management_enabled()){
2250                         hci_stack->state = HCI_STATE_INITIALIZING;
2251                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2252                         break;
2253                     }
2254 #endif
2255                     hci_power_transition_to_initializing();
2256                     break;
2257                 case HCI_POWER_OFF:
2258                     // see hci_run
2259                     hci_stack->state = HCI_STATE_HALTING;
2260                     break;
2261                 case HCI_POWER_SLEEP:
2262                     // do nothing
2263                     break;
2264             }
2265             break;
2266 
2267         case HCI_STATE_SLEEPING:
2268             switch (power_mode){
2269                 case HCI_POWER_ON:
2270 
2271 #ifdef HAVE_PLATFORM_IPHONE_OS
2272                     // nothing to do, if H4 supports power management
2273                     if (btstack_control_iphone_power_management_enabled()){
2274                         hci_stack->state = HCI_STATE_INITIALIZING;
2275                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2276                         hci_update_scan_enable();
2277                         break;
2278                     }
2279 #endif
2280                     err = hci_power_control_wake();
2281                     if (err) return err;
2282                     hci_power_transition_to_initializing();
2283                     break;
2284                 case HCI_POWER_OFF:
2285                     hci_stack->state = HCI_STATE_HALTING;
2286                     break;
2287                 case HCI_POWER_SLEEP:
2288                     // do nothing
2289                     break;
2290             }
2291             break;
2292     }
2293 
2294     // create internal event
2295 	hci_emit_state();
2296 
2297 	// trigger next/first action
2298 	hci_run();
2299 
2300     return 0;
2301 }
2302 
2303 static void hci_update_scan_enable(void){
2304     // 2 = page scan, 1 = inq scan
2305     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2306     hci_run();
2307 }
2308 
2309 void gap_discoverable_control(uint8_t enable){
2310     if (enable) enable = 1; // normalize argument
2311 
2312     if (hci_stack->discoverable == enable){
2313         hci_emit_discoverable_enabled(hci_stack->discoverable);
2314         return;
2315     }
2316 
2317     hci_stack->discoverable = enable;
2318     hci_update_scan_enable();
2319 }
2320 
2321 void gap_connectable_control(uint8_t enable){
2322     if (enable) enable = 1; // normalize argument
2323 
2324     // don't emit event
2325     if (hci_stack->connectable == enable) return;
2326 
2327     hci_stack->connectable = enable;
2328     hci_update_scan_enable();
2329 }
2330 
2331 void gap_local_bd_addr(bd_addr_t address_buffer){
2332     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
2333 }
2334 
2335 static void hci_run(void){
2336 
2337     // log_info("hci_run: entered");
2338     btstack_linked_item_t * it;
2339 
2340     // send continuation fragments first, as they block the prepared packet buffer
2341     if (hci_stack->acl_fragmentation_total_size > 0) {
2342         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2343         if (hci_can_send_prepared_acl_packet_now(con_handle)){
2344             hci_connection_t *connection = hci_connection_for_handle(con_handle);
2345             if (connection) {
2346                 hci_send_acl_packet_fragments(connection);
2347                 return;
2348             }
2349             // connection gone -> discard further fragments
2350             hci_stack->acl_fragmentation_total_size = 0;
2351             hci_stack->acl_fragmentation_pos = 0;
2352         }
2353     }
2354 
2355     if (!hci_can_send_command_packet_now()) return;
2356 
2357     // global/non-connection oriented commands
2358 
2359     // decline incoming connections
2360     if (hci_stack->decline_reason){
2361         uint8_t reason = hci_stack->decline_reason;
2362         hci_stack->decline_reason = 0;
2363         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2364         return;
2365     }
2366 
2367     // send scan enable
2368     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
2369         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
2370         hci_stack->new_scan_enable_value = 0xff;
2371         return;
2372     }
2373 
2374 #ifdef ENABLE_BLE
2375     if (hci_stack->state == HCI_STATE_WORKING){
2376         // handle le scan
2377         switch(hci_stack->le_scanning_state){
2378             case LE_START_SCAN:
2379                 hci_stack->le_scanning_state = LE_SCANNING;
2380                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
2381                 return;
2382 
2383             case LE_STOP_SCAN:
2384                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
2385                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
2386                 return;
2387             default:
2388                 break;
2389         }
2390         if (hci_stack->le_scan_type != 0xff){
2391             // defaults: active scanning, accept all advertisement packets
2392             int scan_type = hci_stack->le_scan_type;
2393             hci_stack->le_scan_type = 0xff;
2394             hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->adv_addr_type, 0);
2395             return;
2396         }
2397         // le advertisement control
2398         if (hci_stack->le_advertisements_todo){
2399             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
2400         }
2401         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
2402             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
2403             hci_send_cmd(&hci_le_set_advertise_enable, 0);
2404             return;
2405         }
2406         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
2407             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
2408             hci_send_cmd(&hci_le_set_advertising_parameters,
2409                  hci_stack->le_advertisements_interval_min,
2410                  hci_stack->le_advertisements_interval_max,
2411                  hci_stack->le_advertisements_type,
2412                  hci_stack->le_advertisements_own_address_type,
2413                  hci_stack->le_advertisements_direct_address_type,
2414                  hci_stack->le_advertisements_direct_address,
2415                  hci_stack->le_advertisements_channel_map,
2416                  hci_stack->le_advertisements_filter_policy);
2417             return;
2418         }
2419         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
2420             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
2421             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len,
2422                 hci_stack->le_advertisements_data);
2423             return;
2424         }
2425         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
2426             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
2427             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len,
2428                 hci_stack->le_scan_response_data);
2429             return;
2430         }
2431         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
2432             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
2433             hci_send_cmd(&hci_le_set_advertise_enable, 1);
2434             return;
2435         }
2436 
2437         //
2438         // LE Whitelist Management
2439         //
2440 
2441         // check if whitelist needs modification
2442         btstack_linked_list_iterator_t lit;
2443         int modification_pending = 0;
2444         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2445         while (btstack_linked_list_iterator_has_next(&lit)){
2446             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2447             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
2448                 modification_pending = 1;
2449                 break;
2450             }
2451         }
2452 
2453         if (modification_pending){
2454             // stop connnecting if modification pending
2455             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
2456                 hci_send_cmd(&hci_le_create_connection_cancel);
2457                 return;
2458             }
2459 
2460             // add/remove entries
2461             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2462             while (btstack_linked_list_iterator_has_next(&lit)){
2463                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2464                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
2465                     entry->state = LE_WHITELIST_ON_CONTROLLER;
2466                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
2467                     return;
2468 
2469                 }
2470                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
2471                     bd_addr_t address;
2472                     bd_addr_type_t address_type = entry->address_type;
2473                     memcpy(address, entry->address, 6);
2474                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
2475                     btstack_memory_whitelist_entry_free(entry);
2476                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
2477                     return;
2478                 }
2479             }
2480         }
2481 
2482         // start connecting
2483         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
2484             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
2485             bd_addr_t null_addr;
2486             memset(null_addr, 0, 6);
2487             hci_send_cmd(&hci_le_create_connection,
2488                  0x0060,    // scan interval: 60 ms
2489                  0x0030,    // scan interval: 30 ms
2490                  1,         // use whitelist
2491                  0,         // peer address type
2492                  null_addr,      // peer bd addr
2493                  hci_stack->adv_addr_type, // our addr type:
2494                  0x0008,    // conn interval min
2495                  0x0018,    // conn interval max
2496                  0,         // conn latency
2497                  0x0048,    // supervision timeout
2498                  0x0001,    // min ce length
2499                  0x0001     // max ce length
2500                  );
2501             return;
2502         }
2503     }
2504 #endif
2505 
2506     // send pending HCI commands
2507     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
2508         hci_connection_t * connection = (hci_connection_t *) it;
2509 
2510         switch(connection->state){
2511             case SEND_CREATE_CONNECTION:
2512                 switch(connection->address_type){
2513                     case BD_ADDR_TYPE_CLASSIC:
2514                         log_info("sending hci_create_connection");
2515                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
2516                         break;
2517                     default:
2518 #ifdef ENABLE_BLE
2519                         log_info("sending hci_le_create_connection");
2520                         hci_send_cmd(&hci_le_create_connection,
2521                                      0x0060,    // scan interval: 60 ms
2522                                      0x0030,    // scan interval: 30 ms
2523                                      0,         // don't use whitelist
2524                                      connection->address_type, // peer address type
2525                                      connection->address,      // peer bd addr
2526                                      hci_stack->adv_addr_type, // our addr type:
2527                                      0x0008,    // conn interval min
2528                                      0x0018,    // conn interval max
2529                                      0,         // conn latency
2530                                      0x0048,    // supervision timeout
2531                                      0x0001,    // min ce length
2532                                      0x0001     // max ce length
2533                                      );
2534 
2535                         connection->state = SENT_CREATE_CONNECTION;
2536 #endif
2537                         break;
2538                 }
2539                 return;
2540 
2541             case RECEIVED_CONNECTION_REQUEST:
2542                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
2543                 connection->state = ACCEPTED_CONNECTION_REQUEST;
2544                 connection->role  = HCI_ROLE_SLAVE;
2545                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
2546                     hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
2547                 } else {
2548                     // remote supported feature eSCO is set if link type is eSCO
2549                     uint16_t max_latency;
2550                     uint8_t  retransmission_effort;
2551                     uint16_t packet_types;
2552                     // remote supported feature eSCO is set if link type is eSCO
2553                     if (connection->remote_supported_feature_eSCO){
2554                         // eSCO: S4 - max latency == transmission interval = 0x000c == 12 ms,
2555                         max_latency = 0x000c;
2556                         retransmission_effort = 0x02;
2557                         packet_types = 0x388;
2558                     } else {
2559                         // SCO: max latency, retransmission interval: N/A. any packet type
2560                         max_latency = 0xffff;
2561                         retransmission_effort = 0xff;
2562                         packet_types = 0x003f;
2563                     }
2564                     hci_send_cmd(&hci_accept_synchronous_connection, connection->address, 8000, 8000, max_latency, hci_stack->sco_voice_setting, retransmission_effort, packet_types);
2565                 }
2566                 return;
2567 
2568 #ifdef ENABLE_BLE
2569             case SEND_CANCEL_CONNECTION:
2570                 connection->state = SENT_CANCEL_CONNECTION;
2571                 hci_send_cmd(&hci_le_create_connection_cancel);
2572                 return;
2573 #endif
2574             case SEND_DISCONNECT:
2575                 connection->state = SENT_DISCONNECT;
2576                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
2577                 return;
2578 
2579             default:
2580                 break;
2581         }
2582 
2583         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
2584             log_info("responding to link key request");
2585             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
2586             link_key_t link_key;
2587             link_key_type_t link_key_type;
2588             if ( hci_stack->link_key_db
2589               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
2590               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
2591                connection->link_key_type = link_key_type;
2592                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
2593             } else {
2594                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
2595             }
2596             return;
2597         }
2598 
2599         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
2600             log_info("denying to pin request");
2601             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
2602             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
2603             return;
2604         }
2605 
2606         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
2607             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
2608             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
2609             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
2610                 // tweak authentication requirements
2611                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
2612                 if (connection->bonding_flags & BONDING_DEDICATED){
2613                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
2614                 }
2615                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
2616                     authreq |= 1;
2617                 }
2618                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
2619             } else {
2620                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
2621             }
2622             return;
2623         }
2624 
2625         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
2626             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
2627             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
2628             return;
2629         }
2630 
2631         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
2632             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
2633             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
2634             return;
2635         }
2636 
2637         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
2638             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
2639             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
2640             return;
2641         }
2642 
2643         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
2644             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
2645             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
2646             return;
2647         }
2648         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
2649             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
2650             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
2651             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
2652             return;
2653         }
2654         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
2655             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
2656             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
2657             return;
2658         }
2659         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
2660             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
2661             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
2662             return;
2663         }
2664 
2665 #ifdef ENABLE_BLE
2666         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2667             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2668 
2669             uint16_t connection_interval_min = connection->le_conn_interval_min;
2670             connection->le_conn_interval_min = 0;
2671             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2672                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2673                 0x0000, 0xffff);
2674         }
2675 #endif
2676     }
2677 
2678     hci_connection_t * connection;
2679     switch (hci_stack->state){
2680         case HCI_STATE_INITIALIZING:
2681             hci_initializing_run();
2682             break;
2683 
2684         case HCI_STATE_HALTING:
2685 
2686             log_info("HCI_STATE_HALTING");
2687 
2688             // free whitelist entries
2689 #ifdef ENABLE_BLE
2690             {
2691                 btstack_linked_list_iterator_t lit;
2692                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2693                 while (btstack_linked_list_iterator_has_next(&lit)){
2694                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2695                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
2696                     btstack_memory_whitelist_entry_free(entry);
2697                 }
2698             }
2699 #endif
2700             // close all open connections
2701             connection =  (hci_connection_t *) hci_stack->connections;
2702             if (connection){
2703                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
2704                 if (!hci_can_send_command_packet_now()) return;
2705 
2706                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
2707 
2708                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
2709                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
2710 
2711                 // ... which would be ignored anyway as we shutdown (free) the connection now
2712                 hci_shutdown_connection(connection);
2713 
2714                 // finally, send the disconnect command
2715                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
2716                 return;
2717             }
2718             log_info("HCI_STATE_HALTING, calling off");
2719 
2720             // switch mode
2721             hci_power_control_off();
2722 
2723             log_info("HCI_STATE_HALTING, emitting state");
2724             hci_emit_state();
2725             log_info("HCI_STATE_HALTING, done");
2726             break;
2727 
2728         case HCI_STATE_FALLING_ASLEEP:
2729             switch(hci_stack->substate) {
2730                 case HCI_FALLING_ASLEEP_DISCONNECT:
2731                     log_info("HCI_STATE_FALLING_ASLEEP");
2732                     // close all open connections
2733                     connection =  (hci_connection_t *) hci_stack->connections;
2734 
2735 #ifdef HAVE_PLATFORM_IPHONE_OS
2736                     // don't close connections, if H4 supports power management
2737                     if (btstack_control_iphone_power_management_enabled()){
2738                         connection = NULL;
2739                     }
2740 #endif
2741                     if (connection){
2742 
2743                         // send disconnect
2744                         if (!hci_can_send_command_packet_now()) return;
2745 
2746                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2747                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2748 
2749                         // send disconnected event right away - causes higher layer connections to get closed, too.
2750                         hci_shutdown_connection(connection);
2751                         return;
2752                     }
2753 
2754                     if (hci_classic_supported()){
2755                         // disable page and inquiry scan
2756                         if (!hci_can_send_command_packet_now()) return;
2757 
2758                         log_info("HCI_STATE_HALTING, disabling inq scans");
2759                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
2760 
2761                         // continue in next sub state
2762                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
2763                         break;
2764                     }
2765                     // fall through for ble-only chips
2766 
2767                 case HCI_FALLING_ASLEEP_COMPLETE:
2768                     log_info("HCI_STATE_HALTING, calling sleep");
2769 #ifdef HAVE_PLATFORM_IPHONE_OS
2770                     // don't actually go to sleep, if H4 supports power management
2771                     if (btstack_control_iphone_power_management_enabled()){
2772                         // SLEEP MODE reached
2773                         hci_stack->state = HCI_STATE_SLEEPING;
2774                         hci_emit_state();
2775                         break;
2776                     }
2777 #endif
2778                     // switch mode
2779                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
2780                     hci_emit_state();
2781                     break;
2782 
2783                 default:
2784                     break;
2785             }
2786             break;
2787 
2788         default:
2789             break;
2790     }
2791 }
2792 
2793 int hci_send_cmd_packet(uint8_t *packet, int size){
2794     bd_addr_t addr;
2795     hci_connection_t * conn;
2796     // house-keeping
2797 
2798     // create_connection?
2799     if (IS_COMMAND(packet, hci_create_connection)){
2800         reverse_bd_addr(&packet[3], addr);
2801         log_info("Create_connection to %s", bd_addr_to_str(addr));
2802 
2803         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2804         if (!conn){
2805             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2806             if (!conn){
2807                 // notify client that alloc failed
2808                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2809                 return 0; // don't sent packet to controller
2810             }
2811             conn->state = SEND_CREATE_CONNECTION;
2812         }
2813         log_info("conn state %u", conn->state);
2814         switch (conn->state){
2815             // if connection active exists
2816             case OPEN:
2817                 // and OPEN, emit connection complete command, don't send to controller
2818                 hci_emit_connection_complete(conn, 0);
2819                 return 0;
2820             case SEND_CREATE_CONNECTION:
2821                 // connection created by hci, e.g. dedicated bonding
2822                 break;
2823             default:
2824                 // otherwise, just ignore as it is already in the open process
2825                 return 0;
2826         }
2827         conn->state = SENT_CREATE_CONNECTION;
2828     }
2829     if (IS_COMMAND(packet, hci_link_key_request_reply)){
2830         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
2831     }
2832     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
2833         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
2834     }
2835 
2836     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
2837         if (hci_stack->link_key_db){
2838             reverse_bd_addr(&packet[3], addr);
2839             hci_stack->link_key_db->delete_link_key(addr);
2840         }
2841     }
2842 
2843     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
2844     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
2845         reverse_bd_addr(&packet[3], addr);
2846         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2847         if (conn){
2848             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
2849         }
2850     }
2851 
2852     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
2853     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
2854     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
2855     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
2856         reverse_bd_addr(&packet[3], addr);
2857         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2858         if (conn){
2859             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
2860         }
2861     }
2862 
2863     if (IS_COMMAND(packet, hci_write_loopback_mode)){
2864         hci_stack->loopback_mode = packet[3];
2865     }
2866 
2867 #ifdef ENABLE_BLE
2868     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
2869         hci_stack->adv_addr_type = packet[8];
2870     }
2871     if (IS_COMMAND(packet, hci_le_set_random_address)){
2872         reverse_bd_addr(&packet[3], hci_stack->adv_address);
2873     }
2874     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
2875         hci_stack->le_advertisements_active = packet[3];
2876     }
2877     if (IS_COMMAND(packet, hci_le_create_connection)){
2878         // white list used?
2879         uint8_t initiator_filter_policy = packet[7];
2880         switch (initiator_filter_policy){
2881             case 0:
2882                 // whitelist not used
2883                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
2884                 break;
2885             case 1:
2886                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
2887                 break;
2888             default:
2889                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
2890                 break;
2891         }
2892     }
2893     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
2894         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2895     }
2896 #endif
2897 
2898     hci_stack->num_cmd_packets--;
2899 
2900     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2901     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2902 
2903     // release packet buffer for synchronous transport implementations
2904     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
2905         hci_stack->hci_packet_buffer_reserved = 0;
2906     }
2907 
2908     return err;
2909 }
2910 
2911 // disconnect because of security block
2912 void hci_disconnect_security_block(hci_con_handle_t con_handle){
2913     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2914     if (!connection) return;
2915     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2916 }
2917 
2918 
2919 // Configure Secure Simple Pairing
2920 
2921 // enable will enable SSP during init
2922 void gap_ssp_set_enable(int enable){
2923     hci_stack->ssp_enable = enable;
2924 }
2925 
2926 static int hci_local_ssp_activated(void){
2927     return gap_ssp_supported() && hci_stack->ssp_enable;
2928 }
2929 
2930 // if set, BTstack will respond to io capability request using authentication requirement
2931 void gap_ssp_set_io_capability(int io_capability){
2932     hci_stack->ssp_io_capability = io_capability;
2933 }
2934 void gap_ssp_set_authentication_requirement(int authentication_requirement){
2935     hci_stack->ssp_authentication_requirement = authentication_requirement;
2936 }
2937 
2938 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2939 void gap_ssp_set_auto_accept(int auto_accept){
2940     hci_stack->ssp_auto_accept = auto_accept;
2941 }
2942 
2943 /**
2944  * pre: numcmds >= 0 - it's allowed to send a command to the controller
2945  */
2946 int hci_send_cmd(const hci_cmd_t *cmd, ...){
2947 
2948     if (!hci_can_send_command_packet_now()){
2949         log_error("hci_send_cmd called but cannot send packet now");
2950         return 0;
2951     }
2952 
2953     // for HCI INITIALIZATION
2954     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
2955     hci_stack->last_cmd_opcode = cmd->opcode;
2956 
2957     hci_reserve_packet_buffer();
2958     uint8_t * packet = hci_stack->hci_packet_buffer;
2959 
2960     va_list argptr;
2961     va_start(argptr, cmd);
2962     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
2963     va_end(argptr);
2964 
2965     return hci_send_cmd_packet(packet, size);
2966 }
2967 
2968 // Create various non-HCI events.
2969 // TODO: generalize, use table similar to hci_create_command
2970 
2971 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
2972     // dump packet
2973     if (dump) {
2974         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
2975     }
2976 
2977     // dispatch to all event handlers
2978     btstack_linked_list_iterator_t it;
2979     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
2980     while (btstack_linked_list_iterator_has_next(&it)){
2981         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
2982         entry->callback(HCI_EVENT_PACKET, 0, event, size);
2983     }
2984 }
2985 
2986 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
2987     if (!hci_stack->acl_packet_handler) return;
2988     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
2989 }
2990 
2991 static void hci_notify_if_sco_can_send_now(void){
2992     // notify SCO sender if waiting
2993     if (!hci_stack->sco_waiting_for_can_send_now) return;
2994     if (hci_can_send_sco_packet_now()){
2995         hci_stack->sco_waiting_for_can_send_now = 0;
2996         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
2997         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
2998         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
2999     }
3000 }
3001 
3002 void hci_emit_state(void){
3003     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3004     uint8_t event[3];
3005     event[0] = BTSTACK_EVENT_STATE;
3006     event[1] = sizeof(event) - 2;
3007     event[2] = hci_stack->state;
3008     hci_emit_event(event, sizeof(event), 1);
3009 }
3010 
3011 static void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
3012     uint8_t event[13];
3013     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3014     event[1] = sizeof(event) - 2;
3015     event[2] = status;
3016     little_endian_store_16(event, 3, conn->con_handle);
3017     reverse_bd_addr(conn->address, &event[5]);
3018     event[11] = 1; // ACL connection
3019     event[12] = 0; // encryption disabled
3020     hci_emit_event(event, sizeof(event), 1);
3021 }
3022 
3023 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3024     uint8_t event[21];
3025     event[0] = HCI_EVENT_LE_META;
3026     event[1] = sizeof(event) - 2;
3027     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
3028     event[3] = status;
3029     little_endian_store_16(event, 4, con_handle);
3030     event[6] = 0; // TODO: role
3031     event[7] = address_type;
3032     reverse_bd_addr(address, &event[8]);
3033     little_endian_store_16(event, 14, 0); // interval
3034     little_endian_store_16(event, 16, 0); // latency
3035     little_endian_store_16(event, 18, 0); // supervision timeout
3036     event[20] = 0; // master clock accuracy
3037     hci_emit_event(event, sizeof(event), 1);
3038 }
3039 
3040 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
3041     uint8_t event[6];
3042     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
3043     event[1] = sizeof(event) - 2;
3044     event[2] = 0; // status = OK
3045     little_endian_store_16(event, 3, con_handle);
3046     event[5] = reason;
3047     hci_emit_event(event, sizeof(event), 1);
3048 }
3049 
3050 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3051     if (disable_l2cap_timeouts) return;
3052     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3053     uint8_t event[4];
3054     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3055     event[1] = sizeof(event) - 2;
3056     little_endian_store_16(event, 2, conn->con_handle);
3057     hci_emit_event(event, sizeof(event), 1);
3058 }
3059 
3060 static void hci_emit_nr_connections_changed(void){
3061     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
3062     uint8_t event[3];
3063     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3064     event[1] = sizeof(event) - 2;
3065     event[2] = nr_hci_connections();
3066     hci_emit_event(event, sizeof(event), 1);
3067 }
3068 
3069 static void hci_emit_hci_open_failed(void){
3070     log_info("BTSTACK_EVENT_POWERON_FAILED");
3071     uint8_t event[2];
3072     event[0] = BTSTACK_EVENT_POWERON_FAILED;
3073     event[1] = sizeof(event) - 2;
3074     hci_emit_event(event, sizeof(event), 1);
3075 }
3076 
3077 static void hci_emit_discoverable_enabled(uint8_t enabled){
3078     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
3079     uint8_t event[3];
3080     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
3081     event[1] = sizeof(event) - 2;
3082     event[2] = enabled;
3083     hci_emit_event(event, sizeof(event), 1);
3084 }
3085 
3086 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3087     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3088     uint8_t event[5];
3089     int pos = 0;
3090     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3091     event[pos++] = sizeof(event) - 2;
3092     little_endian_store_16(event, 2, con_handle);
3093     pos += 2;
3094     event[pos++] = level;
3095     hci_emit_event(event, sizeof(event), 1);
3096 }
3097 
3098 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
3099     log_info("hci_emit_dedicated_bonding_result %u ", status);
3100     uint8_t event[9];
3101     int pos = 0;
3102     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
3103     event[pos++] = sizeof(event) - 2;
3104     event[pos++] = status;
3105     reverse_bd_addr(address, &event[pos]);
3106     pos += 6;
3107     hci_emit_event(event, sizeof(event), 1);
3108 }
3109 
3110 // query if remote side supports eSCO
3111 int hci_remote_esco_supported(hci_con_handle_t con_handle){
3112     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3113     if (!connection) return 0;
3114     return connection->remote_supported_feature_eSCO;
3115 }
3116 
3117 // query if remote side supports SSP
3118 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
3119     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3120     if (!connection) return 0;
3121     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
3122 }
3123 
3124 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
3125     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3126 }
3127 
3128 // GAP API
3129 /**
3130  * @bbrief enable/disable bonding. default is enabled
3131  * @praram enabled
3132  */
3133 void gap_set_bondable_mode(int enable){
3134     hci_stack->bondable = enable ? 1 : 0;
3135 }
3136 /**
3137  * @brief Get bondable mode.
3138  * @return 1 if bondable
3139  */
3140 int gap_get_bondable_mode(void){
3141     return hci_stack->bondable;
3142 }
3143 
3144 /**
3145  * @brief map link keys to security levels
3146  */
3147 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
3148     switch (link_key_type){
3149         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
3150             return LEVEL_4;
3151         case COMBINATION_KEY:
3152         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
3153             return LEVEL_3;
3154         default:
3155             return LEVEL_2;
3156     }
3157 }
3158 
3159 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
3160     if (!connection) return LEVEL_0;
3161     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
3162     return gap_security_level_for_link_key_type(connection->link_key_type);
3163 }
3164 
3165 
3166 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
3167     log_info("gap_mitm_protection_required_for_security_level %u", level);
3168     return level > LEVEL_2;
3169 }
3170 
3171 /**
3172  * @brief get current security level
3173  */
3174 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
3175     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3176     if (!connection) return LEVEL_0;
3177     return gap_security_level_for_connection(connection);
3178 }
3179 
3180 /**
3181  * @brief request connection to device to
3182  * @result GAP_AUTHENTICATION_RESULT
3183  */
3184 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
3185     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3186     if (!connection){
3187         hci_emit_security_level(con_handle, LEVEL_0);
3188         return;
3189     }
3190     gap_security_level_t current_level = gap_security_level(con_handle);
3191     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
3192     if (current_level >= requested_level){
3193         hci_emit_security_level(con_handle, current_level);
3194         return;
3195     }
3196 
3197     connection->requested_security_level = requested_level;
3198 
3199 #if 0
3200     // sending encryption request without a link key results in an error.
3201     // TODO: figure out how to use it properly
3202 
3203     // would enabling ecnryption suffice (>= LEVEL_2)?
3204     if (hci_stack->link_key_db){
3205         link_key_type_t link_key_type;
3206         link_key_t      link_key;
3207         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3208             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3209                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3210                 return;
3211             }
3212         }
3213     }
3214 #endif
3215 
3216     // try to authenticate connection
3217     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3218     hci_run();
3219 }
3220 
3221 /**
3222  * @brief start dedicated bonding with device. disconnect after bonding
3223  * @param device
3224  * @param request MITM protection
3225  * @result GAP_DEDICATED_BONDING_COMPLETE
3226  */
3227 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3228 
3229     // create connection state machine
3230     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3231 
3232     if (!connection){
3233         return BTSTACK_MEMORY_ALLOC_FAILED;
3234     }
3235 
3236     // delete linkn key
3237     gap_drop_link_key_for_bd_addr(device);
3238 
3239     // configure LEVEL_2/3, dedicated bonding
3240     connection->state = SEND_CREATE_CONNECTION;
3241     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
3242     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
3243     connection->bonding_flags = BONDING_DEDICATED;
3244 
3245     // wait for GAP Security Result and send GAP Dedicated Bonding complete
3246 
3247     // handle: connnection failure (connection complete != ok)
3248     // handle: authentication failure
3249     // handle: disconnect on done
3250 
3251     hci_run();
3252 
3253     return 0;
3254 }
3255 
3256 void gap_set_local_name(const char * local_name){
3257     hci_stack->local_name = local_name;
3258 }
3259 
3260 void gap_start_scan(void){
3261     if (hci_stack->le_scanning_state == LE_SCANNING) return;
3262     hci_stack->le_scanning_state = LE_START_SCAN;
3263     hci_run();
3264 }
3265 
3266 void gap_stop_scan(void){
3267     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return;
3268     hci_stack->le_scanning_state = LE_STOP_SCAN;
3269     hci_run();
3270 }
3271 
3272 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
3273     hci_stack->le_scan_type     = scan_type;
3274     hci_stack->le_scan_interval = scan_interval;
3275     hci_stack->le_scan_window   = scan_window;
3276     hci_run();
3277 }
3278 
3279 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
3280     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3281     if (!conn){
3282         log_info("gap_connect: no connection exists yet, creating context");
3283         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3284         if (!conn){
3285             // notify client that alloc failed
3286             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3287             log_info("gap_connect: failed to alloc hci_connection_t");
3288             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
3289         }
3290         conn->state = SEND_CREATE_CONNECTION;
3291         log_info("gap_connect: send create connection next");
3292         hci_run();
3293         return 0;
3294     }
3295 
3296     if (!hci_is_le_connection(conn) ||
3297         conn->state == SEND_CREATE_CONNECTION ||
3298         conn->state == SENT_CREATE_CONNECTION) {
3299         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
3300         log_error("gap_connect: classic connection or connect is already being created");
3301         return GATT_CLIENT_IN_WRONG_STATE;
3302     }
3303 
3304     log_info("gap_connect: context exists with state %u", conn->state);
3305     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
3306     hci_run();
3307     return 0;
3308 }
3309 
3310 // @assumption: only a single outgoing LE Connection exists
3311 static hci_connection_t * gap_get_outgoing_connection(void){
3312     btstack_linked_item_t *it;
3313     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3314         hci_connection_t * conn = (hci_connection_t *) it;
3315         if (!hci_is_le_connection(conn)) continue;
3316         switch (conn->state){
3317             case SEND_CREATE_CONNECTION:
3318             case SENT_CREATE_CONNECTION:
3319                 return conn;
3320             default:
3321                 break;
3322         };
3323     }
3324     return NULL;
3325 }
3326 
3327 uint8_t gap_connect_cancel(void){
3328     hci_connection_t * conn = gap_get_outgoing_connection();
3329     if (!conn) return 0;
3330     switch (conn->state){
3331         case SEND_CREATE_CONNECTION:
3332             // skip sending create connection and emit event instead
3333             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
3334             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
3335             btstack_memory_hci_connection_free( conn );
3336             break;
3337         case SENT_CREATE_CONNECTION:
3338             // request to send cancel connection
3339             conn->state = SEND_CANCEL_CONNECTION;
3340             hci_run();
3341             break;
3342         default:
3343             break;
3344     }
3345     return 0;
3346 }
3347 
3348 /**
3349  * @brief Updates the connection parameters for a given LE connection
3350  * @param handle
3351  * @param conn_interval_min (unit: 1.25ms)
3352  * @param conn_interval_max (unit: 1.25ms)
3353  * @param conn_latency
3354  * @param supervision_timeout (unit: 10ms)
3355  * @returns 0 if ok
3356  */
3357 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3358     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3359     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3360     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3361     connection->le_conn_interval_min = conn_interval_min;
3362     connection->le_conn_interval_max = conn_interval_max;
3363     connection->le_conn_latency = conn_latency;
3364     connection->le_supervision_timeout = supervision_timeout;
3365     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
3366     hci_run();
3367     return 0;
3368 }
3369 
3370 /**
3371  * @brief Request an update of the connection parameter for a given LE connection
3372  * @param handle
3373  * @param conn_interval_min (unit: 1.25ms)
3374  * @param conn_interval_max (unit: 1.25ms)
3375  * @param conn_latency
3376  * @param supervision_timeout (unit: 10ms)
3377  * @returns 0 if ok
3378  */
3379 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3380     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3381     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3382     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3383     connection->le_conn_interval_min = conn_interval_min;
3384     connection->le_conn_interval_max = conn_interval_max;
3385     connection->le_conn_latency = conn_latency;
3386     connection->le_supervision_timeout = supervision_timeout;
3387     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
3388     hci_run();
3389     return 0;
3390 }
3391 
3392 static void gap_advertisments_changed(void){
3393     // disable advertisements before updating adv, scan data, or adv params
3394     if (hci_stack->le_advertisements_active){
3395         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
3396     }
3397     hci_run();
3398 }
3399 
3400 /**
3401  * @brief Set Advertisement Data
3402  * @param advertising_data_length
3403  * @param advertising_data (max 31 octets)
3404  * @note data is not copied, pointer has to stay valid
3405  */
3406 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
3407     hci_stack->le_advertisements_data_len = advertising_data_length;
3408     hci_stack->le_advertisements_data = advertising_data;
3409     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3410     gap_advertisments_changed();
3411 }
3412 
3413 /**
3414  * @brief Set Scan Response Data
3415  * @param advertising_data_length
3416  * @param advertising_data (max 31 octets)
3417  * @note data is not copied, pointer has to stay valid
3418  */
3419 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
3420     hci_stack->le_scan_response_data_len = scan_response_data_length;
3421     hci_stack->le_scan_response_data = scan_response_data;
3422     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3423     gap_advertisments_changed();
3424 }
3425 
3426 /**
3427  * @brief Set Advertisement Parameters
3428  * @param adv_int_min
3429  * @param adv_int_max
3430  * @param adv_type
3431  * @param own_address_type
3432  * @param direct_address_type
3433  * @param direct_address
3434  * @param channel_map
3435  * @param filter_policy
3436  *
3437  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
3438  */
3439  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
3440     uint8_t own_address_type, uint8_t direct_address_typ, bd_addr_t direct_address,
3441     uint8_t channel_map, uint8_t filter_policy) {
3442 
3443     hci_stack->le_advertisements_interval_min = adv_int_min;
3444     hci_stack->le_advertisements_interval_max = adv_int_max;
3445     hci_stack->le_advertisements_type = adv_type;
3446     hci_stack->le_advertisements_own_address_type = own_address_type;
3447     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
3448     hci_stack->le_advertisements_channel_map = channel_map;
3449     hci_stack->le_advertisements_filter_policy = filter_policy;
3450     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
3451 
3452     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3453     gap_advertisments_changed();
3454  }
3455 
3456 /**
3457  * @brief Enable/Disable Advertisements
3458  * @param enabled
3459  */
3460 void gap_advertisements_enable(int enabled){
3461     hci_stack->le_advertisements_enabled = enabled;
3462     if (enabled && !hci_stack->le_advertisements_active){
3463         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
3464     }
3465     if (!enabled && hci_stack->le_advertisements_active){
3466         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
3467     }
3468     hci_run();
3469 }
3470 
3471 
3472 uint8_t gap_disconnect(hci_con_handle_t handle){
3473     hci_connection_t * conn = hci_connection_for_handle(handle);
3474     if (!conn){
3475         hci_emit_disconnection_complete(handle, 0);
3476         return 0;
3477     }
3478     conn->state = SEND_DISCONNECT;
3479     hci_run();
3480     return 0;
3481 }
3482 
3483 /**
3484  * @brief Get connection type
3485  * @param con_handle
3486  * @result connection_type
3487  */
3488 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
3489     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
3490     if (!conn) return GAP_CONNECTION_INVALID;
3491     switch (conn->address_type){
3492         case BD_ADDR_TYPE_LE_PUBLIC:
3493         case BD_ADDR_TYPE_LE_RANDOM:
3494             return GAP_CONNECTION_LE;
3495         case BD_ADDR_TYPE_SCO:
3496             return GAP_CONNECTION_SCO;
3497         case BD_ADDR_TYPE_CLASSIC:
3498             return GAP_CONNECTION_ACL;
3499         default:
3500             return GAP_CONNECTION_INVALID;
3501     }
3502 }
3503 
3504 #ifdef ENABLE_BLE
3505 
3506 /**
3507  * @brief Auto Connection Establishment - Start Connecting to device
3508  * @param address_typ
3509  * @param address
3510  * @returns 0 if ok
3511  */
3512 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
3513     // check capacity
3514     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
3515     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3516     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
3517     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
3518     entry->address_type = address_type;
3519     memcpy(entry->address, address, 6);
3520     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
3521     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
3522     hci_run();
3523     return 0;
3524 }
3525 
3526 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
3527     btstack_linked_list_iterator_t it;
3528     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3529     while (btstack_linked_list_iterator_has_next(&it)){
3530         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3531         if (entry->address_type != address_type) continue;
3532         if (memcmp(entry->address, address, 6) != 0) continue;
3533         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3534             // remove from controller if already present
3535             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3536             continue;
3537         }
3538         // direclty remove entry from whitelist
3539         btstack_linked_list_iterator_remove(&it);
3540         btstack_memory_whitelist_entry_free(entry);
3541     }
3542 }
3543 
3544 /**
3545  * @brief Auto Connection Establishment - Stop Connecting to device
3546  * @param address_typ
3547  * @param address
3548  * @returns 0 if ok
3549  */
3550 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
3551     hci_remove_from_whitelist(address_type, address);
3552     hci_run();
3553     return 0;
3554 }
3555 
3556 /**
3557  * @brief Auto Connection Establishment - Stop everything
3558  * @note  Convenience function to stop all active auto connection attempts
3559  */
3560 void gap_auto_connection_stop_all(void){
3561     btstack_linked_list_iterator_t it;
3562     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3563     while (btstack_linked_list_iterator_has_next(&it)){
3564         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3565         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3566             // remove from controller if already present
3567             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3568             continue;
3569         }
3570         // directly remove entry from whitelist
3571         btstack_linked_list_iterator_remove(&it);
3572         btstack_memory_whitelist_entry_free(entry);
3573     }
3574     hci_run();
3575 }
3576 
3577 #endif
3578 
3579 /**
3580  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
3581  */
3582 void hci_set_sco_voice_setting(uint16_t voice_setting){
3583     hci_stack->sco_voice_setting = voice_setting;
3584 }
3585 
3586 /**
3587  * @brief Get SCO Voice Setting
3588  * @return current voice setting
3589  */
3590 uint16_t hci_get_sco_voice_setting(void){
3591     return hci_stack->sco_voice_setting;
3592 }
3593 
3594 /** @brief Get SCO packet length for current SCO Voice setting
3595  *  @note  Using SCO packets of the exact length is required for USB transfer
3596  *  @return Length of SCO packets in bytes (not audio frames)
3597  */
3598 int hci_get_sco_packet_length(void){
3599     // see Core Spec for H2 USB Transfer.
3600     if (hci_stack->sco_voice_setting & 0x0020) return 51;
3601     return 27;
3602 }
3603 
3604 /**
3605  * @brief Set callback for Bluetooth Hardware Error
3606  */
3607 void hci_set_hardware_error_callback(void (*fn)(void)){
3608     hci_stack->hardware_error_callback = fn;
3609 }
3610 
3611 /**
3612  * @brief Set callback for local information from Bluetooth controller right after HCI Reset
3613  * @note Can be used to select chipset driver dynamically during startup
3614  */
3615 void hci_set_local_version_information_callback(void (*fn)(uint8_t * local_version_information)){
3616     hci_stack->local_version_information_callback = fn;
3617 }
3618 
3619 void hci_disconnect_all(void){
3620     btstack_linked_list_iterator_t it;
3621     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
3622     while (btstack_linked_list_iterator_has_next(&it)){
3623         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
3624         if (con->state == SENT_DISCONNECT) continue;
3625         con->state = SEND_DISCONNECT;
3626     }
3627     hci_run();
3628 }
3629