xref: /btstack/src/hci.c (revision cb00d3aa12a5dbf3212bdb7e9fa9766a5b99fc3f)
1 /*
2  * Copyright (C) 2009-2012 by Matthias Ringwald
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 MATTHIAS RINGWALD 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 [email protected]
34  *
35  */
36 
37 /*
38  *  hci.c
39  *
40  *  Created by Matthias Ringwald on 4/29/09.
41  *
42  */
43 
44 #include "btstack-config.h"
45 
46 #include "hci.h"
47 #include "gap.h"
48 
49 #include <stdarg.h>
50 #include <string.h>
51 #include <stdio.h>
52 
53 #ifndef EMBEDDED
54 #include <unistd.h> // gethostbyname
55 #include <btstack/version.h>
56 #endif
57 
58 #include "btstack_memory.h"
59 #include "debug.h"
60 #include "hci_dump.h"
61 
62 #include <btstack/hci_cmds.h>
63 
64 #define HCI_CONNECTION_TIMEOUT_MS 10000
65 
66 #define HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP 11
67 
68 #ifdef USE_BLUETOOL
69 #include "bt_control_iphone.h"
70 #endif
71 
72 static void hci_update_scan_enable(void);
73 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
74 static void hci_connection_timeout_handler(timer_source_t *timer);
75 static void hci_connection_timestamp(hci_connection_t *connection);
76 static int  hci_power_control_on(void);
77 static void hci_power_control_off(void);
78 static void hci_state_reset();
79 
80 // the STACK is here
81 #ifndef HAVE_MALLOC
82 static hci_stack_t   hci_stack_static;
83 #endif
84 static hci_stack_t * hci_stack = NULL;
85 
86 // test helper
87 static uint8_t disable_l2cap_timeouts = 0;
88 
89 /**
90  * create connection for given address
91  *
92  * @return connection OR NULL, if no memory left
93  */
94 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
95 
96     log_info("create_connection_for_addr %s", bd_addr_to_str(addr));
97     hci_connection_t * conn = (hci_connection_t *) btstack_memory_hci_connection_get();
98     if (!conn) return NULL;
99     BD_ADDR_COPY(conn->address, addr);
100     conn->address_type = addr_type;
101     conn->con_handle = 0xffff;
102     conn->authentication_flags = AUTH_FLAGS_NONE;
103     conn->bonding_flags = 0;
104     conn->requested_security_level = LEVEL_0;
105     linked_item_set_user(&conn->timeout.item, conn);
106     conn->timeout.process = hci_connection_timeout_handler;
107     hci_connection_timestamp(conn);
108     conn->acl_recombination_length = 0;
109     conn->acl_recombination_pos = 0;
110     conn->num_acl_packets_sent = 0;
111     linked_list_add(&hci_stack->connections, (linked_item_t *) conn);
112     return conn;
113 }
114 
115 /**
116  * get connection for a given handle
117  *
118  * @return connection OR NULL, if not found
119  */
120 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
121     linked_item_t *it;
122     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
123         if ( ((hci_connection_t *) it)->con_handle == con_handle){
124             return (hci_connection_t *) it;
125         }
126     }
127     return NULL;
128 }
129 
130 /**
131  * get connection for given address
132  *
133  * @return connection OR NULL, if not found
134  */
135 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t * addr, bd_addr_type_t addr_type){
136     linked_item_t *it;
137     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
138         hci_connection_t * connection = (hci_connection_t *) it;
139         if (connection->address_type != addr_type)  continue;
140         if (memcmp(addr, connection->address, 6) != 0) continue;
141         return connection;
142     }
143     return NULL;
144 }
145 
146 static void hci_connection_timeout_handler(timer_source_t *timer){
147     hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item);
148 #ifdef HAVE_TIME
149     struct timeval tv;
150     gettimeofday(&tv, NULL);
151     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
152         // connections might be timed out
153         hci_emit_l2cap_check_timeout(connection);
154     }
155 #endif
156 #ifdef HAVE_TICK
157     if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
158         // connections might be timed out
159         hci_emit_l2cap_check_timeout(connection);
160     }
161 #endif
162     run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
163     run_loop_add_timer(timer);
164 }
165 
166 static void hci_connection_timestamp(hci_connection_t *connection){
167 #ifdef HAVE_TIME
168     gettimeofday(&connection->timestamp, NULL);
169 #endif
170 #ifdef HAVE_TICK
171     connection->timestamp = embedded_get_ticks();
172 #endif
173 }
174 
175 
176 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
177     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
178 }
179 
180 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
181     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
182 }
183 
184 
185 /**
186  * add authentication flags and reset timer
187  * @note: assumes classic connection
188  */
189 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
190     bd_addr_t addr;
191     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
192     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
193     if (conn) {
194         connectionSetAuthenticationFlags(conn, flags);
195         hci_connection_timestamp(conn);
196     }
197 }
198 
199 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
200     hci_connection_t * conn = hci_connection_for_handle(handle);
201     if (!conn) return 0;
202     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
203     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
204     return 0;
205 }
206 
207 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
208     if (hci_stack->remote_device_db) {
209         hci_stack->remote_device_db->delete_link_key(addr);
210     }
211 }
212 
213 int hci_is_le_connection(hci_connection_t * connection){
214     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
215     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
216 }
217 
218 
219 /**
220  * count connections
221  */
222 static int nr_hci_connections(void){
223     int count = 0;
224     linked_item_t *it;
225     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
226     return count;
227 }
228 
229 /**
230  * Dummy handler called by HCI
231  */
232 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
233 }
234 
235 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
236     hci_connection_t * connection = hci_connection_for_handle(handle);
237     if (!connection) {
238         log_error("hci_number_outgoing_packets: connection for handle %u does not exist!", handle);
239         return 0;
240     }
241     return connection->num_acl_packets_sent;
242 }
243 
244 uint8_t hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
245 
246     int num_packets_sent_classic = 0;
247     int num_packets_sent_le = 0;
248 
249     bd_addr_type_t address_type = BD_ADDR_TYPE_UNKNOWN;
250 
251     linked_item_t *it;
252     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
253         hci_connection_t * connection = (hci_connection_t *) it;
254         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
255             num_packets_sent_classic += connection->num_acl_packets_sent;
256         } else {
257             num_packets_sent_le += connection->num_acl_packets_sent;
258         }
259         if (connection->con_handle == con_handle){
260             address_type = connection->address_type;
261         }
262     }
263 
264     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
265     int free_slots_le = 0;
266 
267     if (free_slots_classic < 0){
268         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);
269         return 0;
270     }
271 
272     if (hci_stack->le_acl_packets_total_num){
273         // if we have LE slots, they are used
274         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
275         if (free_slots_le < 0){
276             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);
277             return 0;
278         }
279     } else {
280         // otherwise, classic slots are used for LE, too
281         free_slots_classic -= num_packets_sent_le;
282         if (free_slots_classic < 0){
283             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);
284             return 0;
285         }
286     }
287 
288     switch (address_type){
289         case BD_ADDR_TYPE_UNKNOWN:
290             log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
291             return 0;
292 
293         case BD_ADDR_TYPE_CLASSIC:
294             return free_slots_classic;
295 
296         default:
297            if (hci_stack->le_acl_packets_total_num){
298                return free_slots_le;
299            }
300            return free_slots_classic;
301     }
302 }
303 
304 
305 // @deprecated
306 int hci_can_send_packet_now(uint8_t packet_type){
307     switch (packet_type) {
308         case HCI_ACL_DATA_PACKET:
309             return hci_can_send_prepared_acl_packet_now(0);
310         case HCI_COMMAND_DATA_PACKET:
311             return hci_can_send_command_packet_now();
312         default:
313             return 0;
314     }
315 }
316 
317 // @deprecated
318 // same as hci_can_send_packet_now, but also checks if packet buffer is free for use
319 int hci_can_send_packet_now_using_packet_buffer(uint8_t packet_type){
320 
321     if (hci_stack->hci_packet_buffer_reserved) return 0;
322 
323     switch (packet_type) {
324         case HCI_ACL_DATA_PACKET:
325             return hci_can_send_acl_packet_now(0);
326         case HCI_COMMAND_DATA_PACKET:
327             return hci_can_send_command_packet_now();
328         default:
329             return 0;
330     }
331 }
332 
333 
334 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
335 int hci_can_send_command_packet_now(void){
336     if (hci_stack->hci_packet_buffer_reserved) return 0;
337 
338     // check for async hci transport implementations
339     if (hci_stack->hci_transport->can_send_packet_now){
340         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
341             return 0;
342         }
343     }
344 
345     return hci_stack->num_cmd_packets > 0;
346 }
347 
348 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
349     // check for async hci transport implementations
350     if (hci_stack->hci_transport->can_send_packet_now){
351         if (!hci_stack->hci_transport->can_send_packet_now(HCI_ACL_DATA_PACKET)){
352             return 0;
353         }
354     }
355     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
356 }
357 
358 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
359     if (hci_stack->hci_packet_buffer_reserved) return 0;
360     return hci_can_send_prepared_acl_packet_now(con_handle);
361 }
362 
363 // used for internal checks in l2cap[-le].c
364 int hci_is_packet_buffer_reserved(void){
365     return hci_stack->hci_packet_buffer_reserved;
366 }
367 
368 // reserves outgoing packet buffer. @returns 1 if successful
369 int hci_reserve_packet_buffer(void){
370     if (hci_stack->hci_packet_buffer_reserved) {
371         log_error("hci_reserve_packet_buffer called but buffer already reserved");
372         return 0;
373     }
374     hci_stack->hci_packet_buffer_reserved = 1;
375     return 1;
376 }
377 
378 void hci_release_packet_buffer(void){
379     hci_stack->hci_packet_buffer_reserved = 0;
380 }
381 
382 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
383 int hci_transport_synchronous(void){
384     return hci_stack->hci_transport->can_send_packet_now == NULL;
385 }
386 
387 // pre: caller has reserved the packet buffer
388 int hci_send_acl_packet_buffer(int size){
389 
390     if (!hci_stack->hci_packet_buffer_reserved) {
391         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
392         return 0;
393     }
394 
395     uint8_t * packet = hci_stack->hci_packet_buffer;
396     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
397 
398     // check for free places on Bluetooth module
399     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
400         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
401         hci_release_packet_buffer();
402         return BTSTACK_ACL_BUFFERS_FULL;
403     }
404 
405     hci_connection_t *connection = hci_connection_for_handle( con_handle);
406     if (!connection) {
407         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
408         hci_release_packet_buffer();
409         return 0;
410     }
411     hci_connection_timestamp(connection);
412 
413     // count packet
414     connection->num_acl_packets_sent++;
415     // log_info("hci_send_acl_packet - handle %u, sent %u", connection->con_handle, connection->num_acl_packets_sent);
416 
417     // send packet
418     int err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
419 
420     // free packet buffer for synchronous transport implementations
421     if (hci_transport_synchronous()){
422         hci_release_packet_buffer();
423     }
424 
425     return err;
426 }
427 
428 static void acl_handler(uint8_t *packet, int size){
429 
430     // log_info("acl_handler: size %u", size);
431 
432     // get info
433     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
434     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
435     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
436     uint16_t acl_length         = READ_ACL_LENGTH(packet);
437 
438     // ignore non-registered handle
439     if (!conn){
440         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
441         return;
442     }
443 
444     // assert packet is complete
445     if (acl_length + 4 != size){
446         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
447         return;
448     }
449 
450     // update idle timestamp
451     hci_connection_timestamp(conn);
452 
453     // handle different packet types
454     switch (acl_flags & 0x03) {
455 
456         case 0x01: // continuation fragment
457 
458             // sanity check
459             if (conn->acl_recombination_pos == 0) {
460                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
461                 return;
462             }
463 
464             // append fragment payload (header already stored)
465             memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length );
466             conn->acl_recombination_pos += acl_length;
467 
468             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
469             //        conn->acl_recombination_pos, conn->acl_recombination_length);
470 
471             // forward complete L2CAP packet if complete.
472             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
473 
474                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos);
475                 // reset recombination buffer
476                 conn->acl_recombination_length = 0;
477                 conn->acl_recombination_pos = 0;
478             }
479             break;
480 
481         case 0x02: { // first fragment
482 
483             // sanity check
484             if (conn->acl_recombination_pos) {
485                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x", con_handle);
486                 return;
487             }
488 
489             // peek into L2CAP packet!
490             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
491 
492             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
493 
494             // compare fragment size to L2CAP packet size
495             if (acl_length >= l2cap_length + 4){
496 
497                 // forward fragment as L2CAP packet
498                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
499 
500             } else {
501                 // store first fragment and tweak acl length for complete package
502                 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4);
503                 conn->acl_recombination_pos    = acl_length + 4;
504                 conn->acl_recombination_length = l2cap_length;
505                 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4);
506             }
507             break;
508 
509         }
510         default:
511             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
512             return;
513     }
514 
515     // execute main loop
516     hci_run();
517 }
518 
519 static void hci_shutdown_connection(hci_connection_t *conn){
520     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
521 
522     run_loop_remove_timer(&conn->timeout);
523 
524     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
525     btstack_memory_hci_connection_free( conn );
526 
527     // now it's gone
528     hci_emit_nr_connections_changed();
529 }
530 
531 static const uint16_t packet_type_sizes[] = {
532     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
533     HCI_ACL_DH1_SIZE, 0, 0, 0,
534     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
535     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
536 };
537 static const uint8_t  packet_type_feature_requirement_bit[] = {
538      0, // 3 slot packets
539      1, // 5 slot packets
540     25, // EDR 2 mpbs
541     26, // EDR 3 mbps
542     39, // 3 slot EDR packts
543     40, // 5 slot EDR packet
544 };
545 static const uint16_t packet_type_feature_packet_mask[] = {
546     0x0f00, // 3 slot packets
547     0xf000, // 5 slot packets
548     0x1102, // EDR 2 mpbs
549     0x2204, // EDR 3 mbps
550     0x0300, // 3 slot EDR packts
551     0x3000, // 5 slot EDR packet
552 };
553 
554 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
555     // enable packet types based on size
556     uint16_t packet_types = 0;
557     int i;
558     for (i=0;i<16;i++){
559         if (packet_type_sizes[i] == 0) continue;
560         if (packet_type_sizes[i] <= buffer_size){
561             packet_types |= 1 << i;
562         }
563     }
564     // disable packet types due to missing local supported features
565     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
566         int bit_idx = packet_type_feature_requirement_bit[i];
567         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
568         if (feature_set) continue;
569         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
570         packet_types &= ~packet_type_feature_packet_mask[i];
571     }
572     // flip bits for "may not be used"
573     packet_types ^= 0x3306;
574     return packet_types;
575 }
576 
577 uint16_t hci_usable_acl_packet_types(void){
578     return hci_stack->packet_types;
579 }
580 
581 uint8_t* hci_get_outgoing_packet_buffer(void){
582     // hci packet buffer is >= acl data packet length
583     return hci_stack->hci_packet_buffer;
584 }
585 
586 uint16_t hci_max_acl_data_packet_length(void){
587     return hci_stack->acl_data_packet_length;
588 }
589 
590 int hci_non_flushable_packet_boundary_flag_supported(void){
591     // No. 54, byte 6, bit 6
592     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
593 }
594 
595 int hci_ssp_supported(void){
596     // No. 51, byte 6, bit 3
597     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
598 }
599 
600 int hci_classic_supported(void){
601     // No. 37, byte 4, bit 5, = No BR/EDR Support
602     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
603 }
604 
605 int hci_le_supported(void){
606 #ifdef HAVE_BLE
607     // No. 37, byte 4, bit 6 = LE Supported (Controller)
608     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
609 #else
610     return 0;
611 #endif
612 }
613 
614 // get addr type and address used in advertisement packets
615 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){
616     *addr_type = hci_stack->adv_addr_type;
617     if (hci_stack->adv_addr_type){
618         memcpy(addr, hci_stack->adv_address, 6);
619     } else {
620         memcpy(addr, hci_stack->local_bd_addr, 6);
621     }
622 }
623 
624 #ifdef HAVE_BLE
625 void le_handle_advertisement_report(uint8_t *packet, int size){
626     int offset = 3;
627     int num_reports = packet[offset];
628     offset += 1;
629 
630     int i;
631     int total_data_length = 0;
632 
633     for (i=0; i<num_reports;i++){
634         total_data_length += packet[4+num_reports*8+i];
635     }
636 
637     log_info("num reports: %d, ", num_reports);
638     for (i=0; i<num_reports;i++){
639         uint8_t data_length = packet[offset + 9];
640         uint8_t event_size = 10 + data_length;
641         uint8_t event[2 + event_size ];
642         int pos = 0;
643         event[pos++] = GAP_LE_ADVERTISING_REPORT;
644         event[pos++] = event_size;
645         memcpy(&event[pos], &packet[offset], 1+1+6); // bt address
646         offset += 8;
647         pos += 8;
648         event[pos++] = packet[offset + 1 + data_length]; // rssi
649         event[pos++] = packet[offset++]; //data_length;
650         memcpy(&event[pos], &packet[offset], data_length);
651         pos += data_length;
652         offset += data_length + 1; // rssi
653         hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
654     }
655 }
656 #endif
657 
658 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
659     uint8_t command_completed = 0;
660     if ((hci_stack->substate % 2) == 0) return;
661     // odd: waiting for event
662     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
663         uint16_t opcode = READ_BT_16(packet,3);
664         if (opcode == hci_stack->last_cmd_opcode){
665             command_completed = 1;
666             log_info("Command complete for expected opcode %04x -> new substate %u", opcode, hci_stack->substate);
667         } else {
668             log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
669         }
670     }
671     if (packet[0] == HCI_EVENT_COMMAND_STATUS){
672         uint8_t  status = packet[2];
673         uint16_t opcode = READ_BT_16(packet,4);
674         if (opcode == hci_stack->last_cmd_opcode){
675             if (status){
676                 command_completed = 1;
677                 log_error("Command status error 0x%02x for expected opcode %04x -> new substate %u", status, opcode, hci_stack->substate);
678             } else {
679                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
680             }
681         } else {
682             log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
683         }
684     }
685 
686     if (!command_completed) return;
687 
688     switch(hci_stack->substate >> 1){
689         default:
690             hci_stack->substate++;
691             break;
692     }
693 }
694 
695 static void hci_initializing_state_machine(){
696         // log_info("hci_init: substate %u", hci_stack->substate);
697     if (hci_stack->substate % 2) {
698         // odd: waiting for command completion
699         return;
700     }
701     switch (hci_stack->substate >> 1){
702         case 0: // RESET
703             hci_state_reset();
704 
705             hci_send_cmd(&hci_reset);
706             if (hci_stack->config == NULL || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
707                 // skip baud change
708                 hci_stack->substate = 4; // >> 1 = 2
709             }
710             break;
711         case 1: // SEND BAUD CHANGE
712             hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
713             hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
714             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
715             break;
716         case 2: // LOCAL BAUD CHANGE
717             log_info("Local baud rate change");
718             hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
719             hci_stack->substate += 2;
720             // break missing here for fall through
721 
722         case 3:
723             log_info("Custom init");
724             // Custom initialization
725             if (hci_stack->control && hci_stack->control->next_cmd){
726                 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
727                 if (valid_cmd){
728                     int size = 3 + hci_stack->hci_packet_buffer[2];
729                     hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
730                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
731                     hci_stack->substate = 4; // more init commands
732                     break;
733                 }
734                 log_info("hci_run: init script done");
735             }
736             // otherwise continue
737             hci_send_cmd(&hci_read_bd_addr);
738             break;
739         case 4:
740             hci_send_cmd(&hci_read_buffer_size);
741             break;
742         case 5:
743             hci_send_cmd(&hci_read_local_supported_features);
744             break;
745         case 6:
746             if (hci_le_supported()){
747                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
748             } else {
749                 // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
750                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
751             }
752 
753             // skip Classic init commands for LE only chipsets
754             if (!hci_classic_supported()){
755                 if (hci_le_supported()){
756                     hci_stack->substate = 11 << 1;    // skip all classic command
757                 } else {
758                     log_error("Neither BR/EDR nor LE supported");
759                     hci_stack->substate = 14 << 1;    // skip all
760                 }
761             }
762             break;
763         case 7:
764             if (hci_ssp_supported()){
765                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
766                 break;
767             }
768             hci_stack->substate += 2;
769             // break missing here for fall through
770 
771         case 8:
772             // ca. 15 sec
773             hci_send_cmd(&hci_write_page_timeout, 0x6000);
774             break;
775         case 9:
776             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
777             break;
778         case 10:
779             if (hci_stack->local_name){
780                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
781             } else {
782                 char hostname[30];
783 #ifdef EMBEDDED
784                 // BTstack-11:22:33:44:55:66
785                 strcpy(hostname, "BTstack ");
786                 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr));
787                 log_info("---> Name %s", hostname);
788 #else
789                 // hostname for POSIX systems
790                 gethostname(hostname, 30);
791                 hostname[29] = '\0';
792 #endif
793                 hci_send_cmd(&hci_write_local_name, hostname);
794             }
795             break;
796         case 11:
797             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
798             if (!hci_le_supported()){
799                 // SKIP LE init for Classic only configuration
800                 hci_stack->substate = 14 << 1;
801             }
802             break;
803 
804 #ifdef HAVE_BLE
805         // LE INIT
806         case 12:
807             hci_send_cmd(&hci_le_read_buffer_size);
808             break;
809         case 13:
810             // LE Supported Host = 1, Simultaneous Host = 0
811             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
812             break;
813         case 14:
814             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs
815             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0);
816             break;
817 #endif
818 
819         // DONE
820         case 15:
821             // done.
822             hci_stack->state = HCI_STATE_WORKING;
823             hci_emit_state();
824             break;
825         default:
826             break;
827     }
828     hci_stack->substate++;
829 }
830 
831 // avoid huge local variables
832 #ifndef EMBEDDED
833 static device_name_t device_name;
834 #endif
835 static void event_handler(uint8_t *packet, int size){
836 
837     uint16_t event_length = packet[1];
838 
839     // assert packet is complete
840     if (size != event_length + 2){
841         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
842         return;
843     }
844 
845     bd_addr_t addr;
846     bd_addr_type_t addr_type;
847     uint8_t link_type;
848     hci_con_handle_t handle;
849     hci_connection_t * conn;
850     int i;
851 
852     // log_info("HCI:EVENT:%02x", packet[0]);
853 
854     switch (packet[0]) {
855 
856         case HCI_EVENT_COMMAND_COMPLETE:
857             // get num cmd packets
858             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]);
859             hci_stack->num_cmd_packets = packet[2];
860 
861             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
862                 // from offset 5
863                 // status
864                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
865                 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6);
866                 // ignore: SCO data packet len (8)
867                 hci_stack->acl_packets_total_num  = packet[9];
868                 // ignore: total num SCO packets
869                 if (hci_stack->state == HCI_STATE_INITIALIZING){
870                     // determine usable ACL payload size
871                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
872                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
873                     }
874                     log_info("hci_read_buffer_size: used size %u, count %u",
875                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num);
876                 }
877             }
878 #ifdef HAVE_BLE
879             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){
880                 hci_stack->le_data_packets_length = READ_BT_16(packet, 6);
881                 hci_stack->le_acl_packets_total_num  = packet[8];
882                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
883             }
884 #endif
885             // Dump local address
886             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
887                 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
888                 log_info("Local Address, Status: 0x%02x: Addr: %s",
889                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
890             }
891             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
892                 hci_emit_discoverable_enabled(hci_stack->discoverable);
893             }
894             // Note: HCI init checks
895             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
896                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
897                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
898                     hci_stack->local_supported_features[0], hci_stack->local_supported_features[1],
899                     hci_stack->local_supported_features[2], hci_stack->local_supported_features[3],
900                     hci_stack->local_supported_features[4], hci_stack->local_supported_features[5],
901                     hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]);
902 
903                 // determine usable ACL packet types based buffer size and supported features
904                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(hci_stack->acl_data_packet_length, &hci_stack->local_supported_features[0]);
905                 log_info("packet types %04x", hci_stack->packet_types);
906 
907                 // Classic/LE
908                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
909             }
910             break;
911 
912         case HCI_EVENT_COMMAND_STATUS:
913             // get num cmd packets
914             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]);
915             hci_stack->num_cmd_packets = packet[3];
916             break;
917 
918         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
919             int offset = 3;
920             for (i=0; i<packet[2];i++){
921                 handle = READ_BT_16(packet, offset);
922                 offset += 2;
923                 uint16_t num_packets = READ_BT_16(packet, offset);
924                 offset += 2;
925 
926                 conn = hci_connection_for_handle(handle);
927                 if (!conn){
928                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
929                     continue;
930                 }
931                 conn->num_acl_packets_sent -= num_packets;
932                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
933             }
934             break;
935         }
936         case HCI_EVENT_CONNECTION_REQUEST:
937             bt_flip_addr(addr, &packet[2]);
938             // TODO: eval COD 8-10
939             link_type = packet[11];
940             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
941             if (link_type == 1) { // ACL
942                 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
943                 if (!conn) {
944                     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
945                 }
946                 if (!conn) {
947                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
948                     hci_stack->decline_reason = 0x0d;
949                     BD_ADDR_COPY(hci_stack->decline_addr, addr);
950                     break;
951                 }
952                 conn->state = RECEIVED_CONNECTION_REQUEST;
953                 hci_run();
954             } else {
955                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
956                 hci_stack->decline_reason = 0x0a;
957                 BD_ADDR_COPY(hci_stack->decline_addr, addr);
958             }
959             break;
960 
961         case HCI_EVENT_CONNECTION_COMPLETE:
962             // Connection management
963             bt_flip_addr(addr, &packet[5]);
964             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
965             addr_type = BD_ADDR_TYPE_CLASSIC;
966             conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
967             if (conn) {
968                 if (!packet[2]){
969                     conn->state = OPEN;
970                     conn->con_handle = READ_BT_16(packet, 3);
971                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
972 
973                     // restart timer
974                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
975                     run_loop_add_timer(&conn->timeout);
976 
977                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
978 
979                     hci_emit_nr_connections_changed();
980                 } else {
981                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
982                     uint8_t status = packet[2];
983                     bd_addr_t bd_address;
984                     memcpy(&bd_address, conn->address, 6);
985 
986                     // connection failed, remove entry
987                     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
988                     btstack_memory_hci_connection_free( conn );
989 
990                     // notify client if dedicated bonding
991                     if (notify_dedicated_bonding_failed){
992                         log_info("hci notify_dedicated_bonding_failed");
993                         hci_emit_dedicated_bonding_result(bd_address, status);
994                     }
995 
996                     // if authentication error, also delete link key
997                     if (packet[2] == 0x05) {
998                         hci_drop_link_key_for_bd_addr(&addr);
999                     }
1000                 }
1001             }
1002             break;
1003 
1004         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1005             handle = READ_BT_16(packet, 3);
1006             conn = hci_connection_for_handle(handle);
1007             if (!conn) break;
1008             if (!packet[2]){
1009                 uint8_t * features = &packet[5];
1010                 if (features[6] & (1 << 3)){
1011                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1012                 }
1013             }
1014             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1015             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags);
1016             if (conn->bonding_flags & BONDING_DEDICATED){
1017                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1018             }
1019             break;
1020 
1021         case HCI_EVENT_LINK_KEY_REQUEST:
1022             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1023             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1024             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1025             if (hci_stack->bondable && !hci_stack->remote_device_db) break;
1026             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1027             hci_run();
1028             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1029             return;
1030 
1031         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1032             bt_flip_addr(addr, &packet[2]);
1033             conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1034             if (!conn) break;
1035             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1036             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1037             // Change Connection Encryption keeps link key type
1038             if (link_key_type != CHANGED_COMBINATION_KEY){
1039                 conn->link_key_type = link_key_type;
1040             }
1041             if (!hci_stack->remote_device_db) break;
1042             hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type);
1043             // still forward event to allow dismiss of pairing dialog
1044             break;
1045         }
1046 
1047         case HCI_EVENT_PIN_CODE_REQUEST:
1048             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1049             // non-bondable mode: pin code negative reply will be sent
1050             if (!hci_stack->bondable){
1051                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1052                 hci_run();
1053                 return;
1054             }
1055             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1056             if (!hci_stack->remote_device_db) break;
1057             bt_flip_addr(addr, &packet[2]);
1058             hci_stack->remote_device_db->delete_link_key(&addr);
1059             break;
1060 
1061         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1062             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1063             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1064             break;
1065 
1066         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
1067             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1068             if (!hci_stack->ssp_auto_accept) break;
1069             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1070             break;
1071 
1072         case HCI_EVENT_USER_PASSKEY_REQUEST:
1073             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1074             if (!hci_stack->ssp_auto_accept) break;
1075             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1076             break;
1077 
1078         case HCI_EVENT_ENCRYPTION_CHANGE:
1079             handle = READ_BT_16(packet, 3);
1080             conn = hci_connection_for_handle(handle);
1081             if (!conn) break;
1082             if (packet[2] == 0) {
1083                 if (packet[5]){
1084                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1085                 } else {
1086                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1087                 }
1088             }
1089             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1090             break;
1091 
1092         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1093             handle = READ_BT_16(packet, 3);
1094             conn = hci_connection_for_handle(handle);
1095             if (!conn) break;
1096 
1097             // dedicated bonding: send result and disconnect
1098             if (conn->bonding_flags & BONDING_DEDICATED){
1099                 conn->bonding_flags &= ~BONDING_DEDICATED;
1100                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1101                 conn->bonding_status = packet[2];
1102                 break;
1103             }
1104 
1105             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1106                 // link key sufficient for requested security
1107                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1108                 break;
1109             }
1110             // not enough
1111             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1112             break;
1113 
1114 #ifndef EMBEDDED
1115         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1116             if (!hci_stack->remote_device_db) break;
1117             if (packet[2]) break; // status not ok
1118             bt_flip_addr(addr, &packet[3]);
1119             // fix for invalid remote names - terminate on 0xff
1120             for (i=0; i<248;i++){
1121                 if (packet[9+i] == 0xff){
1122                     packet[9+i] = 0;
1123                     break;
1124                 }
1125             }
1126             memset(&device_name, 0, sizeof(device_name_t));
1127             strncpy((char*) device_name, (char*) &packet[9], 248);
1128             hci_stack->remote_device_db->put_name(&addr, &device_name);
1129             break;
1130 
1131         case HCI_EVENT_INQUIRY_RESULT:
1132         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{
1133             if (!hci_stack->remote_device_db) break;
1134             // first send inq result packet
1135             hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1136             // then send cached remote names
1137             int offset = 3;
1138             for (i=0; i<packet[2];i++){
1139                 bt_flip_addr(addr, &packet[offset]);
1140                 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2;
1141                 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){
1142                     hci_emit_remote_name_cached(&addr, &device_name);
1143                 }
1144             }
1145             return;
1146         }
1147 #endif
1148 
1149         case HCI_EVENT_DISCONNECTION_COMPLETE:
1150             if (!packet[2]){
1151                 handle = READ_BT_16(packet, 3);
1152                 hci_connection_t * conn = hci_connection_for_handle(handle);
1153                 if (conn) {
1154                     uint8_t status = conn->bonding_status;
1155                     bd_addr_t bd_address;
1156                     memcpy(&bd_address, conn->address, 6);
1157                     hci_shutdown_connection(conn);
1158                     if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
1159                         hci_emit_dedicated_bonding_result(bd_address, status);
1160                     }
1161                 }
1162             }
1163             break;
1164 
1165         case HCI_EVENT_HARDWARE_ERROR:
1166             if(hci_stack->control && hci_stack->control->hw_error){
1167                 (*hci_stack->control->hw_error)();
1168             } else {
1169                 // if no special requests, just reboot stack
1170                 hci_power_control_off();
1171                 hci_power_control_on();
1172             }
1173             break;
1174 
1175         case DAEMON_EVENT_HCI_PACKET_SENT:
1176             // free packet buffer for asynchronous transport
1177             if (hci_transport_synchronous()) break;
1178             hci_stack->hci_packet_buffer_reserved = 0;
1179             break;
1180 
1181 #ifdef HAVE_BLE
1182         case HCI_EVENT_LE_META:
1183             switch (packet[2]){
1184                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1185                     log_info("advertising report received");
1186                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1187                     le_handle_advertisement_report(packet, size);
1188                     break;
1189                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1190                     // Connection management
1191                     bt_flip_addr(addr, &packet[8]);
1192                     addr_type = (bd_addr_type_t)packet[7];
1193                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
1194                     // LE connections are auto-accepted, so just create a connection if there isn't one already
1195                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1196                     if (packet[3]){
1197                         if (conn){
1198                             // outgoing connection failed, remove entry
1199                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1200                             btstack_memory_hci_connection_free( conn );
1201                         }
1202                         // if authentication error, also delete link key
1203                         if (packet[3] == 0x05) {
1204                             hci_drop_link_key_for_bd_addr(&addr);
1205                         }
1206                         break;
1207                     }
1208                     if (!conn){
1209                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1210                     }
1211                     if (!conn){
1212                         // no memory
1213                         break;
1214                     }
1215 
1216                     conn->state = OPEN;
1217                     conn->con_handle = READ_BT_16(packet, 4);
1218 
1219                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
1220 
1221                     // restart timer
1222                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1223                     // run_loop_add_timer(&conn->timeout);
1224 
1225                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1226 
1227                     hci_emit_nr_connections_changed();
1228                     break;
1229 
1230             // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]);
1231 
1232                 default:
1233                     break;
1234             }
1235             break;
1236 #endif
1237         default:
1238             break;
1239     }
1240 
1241     // handle BT initialization
1242     if (hci_stack->state == HCI_STATE_INITIALIZING){
1243         hci_initializing_event_handler(packet, size);
1244     }
1245 
1246     // help with BT sleep
1247     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
1248         && hci_stack->substate == 1
1249         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1250         hci_stack->substate++;
1251     }
1252 
1253     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1254 
1255 	// execute main loop
1256 	hci_run();
1257 }
1258 
1259 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1260     switch (packet_type) {
1261         case HCI_EVENT_PACKET:
1262             event_handler(packet, size);
1263             break;
1264         case HCI_ACL_DATA_PACKET:
1265             acl_handler(packet, size);
1266             break;
1267         default:
1268             break;
1269     }
1270 }
1271 
1272 /** Register HCI packet handlers */
1273 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1274     hci_stack->packet_handler = handler;
1275 }
1276 
1277 static void hci_state_reset(){
1278     // no connections yet
1279     hci_stack->connections = NULL;
1280 
1281     // keep discoverable/connectable as this has been requested by the client(s)
1282     // hci_stack->discoverable = 0;
1283     // hci_stack->connectable = 0;
1284     // hci_stack->bondable = 1;
1285 
1286     // buffer is free
1287     hci_stack->hci_packet_buffer_reserved = 0;
1288 
1289     // no pending cmds
1290     hci_stack->decline_reason = 0;
1291     hci_stack->new_scan_enable_value = 0xff;
1292 
1293     // LE
1294     hci_stack->adv_addr_type = 0;
1295     memset(hci_stack->adv_address, 0, 6);
1296     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1297     hci_stack->le_scan_type = 0xff;
1298 }
1299 
1300 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
1301 
1302 #ifdef HAVE_MALLOC
1303     if (!hci_stack) {
1304         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
1305     }
1306 #else
1307     hci_stack = &hci_stack_static;
1308 #endif
1309     memset(hci_stack, 0, sizeof(hci_stack_t));
1310 
1311     // reference to use transport layer implementation
1312     hci_stack->hci_transport = transport;
1313 
1314     // references to used control implementation
1315     hci_stack->control = control;
1316 
1317     // reference to used config
1318     hci_stack->config = config;
1319 
1320     // higher level handler
1321     hci_stack->packet_handler = dummy_handler;
1322 
1323     // store and open remote device db
1324     hci_stack->remote_device_db = remote_device_db;
1325     if (hci_stack->remote_device_db) {
1326         hci_stack->remote_device_db->open();
1327     }
1328 
1329     // max acl payload size defined in config.h
1330     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1331 
1332     // register packet handlers with transport
1333     transport->register_packet_handler(&packet_handler);
1334 
1335     hci_stack->state = HCI_STATE_OFF;
1336 
1337     // class of device
1338     hci_stack->class_of_device = 0x007a020c; // Smartphone
1339 
1340     // bondable by default
1341     hci_stack->bondable = 1;
1342 
1343     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
1344     hci_stack->ssp_enable = 1;
1345     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1346     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
1347     hci_stack->ssp_auto_accept = 1;
1348 
1349     hci_state_reset();
1350 }
1351 
1352 void hci_close(){
1353     // close remote device db
1354     if (hci_stack->remote_device_db) {
1355         hci_stack->remote_device_db->close();
1356     }
1357     while (hci_stack->connections) {
1358         // cancel all l2cap connections
1359         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
1360         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1361     }
1362     hci_power_control(HCI_POWER_OFF);
1363 
1364 #ifdef HAVE_MALLOC
1365     free(hci_stack);
1366 #endif
1367     hci_stack = NULL;
1368 }
1369 
1370 void hci_set_class_of_device(uint32_t class_of_device){
1371     hci_stack->class_of_device = class_of_device;
1372 }
1373 
1374 void hci_disable_l2cap_timeout_check(){
1375     disable_l2cap_timeouts = 1;
1376 }
1377 // State-Module-Driver overview
1378 // state                    module  low-level
1379 // HCI_STATE_OFF             off      close
1380 // HCI_STATE_INITIALIZING,   on       open
1381 // HCI_STATE_WORKING,        on       open
1382 // HCI_STATE_HALTING,        on       open
1383 // HCI_STATE_SLEEPING,    off/sleep   close
1384 // HCI_STATE_FALLING_ASLEEP  on       open
1385 
1386 static int hci_power_control_on(void){
1387 
1388     // power on
1389     int err = 0;
1390     if (hci_stack->control && hci_stack->control->on){
1391         err = (*hci_stack->control->on)(hci_stack->config);
1392     }
1393     if (err){
1394         log_error( "POWER_ON failed");
1395         hci_emit_hci_open_failed();
1396         return err;
1397     }
1398 
1399     // open low-level device
1400     err = hci_stack->hci_transport->open(hci_stack->config);
1401     if (err){
1402         log_error( "HCI_INIT failed, turning Bluetooth off again");
1403         if (hci_stack->control && hci_stack->control->off){
1404             (*hci_stack->control->off)(hci_stack->config);
1405         }
1406         hci_emit_hci_open_failed();
1407         return err;
1408     }
1409     return 0;
1410 }
1411 
1412 static void hci_power_control_off(void){
1413 
1414     log_info("hci_power_control_off");
1415 
1416     // close low-level device
1417     hci_stack->hci_transport->close(hci_stack->config);
1418 
1419     log_info("hci_power_control_off - hci_transport closed");
1420 
1421     // power off
1422     if (hci_stack->control && hci_stack->control->off){
1423         (*hci_stack->control->off)(hci_stack->config);
1424     }
1425 
1426     log_info("hci_power_control_off - control closed");
1427 
1428     hci_stack->state = HCI_STATE_OFF;
1429 }
1430 
1431 static void hci_power_control_sleep(void){
1432 
1433     log_info("hci_power_control_sleep");
1434 
1435 #if 0
1436     // don't close serial port during sleep
1437 
1438     // close low-level device
1439     hci_stack->hci_transport->close(hci_stack->config);
1440 #endif
1441 
1442     // sleep mode
1443     if (hci_stack->control && hci_stack->control->sleep){
1444         (*hci_stack->control->sleep)(hci_stack->config);
1445     }
1446 
1447     hci_stack->state = HCI_STATE_SLEEPING;
1448 }
1449 
1450 static int hci_power_control_wake(void){
1451 
1452     log_info("hci_power_control_wake");
1453 
1454     // wake on
1455     if (hci_stack->control && hci_stack->control->wake){
1456         (*hci_stack->control->wake)(hci_stack->config);
1457     }
1458 
1459 #if 0
1460     // open low-level device
1461     int err = hci_stack->hci_transport->open(hci_stack->config);
1462     if (err){
1463         log_error( "HCI_INIT failed, turning Bluetooth off again");
1464         if (hci_stack->control && hci_stack->control->off){
1465             (*hci_stack->control->off)(hci_stack->config);
1466         }
1467         hci_emit_hci_open_failed();
1468         return err;
1469     }
1470 #endif
1471 
1472     return 0;
1473 }
1474 
1475 static void hci_power_transition_to_initializing(void){
1476     // set up state machine
1477     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1478     hci_stack->hci_packet_buffer_reserved = 0;
1479     hci_stack->state = HCI_STATE_INITIALIZING;
1480     hci_stack->substate = 0;
1481 }
1482 
1483 int hci_power_control(HCI_POWER_MODE power_mode){
1484 
1485     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
1486 
1487     int err = 0;
1488     switch (hci_stack->state){
1489 
1490         case HCI_STATE_OFF:
1491             switch (power_mode){
1492                 case HCI_POWER_ON:
1493                     err = hci_power_control_on();
1494                     if (err) {
1495                         log_error("hci_power_control_on() error %u", err);
1496                         return err;
1497                     }
1498                     hci_power_transition_to_initializing();
1499                     break;
1500                 case HCI_POWER_OFF:
1501                     // do nothing
1502                     break;
1503                 case HCI_POWER_SLEEP:
1504                     // do nothing (with SLEEP == OFF)
1505                     break;
1506             }
1507             break;
1508 
1509         case HCI_STATE_INITIALIZING:
1510             switch (power_mode){
1511                 case HCI_POWER_ON:
1512                     // do nothing
1513                     break;
1514                 case HCI_POWER_OFF:
1515                     // no connections yet, just turn it off
1516                     hci_power_control_off();
1517                     break;
1518                 case HCI_POWER_SLEEP:
1519                     // no connections yet, just turn it off
1520                     hci_power_control_sleep();
1521                     break;
1522             }
1523             break;
1524 
1525         case HCI_STATE_WORKING:
1526             switch (power_mode){
1527                 case HCI_POWER_ON:
1528                     // do nothing
1529                     break;
1530                 case HCI_POWER_OFF:
1531                     // see hci_run
1532                     hci_stack->state = HCI_STATE_HALTING;
1533                     break;
1534                 case HCI_POWER_SLEEP:
1535                     // see hci_run
1536                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1537                     hci_stack->substate = 0;
1538                     break;
1539             }
1540             break;
1541 
1542         case HCI_STATE_HALTING:
1543             switch (power_mode){
1544                 case HCI_POWER_ON:
1545                     hci_power_transition_to_initializing();
1546                     break;
1547                 case HCI_POWER_OFF:
1548                     // do nothing
1549                     break;
1550                 case HCI_POWER_SLEEP:
1551                     // see hci_run
1552                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1553                     hci_stack->substate = 0;
1554                     break;
1555             }
1556             break;
1557 
1558         case HCI_STATE_FALLING_ASLEEP:
1559             switch (power_mode){
1560                 case HCI_POWER_ON:
1561 
1562 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1563                     // nothing to do, if H4 supports power management
1564                     if (bt_control_iphone_power_management_enabled()){
1565                         hci_stack->state = HCI_STATE_INITIALIZING;
1566                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1567                         break;
1568                     }
1569 #endif
1570                     hci_power_transition_to_initializing();
1571                     break;
1572                 case HCI_POWER_OFF:
1573                     // see hci_run
1574                     hci_stack->state = HCI_STATE_HALTING;
1575                     break;
1576                 case HCI_POWER_SLEEP:
1577                     // do nothing
1578                     break;
1579             }
1580             break;
1581 
1582         case HCI_STATE_SLEEPING:
1583             switch (power_mode){
1584                 case HCI_POWER_ON:
1585 
1586 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1587                     // nothing to do, if H4 supports power management
1588                     if (bt_control_iphone_power_management_enabled()){
1589                         hci_stack->state = HCI_STATE_INITIALIZING;
1590                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1591                         hci_update_scan_enable();
1592                         break;
1593                     }
1594 #endif
1595                     err = hci_power_control_wake();
1596                     if (err) return err;
1597                     hci_power_transition_to_initializing();
1598                     break;
1599                 case HCI_POWER_OFF:
1600                     hci_stack->state = HCI_STATE_HALTING;
1601                     break;
1602                 case HCI_POWER_SLEEP:
1603                     // do nothing
1604                     break;
1605             }
1606             break;
1607     }
1608 
1609     // create internal event
1610 	hci_emit_state();
1611 
1612 	// trigger next/first action
1613 	hci_run();
1614 
1615     return 0;
1616 }
1617 
1618 static void hci_update_scan_enable(void){
1619     // 2 = page scan, 1 = inq scan
1620     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1621     hci_run();
1622 }
1623 
1624 void hci_discoverable_control(uint8_t enable){
1625     if (enable) enable = 1; // normalize argument
1626 
1627     if (hci_stack->discoverable == enable){
1628         hci_emit_discoverable_enabled(hci_stack->discoverable);
1629         return;
1630     }
1631 
1632     hci_stack->discoverable = enable;
1633     hci_update_scan_enable();
1634 }
1635 
1636 void hci_connectable_control(uint8_t enable){
1637     if (enable) enable = 1; // normalize argument
1638 
1639     // don't emit event
1640     if (hci_stack->connectable == enable) return;
1641 
1642     hci_stack->connectable = enable;
1643     hci_update_scan_enable();
1644 }
1645 
1646 bd_addr_t * hci_local_bd_addr(void){
1647     return &hci_stack->local_bd_addr;
1648 }
1649 
1650 void hci_run(){
1651 
1652     hci_connection_t * connection;
1653     linked_item_t * it;
1654 
1655     if (!hci_can_send_command_packet_now()) return;
1656 
1657     // global/non-connection oriented commands
1658 
1659     // decline incoming connections
1660     if (hci_stack->decline_reason){
1661         uint8_t reason = hci_stack->decline_reason;
1662         hci_stack->decline_reason = 0;
1663         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1664         return;
1665     }
1666 
1667     // send scan enable
1668     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
1669         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1670         hci_stack->new_scan_enable_value = 0xff;
1671         return;
1672     }
1673 
1674 #ifdef HAVE_BLE
1675     // handle le scan
1676     if (hci_stack->state == HCI_STATE_WORKING){
1677         switch(hci_stack->le_scanning_state){
1678             case LE_START_SCAN:
1679                 hci_stack->le_scanning_state = LE_SCANNING;
1680                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
1681                 return;
1682 
1683             case LE_STOP_SCAN:
1684                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
1685                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
1686                 return;
1687             default:
1688                 break;
1689         }
1690         if (hci_stack->le_scan_type != 0xff){
1691             // defaults: active scanning, accept all advertisement packets
1692             int scan_type = hci_stack->le_scan_type;
1693             hci_stack->le_scan_type = 0xff;
1694             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);
1695             return;
1696         }
1697     }
1698 #endif
1699 
1700     // send pending HCI commands
1701     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1702         connection = (hci_connection_t *) it;
1703 
1704         switch(connection->state){
1705             case SEND_CREATE_CONNECTION:
1706                 switch(connection->address_type){
1707                     case BD_ADDR_TYPE_CLASSIC:
1708                         log_info("sending hci_create_connection");
1709                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1710                         break;
1711                     default:
1712 #ifdef HAVE_BLE
1713                         log_info("sending hci_le_create_connection");
1714                         hci_send_cmd(&hci_le_create_connection,
1715                                      0x0060,    // scan interval: 60 ms
1716                                      0x0030,    // scan interval: 30 ms
1717                                      0,         // don't use whitelist
1718                                      connection->address_type, // peer address type
1719                                      connection->address,      // peer bd addr
1720                                      hci_stack->adv_addr_type, // our addr type:
1721                                      0x0008,    // conn interval min
1722                                      0x0018,    // conn interval max
1723                                      0,         // conn latency
1724                                      0x0048,    // supervision timeout
1725                                      0x0001,    // min ce length
1726                                      0x0001     // max ce length
1727                                      );
1728 
1729                         connection->state = SENT_CREATE_CONNECTION;
1730 #endif
1731                         break;
1732                 }
1733                 return;
1734 
1735             case RECEIVED_CONNECTION_REQUEST:
1736                 log_info("sending hci_accept_connection_request");
1737                 connection->state = ACCEPTED_CONNECTION_REQUEST;
1738                 hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1739                 return;
1740 
1741 #ifdef HAVE_BLE
1742             case SEND_CANCEL_CONNECTION:
1743                 connection->state = SENT_CANCEL_CONNECTION;
1744                 hci_send_cmd(&hci_le_create_connection_cancel);
1745                 return;
1746 #endif
1747             case SEND_DISCONNECT:
1748                 connection->state = SENT_DISCONNECT;
1749                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
1750                 return;
1751 
1752             default:
1753                 break;
1754         }
1755 
1756         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1757             log_info("responding to link key request");
1758             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1759             link_key_t link_key;
1760             link_key_type_t link_key_type;
1761             if ( hci_stack->remote_device_db
1762               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1763               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
1764                connection->link_key_type = link_key_type;
1765                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1766             } else {
1767                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1768             }
1769             return;
1770         }
1771 
1772         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
1773             log_info("denying to pin request");
1774             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
1775             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1776             return;
1777         }
1778 
1779         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1780             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1781             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
1782             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1783                 // tweak authentication requirements
1784                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1785                 if (connection->bonding_flags & BONDING_DEDICATED){
1786                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
1787                 }
1788                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
1789                     authreq |= 1;
1790                 }
1791                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1792             } else {
1793                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1794             }
1795             return;
1796         }
1797 
1798         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1799             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1800             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1801             return;
1802         }
1803 
1804         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1805             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1806             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1807             return;
1808         }
1809 
1810         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1811             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
1812             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
1813             return;
1814         }
1815 
1816         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
1817             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
1818             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
1819             return;
1820         }
1821         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1822             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
1823             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
1824             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1825             return;
1826         }
1827         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
1828             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
1829             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
1830             return;
1831         }
1832         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1833             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1834             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1835             return;
1836         }
1837     }
1838 
1839     switch (hci_stack->state){
1840         case HCI_STATE_INITIALIZING:
1841             hci_initializing_state_machine();
1842             break;
1843 
1844         case HCI_STATE_HALTING:
1845 
1846             log_info("HCI_STATE_HALTING");
1847             // close all open connections
1848             connection =  (hci_connection_t *) hci_stack->connections;
1849             if (connection){
1850 
1851                 // send disconnect
1852                 if (!hci_can_send_command_packet_now()) return;
1853 
1854                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
1855                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1856 
1857                 // send disconnected event right away - causes higher layer connections to get closed, too.
1858                 hci_shutdown_connection(connection);
1859                 return;
1860             }
1861             log_info("HCI_STATE_HALTING, calling off");
1862 
1863             // switch mode
1864             hci_power_control_off();
1865 
1866             log_info("HCI_STATE_HALTING, emitting state");
1867             hci_emit_state();
1868             log_info("HCI_STATE_HALTING, done");
1869             break;
1870 
1871         case HCI_STATE_FALLING_ASLEEP:
1872             switch(hci_stack->substate) {
1873                 case 0:
1874                     log_info("HCI_STATE_FALLING_ASLEEP");
1875                     // close all open connections
1876                     connection =  (hci_connection_t *) hci_stack->connections;
1877 
1878 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1879                     // don't close connections, if H4 supports power management
1880                     if (bt_control_iphone_power_management_enabled()){
1881                         connection = NULL;
1882                     }
1883 #endif
1884                     if (connection){
1885 
1886                         // send disconnect
1887                         if (!hci_can_send_command_packet_now()) return;
1888 
1889                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
1890                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1891 
1892                         // send disconnected event right away - causes higher layer connections to get closed, too.
1893                         hci_shutdown_connection(connection);
1894                         return;
1895                     }
1896 
1897                     if (hci_classic_supported()){
1898                         // disable page and inquiry scan
1899                         if (!hci_can_send_command_packet_now()) return;
1900 
1901                         log_info("HCI_STATE_HALTING, disabling inq scans");
1902                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
1903 
1904                         // continue in next sub state
1905                         hci_stack->substate++;
1906                         break;
1907                     }
1908                     // fall through for ble-only chips
1909 
1910                 case 2:
1911                     log_info("HCI_STATE_HALTING, calling sleep");
1912 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1913                     // don't actually go to sleep, if H4 supports power management
1914                     if (bt_control_iphone_power_management_enabled()){
1915                         // SLEEP MODE reached
1916                         hci_stack->state = HCI_STATE_SLEEPING;
1917                         hci_emit_state();
1918                         break;
1919                     }
1920 #endif
1921                     // switch mode
1922                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
1923                     hci_emit_state();
1924                     break;
1925 
1926                 default:
1927                     break;
1928             }
1929             break;
1930 
1931         default:
1932             break;
1933     }
1934 }
1935 
1936 int hci_send_cmd_packet(uint8_t *packet, int size){
1937     bd_addr_t addr;
1938     hci_connection_t * conn;
1939     // house-keeping
1940 
1941     // create_connection?
1942     if (IS_COMMAND(packet, hci_create_connection)){
1943         bt_flip_addr(addr, &packet[3]);
1944         log_info("Create_connection to %s", bd_addr_to_str(addr));
1945 
1946         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1947         if (!conn){
1948             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1949             if (!conn){
1950                 // notify client that alloc failed
1951                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1952                 return 0; // don't sent packet to controller
1953             }
1954             conn->state = SEND_CREATE_CONNECTION;
1955         }
1956         log_info("conn state %u", conn->state);
1957         switch (conn->state){
1958             // if connection active exists
1959             case OPEN:
1960                 // and OPEN, emit connection complete command, don't send to controller
1961                 hci_emit_connection_complete(conn, 0);
1962                 return 0;
1963             case SEND_CREATE_CONNECTION:
1964                 // connection created by hci, e.g. dedicated bonding
1965                 break;
1966             default:
1967                 // otherwise, just ignore as it is already in the open process
1968                 return 0;
1969         }
1970         conn->state = SENT_CREATE_CONNECTION;
1971     }
1972 
1973     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1974         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1975     }
1976     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1977         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1978     }
1979 
1980     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1981         if (hci_stack->remote_device_db){
1982             bt_flip_addr(addr, &packet[3]);
1983             hci_stack->remote_device_db->delete_link_key(&addr);
1984         }
1985     }
1986 
1987     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
1988     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
1989         bt_flip_addr(addr, &packet[3]);
1990         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1991         if (conn){
1992             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
1993         }
1994     }
1995 
1996     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
1997     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
1998     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
1999     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
2000         bt_flip_addr(addr, &packet[3]);
2001         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2002         if (conn){
2003             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
2004         }
2005     }
2006 
2007 #ifdef HAVE_BLE
2008     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
2009         hci_stack->adv_addr_type = packet[8];
2010     }
2011     if (IS_COMMAND(packet, hci_le_set_random_address)){
2012         bt_flip_addr(hci_stack->adv_address, &packet[3]);
2013     }
2014 #endif
2015 
2016     hci_stack->num_cmd_packets--;
2017     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2018 
2019     // free packet buffer for synchronous transport implementations
2020     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
2021         hci_stack->hci_packet_buffer_reserved = 0;
2022     }
2023 
2024     return err;
2025 }
2026 
2027 // disconnect because of security block
2028 void hci_disconnect_security_block(hci_con_handle_t con_handle){
2029     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2030     if (!connection) return;
2031     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2032 }
2033 
2034 
2035 // Configure Secure Simple Pairing
2036 
2037 // enable will enable SSP during init
2038 void hci_ssp_set_enable(int enable){
2039     hci_stack->ssp_enable = enable;
2040 }
2041 
2042 int hci_local_ssp_activated(){
2043     return hci_ssp_supported() && hci_stack->ssp_enable;
2044 }
2045 
2046 // if set, BTstack will respond to io capability request using authentication requirement
2047 void hci_ssp_set_io_capability(int io_capability){
2048     hci_stack->ssp_io_capability = io_capability;
2049 }
2050 void hci_ssp_set_authentication_requirement(int authentication_requirement){
2051     hci_stack->ssp_authentication_requirement = authentication_requirement;
2052 }
2053 
2054 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2055 void hci_ssp_set_auto_accept(int auto_accept){
2056     hci_stack->ssp_auto_accept = auto_accept;
2057 }
2058 
2059 /**
2060  * pre: numcmds >= 0 - it's allowed to send a command to the controller
2061  */
2062 int hci_send_cmd(const hci_cmd_t *cmd, ...){
2063 
2064     if (!hci_can_send_command_packet_now()){
2065         log_error("hci_send_cmd called but cannot send packet now");
2066         return 0;
2067     }
2068 
2069     // for HCI INITIALIZATION
2070     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
2071     hci_stack->last_cmd_opcode = cmd->opcode;
2072 
2073     hci_reserve_packet_buffer();
2074     uint8_t * packet = hci_stack->hci_packet_buffer;
2075 
2076     va_list argptr;
2077     va_start(argptr, cmd);
2078     uint16_t size = hci_create_cmd_internal(packet, cmd, argptr);
2079     va_end(argptr);
2080 
2081     return hci_send_cmd_packet(packet, size);
2082 }
2083 
2084 // Create various non-HCI events.
2085 // TODO: generalize, use table similar to hci_create_command
2086 
2087 void hci_emit_state(){
2088     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2089     uint8_t event[3];
2090     event[0] = BTSTACK_EVENT_STATE;
2091     event[1] = sizeof(event) - 2;
2092     event[2] = hci_stack->state;
2093     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2094     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2095 }
2096 
2097 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
2098     uint8_t event[13];
2099     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
2100     event[1] = sizeof(event) - 2;
2101     event[2] = status;
2102     bt_store_16(event, 3, conn->con_handle);
2103     bt_flip_addr(&event[5], conn->address);
2104     event[11] = 1; // ACL connection
2105     event[12] = 0; // encryption disabled
2106     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2107     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2108 }
2109 
2110 void hci_emit_le_connection_complete(hci_connection_t *conn, uint8_t status){
2111     uint8_t event[21];
2112     event[0] = HCI_EVENT_LE_META;
2113     event[1] = sizeof(event) - 2;
2114     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
2115     event[3] = status;
2116     bt_store_16(event, 4, conn->con_handle);
2117     event[6] = 0; // TODO: role
2118     event[7] = conn->address_type;
2119     bt_flip_addr(&event[8], conn->address);
2120     bt_store_16(event, 14, 0); // interval
2121     bt_store_16(event, 16, 0); // latency
2122     bt_store_16(event, 18, 0); // supervision timeout
2123     event[20] = 0; // master clock accuracy
2124     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2125     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2126 }
2127 
2128 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
2129     uint8_t event[6];
2130     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
2131     event[1] = sizeof(event) - 2;
2132     event[2] = 0; // status = OK
2133     bt_store_16(event, 3, handle);
2134     event[5] = reason;
2135     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2136     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2137 }
2138 
2139 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
2140     if (disable_l2cap_timeouts) return;
2141     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
2142     uint8_t event[4];
2143     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
2144     event[1] = sizeof(event) - 2;
2145     bt_store_16(event, 2, conn->con_handle);
2146     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2147     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2148 }
2149 
2150 void hci_emit_nr_connections_changed(){
2151     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
2152     uint8_t event[3];
2153     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
2154     event[1] = sizeof(event) - 2;
2155     event[2] = nr_hci_connections();
2156     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2157     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2158 }
2159 
2160 void hci_emit_hci_open_failed(){
2161     log_info("BTSTACK_EVENT_POWERON_FAILED");
2162     uint8_t event[2];
2163     event[0] = BTSTACK_EVENT_POWERON_FAILED;
2164     event[1] = sizeof(event) - 2;
2165     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2166     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2167 }
2168 
2169 #ifndef EMBEDDED
2170 void hci_emit_btstack_version() {
2171     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
2172     uint8_t event[6];
2173     event[0] = BTSTACK_EVENT_VERSION;
2174     event[1] = sizeof(event) - 2;
2175     event[2] = BTSTACK_MAJOR;
2176     event[3] = BTSTACK_MINOR;
2177     bt_store_16(event, 4, BTSTACK_REVISION);
2178     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2179     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2180 }
2181 #endif
2182 
2183 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
2184     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
2185     uint8_t event[3];
2186     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
2187     event[1] = sizeof(event) - 2;
2188     event[2] = enabled;
2189     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2190     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2191 }
2192 
2193 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
2194     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
2195     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
2196     event[1] = sizeof(event) - 2 - 1;
2197     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
2198     bt_flip_addr(&event[3], *addr);
2199     memcpy(&event[9], name, 248);
2200 
2201     event[9+248] = 0;   // assert \0 for log_info
2202     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2203 
2204     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
2205     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2206 }
2207 
2208 void hci_emit_discoverable_enabled(uint8_t enabled){
2209     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2210     uint8_t event[3];
2211     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2212     event[1] = sizeof(event) - 2;
2213     event[2] = enabled;
2214     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2215     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2216 }
2217 
2218 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2219     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2220     uint8_t event[5];
2221     int pos = 0;
2222     event[pos++] = GAP_SECURITY_LEVEL;
2223     event[pos++] = sizeof(event) - 2;
2224     bt_store_16(event, 2, con_handle);
2225     pos += 2;
2226     event[pos++] = level;
2227     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2228     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2229 }
2230 
2231 void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
2232     log_info("hci_emit_dedicated_bonding_result %u ", status);
2233     uint8_t event[9];
2234     int pos = 0;
2235     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2236     event[pos++] = sizeof(event) - 2;
2237     event[pos++] = status;
2238     bt_flip_addr( * (bd_addr_t *) &event[pos], address);
2239     pos += 6;
2240     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2241     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2242 }
2243 
2244 // query if remote side supports SSP
2245 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
2246     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2247     if (!connection) return 0;
2248     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
2249 }
2250 
2251 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2252     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2253 }
2254 
2255 // GAP API
2256 /**
2257  * @bbrief enable/disable bonding. default is enabled
2258  * @praram enabled
2259  */
2260 void gap_set_bondable_mode(int enable){
2261     hci_stack->bondable = enable ? 1 : 0;
2262 }
2263 
2264 /**
2265  * @brief map link keys to security levels
2266  */
2267 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
2268     switch (link_key_type){
2269         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
2270             return LEVEL_4;
2271         case COMBINATION_KEY:
2272         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
2273             return LEVEL_3;
2274         default:
2275             return LEVEL_2;
2276     }
2277 }
2278 
2279 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
2280     if (!connection) return LEVEL_0;
2281     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
2282     return gap_security_level_for_link_key_type(connection->link_key_type);
2283 }
2284 
2285 
2286 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
2287     log_info("gap_mitm_protection_required_for_security_level %u", level);
2288     return level > LEVEL_2;
2289 }
2290 
2291 /**
2292  * @brief get current security level
2293  */
2294 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
2295     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2296     if (!connection) return LEVEL_0;
2297     return gap_security_level_for_connection(connection);
2298 }
2299 
2300 /**
2301  * @brief request connection to device to
2302  * @result GAP_AUTHENTICATION_RESULT
2303  */
2304 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
2305     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2306     if (!connection){
2307         hci_emit_security_level(con_handle, LEVEL_0);
2308         return;
2309     }
2310     gap_security_level_t current_level = gap_security_level(con_handle);
2311     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
2312     if (current_level >= requested_level){
2313         hci_emit_security_level(con_handle, current_level);
2314         return;
2315     }
2316 
2317     connection->requested_security_level = requested_level;
2318 
2319     // would enabling ecnryption suffice (>= LEVEL_2)?
2320     if (hci_stack->remote_device_db){
2321         link_key_type_t link_key_type;
2322         link_key_t      link_key;
2323         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2324             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2325                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2326                 return;
2327             }
2328         }
2329     }
2330 
2331     // try to authenticate connection
2332     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2333     hci_run();
2334 }
2335 
2336 /**
2337  * @brief start dedicated bonding with device. disconnect after bonding
2338  * @param device
2339  * @param request MITM protection
2340  * @result GAP_DEDICATED_BONDING_COMPLETE
2341  */
2342 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2343 
2344     // create connection state machine
2345     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2346 
2347     if (!connection){
2348         return BTSTACK_MEMORY_ALLOC_FAILED;
2349     }
2350 
2351     // delete linkn key
2352     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2353 
2354     // configure LEVEL_2/3, dedicated bonding
2355     connection->state = SEND_CREATE_CONNECTION;
2356     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
2357     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
2358     connection->bonding_flags = BONDING_DEDICATED;
2359 
2360     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2361 
2362     // handle: connnection failure (connection complete != ok)
2363     // handle: authentication failure
2364     // handle: disconnect on done
2365 
2366     hci_run();
2367 
2368     return 0;
2369 }
2370 
2371 void gap_set_local_name(const char * local_name){
2372     hci_stack->local_name = local_name;
2373 }
2374 
2375 le_command_status_t le_central_start_scan(){
2376     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
2377     hci_stack->le_scanning_state = LE_START_SCAN;
2378     hci_run();
2379     return BLE_PERIPHERAL_OK;
2380 }
2381 
2382 le_command_status_t le_central_stop_scan(){
2383     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
2384     hci_stack->le_scanning_state = LE_STOP_SCAN;
2385     hci_run();
2386     return BLE_PERIPHERAL_OK;
2387 }
2388 
2389 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
2390     hci_stack->le_scan_type     = scan_type;
2391     hci_stack->le_scan_interval = scan_interval;
2392     hci_stack->le_scan_window   = scan_window;
2393     hci_run();
2394 }
2395 
2396 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
2397     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2398     if (!conn){
2399         log_info("le_central_connect: no connection exists yet, creating context");
2400         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
2401         if (!conn){
2402             // notify client that alloc failed
2403             hci_emit_le_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2404             log_info("le_central_connect: failed to alloc context");
2405             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
2406         }
2407         conn->state = SEND_CREATE_CONNECTION;
2408         log_info("le_central_connect: send create connection next");
2409         hci_run();
2410         return BLE_PERIPHERAL_OK;
2411     }
2412 
2413     if (!hci_is_le_connection(conn) ||
2414         conn->state == SEND_CREATE_CONNECTION ||
2415         conn->state == SENT_CREATE_CONNECTION) {
2416         hci_emit_le_connection_complete(conn, ERROR_CODE_COMMAND_DISALLOWED);
2417         log_error("le_central_connect: classic connection or connect is already being created");
2418         return BLE_PERIPHERAL_IN_WRONG_STATE;
2419     }
2420 
2421     log_info("le_central_connect: context exists with state %u", conn->state);
2422     hci_emit_le_connection_complete(conn, 0);
2423     hci_run();
2424     return BLE_PERIPHERAL_OK;
2425 }
2426 
2427 // @assumption: only a single outgoing LE Connection exists
2428 static hci_connection_t * le_central_get_outgoing_connection(){
2429     linked_item_t *it;
2430     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
2431         hci_connection_t * conn = (hci_connection_t *) it;
2432         if (!hci_is_le_connection(conn)) continue;
2433         switch (conn->state){
2434             case SEND_CREATE_CONNECTION:
2435             case SENT_CREATE_CONNECTION:
2436                 return conn;
2437             default:
2438                 break;
2439         };
2440     }
2441     return NULL;
2442 }
2443 
2444 le_command_status_t le_central_connect_cancel(){
2445     hci_connection_t * conn = le_central_get_outgoing_connection();
2446     switch (conn->state){
2447         case SEND_CREATE_CONNECTION:
2448             // skip sending create connection and emit event instead
2449             hci_emit_le_connection_complete(conn, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
2450             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
2451             btstack_memory_hci_connection_free( conn );
2452             break;
2453         case SENT_CREATE_CONNECTION:
2454             // request to send cancel connection
2455             conn->state = SEND_CANCEL_CONNECTION;
2456             hci_run();
2457             break;
2458         default:
2459             break;
2460     }
2461     return BLE_PERIPHERAL_OK;
2462 }
2463 
2464 le_command_status_t gap_disconnect(hci_con_handle_t handle){
2465     hci_connection_t * conn = hci_connection_for_handle(handle);
2466     if (!conn){
2467         hci_emit_disconnection_complete(handle, 0);
2468         return BLE_PERIPHERAL_OK;
2469     }
2470     conn->state = SEND_DISCONNECT;
2471     hci_run();
2472     return BLE_PERIPHERAL_OK;
2473 }
2474 
2475 void hci_disconnect_all(){
2476     linked_list_iterator_t it;
2477     linked_list_iterator_init(&it, &hci_stack->connections);
2478     while (linked_list_iterator_has_next(&it)){
2479         hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it);
2480         if (con->state == SENT_DISCONNECT) continue;
2481         con->state = SEND_DISCONNECT;
2482     }
2483     hci_run();
2484 }
2485