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