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