xref: /btstack/src/hci.c (revision 23bed257d17a7298bacea71ae08935f16ab7302f)
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 "../platforms/ios/src/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 = 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 
932                 if (conn->num_acl_packets_sent >= num_packets){
933                     conn->num_acl_packets_sent -= num_packets;
934                 } else {
935                     log_error("hci_number_completed_packets, more slots freed then sent.");
936                     conn->num_acl_packets_sent = 0;
937                 }
938                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
939             }
940             break;
941         }
942         case HCI_EVENT_CONNECTION_REQUEST:
943             bt_flip_addr(addr, &packet[2]);
944             // TODO: eval COD 8-10
945             link_type = packet[11];
946             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
947             if (link_type == 1) { // ACL
948                 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
949                 if (!conn) {
950                     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
951                 }
952                 if (!conn) {
953                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
954                     hci_stack->decline_reason = 0x0d;
955                     BD_ADDR_COPY(hci_stack->decline_addr, addr);
956                     break;
957                 }
958                 conn->state = RECEIVED_CONNECTION_REQUEST;
959                 hci_run();
960             } else {
961                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
962                 hci_stack->decline_reason = 0x0a;
963                 BD_ADDR_COPY(hci_stack->decline_addr, addr);
964             }
965             break;
966 
967         case HCI_EVENT_CONNECTION_COMPLETE:
968             // Connection management
969             bt_flip_addr(addr, &packet[5]);
970             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
971             addr_type = BD_ADDR_TYPE_CLASSIC;
972             conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
973             if (conn) {
974                 if (!packet[2]){
975                     conn->state = OPEN;
976                     conn->con_handle = READ_BT_16(packet, 3);
977                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
978 
979                     // restart timer
980                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
981                     run_loop_add_timer(&conn->timeout);
982 
983                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
984 
985                     hci_emit_nr_connections_changed();
986                 } else {
987                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
988                     uint8_t status = packet[2];
989                     bd_addr_t bd_address;
990                     memcpy(&bd_address, conn->address, 6);
991 
992                     // connection failed, remove entry
993                     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
994                     btstack_memory_hci_connection_free( conn );
995 
996                     // notify client if dedicated bonding
997                     if (notify_dedicated_bonding_failed){
998                         log_info("hci notify_dedicated_bonding_failed");
999                         hci_emit_dedicated_bonding_result(bd_address, status);
1000                     }
1001 
1002                     // if authentication error, also delete link key
1003                     if (packet[2] == 0x05) {
1004                         hci_drop_link_key_for_bd_addr(&addr);
1005                     }
1006                 }
1007             }
1008             break;
1009 
1010         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1011             handle = READ_BT_16(packet, 3);
1012             conn = hci_connection_for_handle(handle);
1013             if (!conn) break;
1014             if (!packet[2]){
1015                 uint8_t * features = &packet[5];
1016                 if (features[6] & (1 << 3)){
1017                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1018                 }
1019             }
1020             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1021             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags);
1022             if (conn->bonding_flags & BONDING_DEDICATED){
1023                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1024             }
1025             break;
1026 
1027         case HCI_EVENT_LINK_KEY_REQUEST:
1028             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1029             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1030             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1031             if (hci_stack->bondable && !hci_stack->remote_device_db) break;
1032             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1033             hci_run();
1034             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1035             return;
1036 
1037         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1038             bt_flip_addr(addr, &packet[2]);
1039             conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1040             if (!conn) break;
1041             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1042             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1043             // Change Connection Encryption keeps link key type
1044             if (link_key_type != CHANGED_COMBINATION_KEY){
1045                 conn->link_key_type = link_key_type;
1046             }
1047             if (!hci_stack->remote_device_db) break;
1048             hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type);
1049             // still forward event to allow dismiss of pairing dialog
1050             break;
1051         }
1052 
1053         case HCI_EVENT_PIN_CODE_REQUEST:
1054             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1055             // non-bondable mode: pin code negative reply will be sent
1056             if (!hci_stack->bondable){
1057                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1058                 hci_run();
1059                 return;
1060             }
1061             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1062             if (!hci_stack->remote_device_db) break;
1063             bt_flip_addr(addr, &packet[2]);
1064             hci_stack->remote_device_db->delete_link_key(&addr);
1065             break;
1066 
1067         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1068             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1069             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1070             break;
1071 
1072         case HCI_EVENT_USER_CONFIRMATION_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_CONFIRM_REPLY);
1076             break;
1077 
1078         case HCI_EVENT_USER_PASSKEY_REQUEST:
1079             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1080             if (!hci_stack->ssp_auto_accept) break;
1081             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1082             break;
1083 
1084         case HCI_EVENT_ENCRYPTION_CHANGE:
1085             handle = READ_BT_16(packet, 3);
1086             conn = hci_connection_for_handle(handle);
1087             if (!conn) break;
1088             if (packet[2] == 0) {
1089                 if (packet[5]){
1090                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1091                 } else {
1092                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1093                 }
1094             }
1095             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1096             break;
1097 
1098         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1099             handle = READ_BT_16(packet, 3);
1100             conn = hci_connection_for_handle(handle);
1101             if (!conn) break;
1102 
1103             // dedicated bonding: send result and disconnect
1104             if (conn->bonding_flags & BONDING_DEDICATED){
1105                 conn->bonding_flags &= ~BONDING_DEDICATED;
1106                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1107                 conn->bonding_status = packet[2];
1108                 break;
1109             }
1110 
1111             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1112                 // link key sufficient for requested security
1113                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1114                 break;
1115             }
1116             // not enough
1117             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1118             break;
1119 
1120 #ifndef EMBEDDED
1121         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1122             if (!hci_stack->remote_device_db) break;
1123             if (packet[2]) break; // status not ok
1124             bt_flip_addr(addr, &packet[3]);
1125             // fix for invalid remote names - terminate on 0xff
1126             for (i=0; i<248;i++){
1127                 if (packet[9+i] == 0xff){
1128                     packet[9+i] = 0;
1129                     break;
1130                 }
1131             }
1132             memset(&device_name, 0, sizeof(device_name_t));
1133             strncpy((char*) device_name, (char*) &packet[9], 248);
1134             hci_stack->remote_device_db->put_name(&addr, &device_name);
1135             break;
1136 
1137         case HCI_EVENT_INQUIRY_RESULT:
1138         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{
1139             if (!hci_stack->remote_device_db) break;
1140             // first send inq result packet
1141             hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1142             // then send cached remote names
1143             int offset = 3;
1144             for (i=0; i<packet[2];i++){
1145                 bt_flip_addr(addr, &packet[offset]);
1146                 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2;
1147                 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){
1148                     hci_emit_remote_name_cached(&addr, &device_name);
1149                 }
1150             }
1151             return;
1152         }
1153 #endif
1154 
1155         // HCI_EVENT_DISCONNECTION_COMPLETE
1156         // has been moved down, to first notify stack before shutting connection down
1157 
1158         case HCI_EVENT_HARDWARE_ERROR:
1159             if(hci_stack->control && hci_stack->control->hw_error){
1160                 (*hci_stack->control->hw_error)();
1161             } else {
1162                 // if no special requests, just reboot stack
1163                 hci_power_control_off();
1164                 hci_power_control_on();
1165             }
1166             break;
1167 
1168         case DAEMON_EVENT_HCI_PACKET_SENT:
1169             // free packet buffer for asynchronous transport
1170             if (hci_transport_synchronous()) break;
1171             hci_stack->hci_packet_buffer_reserved = 0;
1172             break;
1173 
1174 #ifdef HAVE_BLE
1175         case HCI_EVENT_LE_META:
1176             switch (packet[2]){
1177                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1178                     log_info("advertising report received");
1179                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1180                     le_handle_advertisement_report(packet, size);
1181                     break;
1182                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1183                     // Connection management
1184                     bt_flip_addr(addr, &packet[8]);
1185                     addr_type = (bd_addr_type_t)packet[7];
1186                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
1187                     // LE connections are auto-accepted, so just create a connection if there isn't one already
1188                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1189                     if (packet[3]){
1190                         if (conn){
1191                             // outgoing connection failed, remove entry
1192                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1193                             btstack_memory_hci_connection_free( conn );
1194                         }
1195                         // if authentication error, also delete link key
1196                         if (packet[3] == 0x05) {
1197                             hci_drop_link_key_for_bd_addr(&addr);
1198                         }
1199                         break;
1200                     }
1201                     if (!conn){
1202                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1203                     }
1204                     if (!conn){
1205                         // no memory
1206                         break;
1207                     }
1208 
1209                     conn->state = OPEN;
1210                     conn->con_handle = READ_BT_16(packet, 4);
1211 
1212                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
1213 
1214                     // restart timer
1215                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1216                     // run_loop_add_timer(&conn->timeout);
1217 
1218                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1219 
1220                     hci_emit_nr_connections_changed();
1221                     break;
1222 
1223             // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]);
1224 
1225                 default:
1226                     break;
1227             }
1228             break;
1229 #endif
1230         default:
1231             break;
1232     }
1233 
1234     // handle BT initialization
1235     if (hci_stack->state == HCI_STATE_INITIALIZING){
1236         hci_initializing_event_handler(packet, size);
1237     }
1238 
1239     // help with BT sleep
1240     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
1241         && hci_stack->substate == 1
1242         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1243         hci_stack->substate++;
1244     }
1245 
1246     // notify upper stack
1247     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1248 
1249     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
1250     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1251         if (!packet[2]){
1252             handle = READ_BT_16(packet, 3);
1253             hci_connection_t * conn = hci_connection_for_handle(handle);
1254             if (conn) {
1255                 uint8_t status = conn->bonding_status;
1256                 bd_addr_t bd_address;
1257                 memcpy(&bd_address, conn->address, 6);
1258                 hci_shutdown_connection(conn);
1259                 if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
1260                     hci_emit_dedicated_bonding_result(bd_address, status);
1261                 }
1262             }
1263         }
1264     }
1265 
1266 	// execute main loop
1267 	hci_run();
1268 }
1269 
1270 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1271     switch (packet_type) {
1272         case HCI_EVENT_PACKET:
1273             event_handler(packet, size);
1274             break;
1275         case HCI_ACL_DATA_PACKET:
1276             acl_handler(packet, size);
1277             break;
1278         default:
1279             break;
1280     }
1281 }
1282 
1283 /** Register HCI packet handlers */
1284 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1285     hci_stack->packet_handler = handler;
1286 }
1287 
1288 static void hci_state_reset(){
1289     // no connections yet
1290     hci_stack->connections = NULL;
1291 
1292     // keep discoverable/connectable as this has been requested by the client(s)
1293     // hci_stack->discoverable = 0;
1294     // hci_stack->connectable = 0;
1295     // hci_stack->bondable = 1;
1296 
1297     // buffer is free
1298     hci_stack->hci_packet_buffer_reserved = 0;
1299 
1300     // no pending cmds
1301     hci_stack->decline_reason = 0;
1302     hci_stack->new_scan_enable_value = 0xff;
1303 
1304     // LE
1305     hci_stack->adv_addr_type = 0;
1306     memset(hci_stack->adv_address, 0, 6);
1307     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1308     hci_stack->le_scan_type = 0xff;
1309 }
1310 
1311 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
1312 
1313 #ifdef HAVE_MALLOC
1314     if (!hci_stack) {
1315         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
1316     }
1317 #else
1318     hci_stack = &hci_stack_static;
1319 #endif
1320     memset(hci_stack, 0, sizeof(hci_stack_t));
1321 
1322     // reference to use transport layer implementation
1323     hci_stack->hci_transport = transport;
1324 
1325     // references to used control implementation
1326     hci_stack->control = control;
1327 
1328     // reference to used config
1329     hci_stack->config = config;
1330 
1331     // higher level handler
1332     hci_stack->packet_handler = dummy_handler;
1333 
1334     // store and open remote device db
1335     hci_stack->remote_device_db = remote_device_db;
1336     if (hci_stack->remote_device_db) {
1337         hci_stack->remote_device_db->open();
1338     }
1339 
1340     // max acl payload size defined in config.h
1341     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1342 
1343     // register packet handlers with transport
1344     transport->register_packet_handler(&packet_handler);
1345 
1346     hci_stack->state = HCI_STATE_OFF;
1347 
1348     // class of device
1349     hci_stack->class_of_device = 0x007a020c; // Smartphone
1350 
1351     // bondable by default
1352     hci_stack->bondable = 1;
1353 
1354     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
1355     hci_stack->ssp_enable = 1;
1356     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1357     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
1358     hci_stack->ssp_auto_accept = 1;
1359 
1360     hci_state_reset();
1361 }
1362 
1363 void hci_close(){
1364     // close remote device db
1365     if (hci_stack->remote_device_db) {
1366         hci_stack->remote_device_db->close();
1367     }
1368     while (hci_stack->connections) {
1369         // cancel all l2cap connections
1370         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
1371         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1372     }
1373     hci_power_control(HCI_POWER_OFF);
1374 
1375 #ifdef HAVE_MALLOC
1376     free(hci_stack);
1377 #endif
1378     hci_stack = NULL;
1379 }
1380 
1381 void hci_set_class_of_device(uint32_t class_of_device){
1382     hci_stack->class_of_device = class_of_device;
1383 }
1384 
1385 void hci_disable_l2cap_timeout_check(){
1386     disable_l2cap_timeouts = 1;
1387 }
1388 // State-Module-Driver overview
1389 // state                    module  low-level
1390 // HCI_STATE_OFF             off      close
1391 // HCI_STATE_INITIALIZING,   on       open
1392 // HCI_STATE_WORKING,        on       open
1393 // HCI_STATE_HALTING,        on       open
1394 // HCI_STATE_SLEEPING,    off/sleep   close
1395 // HCI_STATE_FALLING_ASLEEP  on       open
1396 
1397 static int hci_power_control_on(void){
1398 
1399     // power on
1400     int err = 0;
1401     if (hci_stack->control && hci_stack->control->on){
1402         err = (*hci_stack->control->on)(hci_stack->config);
1403     }
1404     if (err){
1405         log_error( "POWER_ON failed");
1406         hci_emit_hci_open_failed();
1407         return err;
1408     }
1409 
1410     // open low-level device
1411     err = hci_stack->hci_transport->open(hci_stack->config);
1412     if (err){
1413         log_error( "HCI_INIT failed, turning Bluetooth off again");
1414         if (hci_stack->control && hci_stack->control->off){
1415             (*hci_stack->control->off)(hci_stack->config);
1416         }
1417         hci_emit_hci_open_failed();
1418         return err;
1419     }
1420     return 0;
1421 }
1422 
1423 static void hci_power_control_off(void){
1424 
1425     log_info("hci_power_control_off");
1426 
1427     // close low-level device
1428     hci_stack->hci_transport->close(hci_stack->config);
1429 
1430     log_info("hci_power_control_off - hci_transport closed");
1431 
1432     // power off
1433     if (hci_stack->control && hci_stack->control->off){
1434         (*hci_stack->control->off)(hci_stack->config);
1435     }
1436 
1437     log_info("hci_power_control_off - control closed");
1438 
1439     hci_stack->state = HCI_STATE_OFF;
1440 }
1441 
1442 static void hci_power_control_sleep(void){
1443 
1444     log_info("hci_power_control_sleep");
1445 
1446 #if 0
1447     // don't close serial port during sleep
1448 
1449     // close low-level device
1450     hci_stack->hci_transport->close(hci_stack->config);
1451 #endif
1452 
1453     // sleep mode
1454     if (hci_stack->control && hci_stack->control->sleep){
1455         (*hci_stack->control->sleep)(hci_stack->config);
1456     }
1457 
1458     hci_stack->state = HCI_STATE_SLEEPING;
1459 }
1460 
1461 static int hci_power_control_wake(void){
1462 
1463     log_info("hci_power_control_wake");
1464 
1465     // wake on
1466     if (hci_stack->control && hci_stack->control->wake){
1467         (*hci_stack->control->wake)(hci_stack->config);
1468     }
1469 
1470 #if 0
1471     // open low-level device
1472     int err = hci_stack->hci_transport->open(hci_stack->config);
1473     if (err){
1474         log_error( "HCI_INIT failed, turning Bluetooth off again");
1475         if (hci_stack->control && hci_stack->control->off){
1476             (*hci_stack->control->off)(hci_stack->config);
1477         }
1478         hci_emit_hci_open_failed();
1479         return err;
1480     }
1481 #endif
1482 
1483     return 0;
1484 }
1485 
1486 static void hci_power_transition_to_initializing(void){
1487     // set up state machine
1488     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1489     hci_stack->hci_packet_buffer_reserved = 0;
1490     hci_stack->state = HCI_STATE_INITIALIZING;
1491     hci_stack->substate = 0;
1492 }
1493 
1494 int hci_power_control(HCI_POWER_MODE power_mode){
1495 
1496     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
1497 
1498     int err = 0;
1499     switch (hci_stack->state){
1500 
1501         case HCI_STATE_OFF:
1502             switch (power_mode){
1503                 case HCI_POWER_ON:
1504                     err = hci_power_control_on();
1505                     if (err) {
1506                         log_error("hci_power_control_on() error %u", err);
1507                         return err;
1508                     }
1509                     hci_power_transition_to_initializing();
1510                     break;
1511                 case HCI_POWER_OFF:
1512                     // do nothing
1513                     break;
1514                 case HCI_POWER_SLEEP:
1515                     // do nothing (with SLEEP == OFF)
1516                     break;
1517             }
1518             break;
1519 
1520         case HCI_STATE_INITIALIZING:
1521             switch (power_mode){
1522                 case HCI_POWER_ON:
1523                     // do nothing
1524                     break;
1525                 case HCI_POWER_OFF:
1526                     // no connections yet, just turn it off
1527                     hci_power_control_off();
1528                     break;
1529                 case HCI_POWER_SLEEP:
1530                     // no connections yet, just turn it off
1531                     hci_power_control_sleep();
1532                     break;
1533             }
1534             break;
1535 
1536         case HCI_STATE_WORKING:
1537             switch (power_mode){
1538                 case HCI_POWER_ON:
1539                     // do nothing
1540                     break;
1541                 case HCI_POWER_OFF:
1542                     // see hci_run
1543                     hci_stack->state = HCI_STATE_HALTING;
1544                     break;
1545                 case HCI_POWER_SLEEP:
1546                     // see hci_run
1547                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1548                     hci_stack->substate = 0;
1549                     break;
1550             }
1551             break;
1552 
1553         case HCI_STATE_HALTING:
1554             switch (power_mode){
1555                 case HCI_POWER_ON:
1556                     hci_power_transition_to_initializing();
1557                     break;
1558                 case HCI_POWER_OFF:
1559                     // do nothing
1560                     break;
1561                 case HCI_POWER_SLEEP:
1562                     // see hci_run
1563                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1564                     hci_stack->substate = 0;
1565                     break;
1566             }
1567             break;
1568 
1569         case HCI_STATE_FALLING_ASLEEP:
1570             switch (power_mode){
1571                 case HCI_POWER_ON:
1572 
1573 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1574                     // nothing to do, if H4 supports power management
1575                     if (bt_control_iphone_power_management_enabled()){
1576                         hci_stack->state = HCI_STATE_INITIALIZING;
1577                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1578                         break;
1579                     }
1580 #endif
1581                     hci_power_transition_to_initializing();
1582                     break;
1583                 case HCI_POWER_OFF:
1584                     // see hci_run
1585                     hci_stack->state = HCI_STATE_HALTING;
1586                     break;
1587                 case HCI_POWER_SLEEP:
1588                     // do nothing
1589                     break;
1590             }
1591             break;
1592 
1593         case HCI_STATE_SLEEPING:
1594             switch (power_mode){
1595                 case HCI_POWER_ON:
1596 
1597 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1598                     // nothing to do, if H4 supports power management
1599                     if (bt_control_iphone_power_management_enabled()){
1600                         hci_stack->state = HCI_STATE_INITIALIZING;
1601                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1602                         hci_update_scan_enable();
1603                         break;
1604                     }
1605 #endif
1606                     err = hci_power_control_wake();
1607                     if (err) return err;
1608                     hci_power_transition_to_initializing();
1609                     break;
1610                 case HCI_POWER_OFF:
1611                     hci_stack->state = HCI_STATE_HALTING;
1612                     break;
1613                 case HCI_POWER_SLEEP:
1614                     // do nothing
1615                     break;
1616             }
1617             break;
1618     }
1619 
1620     // create internal event
1621 	hci_emit_state();
1622 
1623 	// trigger next/first action
1624 	hci_run();
1625 
1626     return 0;
1627 }
1628 
1629 static void hci_update_scan_enable(void){
1630     // 2 = page scan, 1 = inq scan
1631     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1632     hci_run();
1633 }
1634 
1635 void hci_discoverable_control(uint8_t enable){
1636     if (enable) enable = 1; // normalize argument
1637 
1638     if (hci_stack->discoverable == enable){
1639         hci_emit_discoverable_enabled(hci_stack->discoverable);
1640         return;
1641     }
1642 
1643     hci_stack->discoverable = enable;
1644     hci_update_scan_enable();
1645 }
1646 
1647 void hci_connectable_control(uint8_t enable){
1648     if (enable) enable = 1; // normalize argument
1649 
1650     // don't emit event
1651     if (hci_stack->connectable == enable) return;
1652 
1653     hci_stack->connectable = enable;
1654     hci_update_scan_enable();
1655 }
1656 
1657 bd_addr_t * hci_local_bd_addr(void){
1658     return &hci_stack->local_bd_addr;
1659 }
1660 
1661 void hci_run(){
1662 
1663     hci_connection_t * connection;
1664     linked_item_t * it;
1665 
1666     if (!hci_can_send_command_packet_now()) return;
1667 
1668     // global/non-connection oriented commands
1669 
1670     // decline incoming connections
1671     if (hci_stack->decline_reason){
1672         uint8_t reason = hci_stack->decline_reason;
1673         hci_stack->decline_reason = 0;
1674         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1675         return;
1676     }
1677 
1678     // send scan enable
1679     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
1680         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1681         hci_stack->new_scan_enable_value = 0xff;
1682         return;
1683     }
1684 
1685 #ifdef HAVE_BLE
1686     // handle le scan
1687     if (hci_stack->state == HCI_STATE_WORKING){
1688         switch(hci_stack->le_scanning_state){
1689             case LE_START_SCAN:
1690                 hci_stack->le_scanning_state = LE_SCANNING;
1691                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
1692                 return;
1693 
1694             case LE_STOP_SCAN:
1695                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
1696                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
1697                 return;
1698             default:
1699                 break;
1700         }
1701         if (hci_stack->le_scan_type != 0xff){
1702             // defaults: active scanning, accept all advertisement packets
1703             int scan_type = hci_stack->le_scan_type;
1704             hci_stack->le_scan_type = 0xff;
1705             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);
1706             return;
1707         }
1708     }
1709 #endif
1710 
1711     // send pending HCI commands
1712     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1713         connection = (hci_connection_t *) it;
1714 
1715         switch(connection->state){
1716             case SEND_CREATE_CONNECTION:
1717                 switch(connection->address_type){
1718                     case BD_ADDR_TYPE_CLASSIC:
1719                         log_info("sending hci_create_connection");
1720                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1721                         break;
1722                     default:
1723 #ifdef HAVE_BLE
1724                         log_info("sending hci_le_create_connection");
1725                         hci_send_cmd(&hci_le_create_connection,
1726                                      0x0060,    // scan interval: 60 ms
1727                                      0x0030,    // scan interval: 30 ms
1728                                      0,         // don't use whitelist
1729                                      connection->address_type, // peer address type
1730                                      connection->address,      // peer bd addr
1731                                      hci_stack->adv_addr_type, // our addr type:
1732                                      0x0008,    // conn interval min
1733                                      0x0018,    // conn interval max
1734                                      0,         // conn latency
1735                                      0x0048,    // supervision timeout
1736                                      0x0001,    // min ce length
1737                                      0x0001     // max ce length
1738                                      );
1739 
1740                         connection->state = SENT_CREATE_CONNECTION;
1741 #endif
1742                         break;
1743                 }
1744                 return;
1745 
1746             case RECEIVED_CONNECTION_REQUEST:
1747                 log_info("sending hci_accept_connection_request");
1748                 connection->state = ACCEPTED_CONNECTION_REQUEST;
1749                 hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1750                 return;
1751 
1752 #ifdef HAVE_BLE
1753             case SEND_CANCEL_CONNECTION:
1754                 connection->state = SENT_CANCEL_CONNECTION;
1755                 hci_send_cmd(&hci_le_create_connection_cancel);
1756                 return;
1757 #endif
1758             case SEND_DISCONNECT:
1759                 connection->state = SENT_DISCONNECT;
1760                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
1761                 return;
1762 
1763             default:
1764                 break;
1765         }
1766 
1767         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1768             log_info("responding to link key request");
1769             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1770             link_key_t link_key;
1771             link_key_type_t link_key_type;
1772             if ( hci_stack->remote_device_db
1773               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1774               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
1775                connection->link_key_type = link_key_type;
1776                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1777             } else {
1778                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1779             }
1780             return;
1781         }
1782 
1783         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
1784             log_info("denying to pin request");
1785             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
1786             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1787             return;
1788         }
1789 
1790         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1791             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1792             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
1793             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1794                 // tweak authentication requirements
1795                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1796                 if (connection->bonding_flags & BONDING_DEDICATED){
1797                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
1798                 }
1799                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
1800                     authreq |= 1;
1801                 }
1802                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1803             } else {
1804                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1805             }
1806             return;
1807         }
1808 
1809         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1810             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1811             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1812             return;
1813         }
1814 
1815         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1816             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1817             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1818             return;
1819         }
1820 
1821         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1822             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
1823             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
1824             return;
1825         }
1826 
1827         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
1828             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
1829             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
1830             return;
1831         }
1832         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1833             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
1834             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
1835             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1836             return;
1837         }
1838         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
1839             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
1840             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
1841             return;
1842         }
1843         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1844             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1845             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1846             return;
1847         }
1848 #ifdef HAVE_BLE
1849         if (connection->le_conn_interval_min){
1850             uint16_t connection_interval_min = connection->le_conn_interval_min;
1851             connection->le_conn_interval_min = 0;
1852             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
1853                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
1854                 0x0000, 0xffff);
1855         }
1856 #endif
1857     }
1858 
1859     switch (hci_stack->state){
1860         case HCI_STATE_INITIALIZING:
1861             hci_initializing_state_machine();
1862             break;
1863 
1864         case HCI_STATE_HALTING:
1865 
1866             log_info("HCI_STATE_HALTING");
1867             // close all open connections
1868             connection =  (hci_connection_t *) hci_stack->connections;
1869             if (connection){
1870 
1871                 // send disconnect
1872                 if (!hci_can_send_command_packet_now()) return;
1873 
1874                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
1875                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1876 
1877                 // send disconnected event right away - causes higher layer connections to get closed, too.
1878                 hci_shutdown_connection(connection);
1879                 return;
1880             }
1881             log_info("HCI_STATE_HALTING, calling off");
1882 
1883             // switch mode
1884             hci_power_control_off();
1885 
1886             log_info("HCI_STATE_HALTING, emitting state");
1887             hci_emit_state();
1888             log_info("HCI_STATE_HALTING, done");
1889             break;
1890 
1891         case HCI_STATE_FALLING_ASLEEP:
1892             switch(hci_stack->substate) {
1893                 case 0:
1894                     log_info("HCI_STATE_FALLING_ASLEEP");
1895                     // close all open connections
1896                     connection =  (hci_connection_t *) hci_stack->connections;
1897 
1898 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1899                     // don't close connections, if H4 supports power management
1900                     if (bt_control_iphone_power_management_enabled()){
1901                         connection = NULL;
1902                     }
1903 #endif
1904                     if (connection){
1905 
1906                         // send disconnect
1907                         if (!hci_can_send_command_packet_now()) return;
1908 
1909                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
1910                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1911 
1912                         // send disconnected event right away - causes higher layer connections to get closed, too.
1913                         hci_shutdown_connection(connection);
1914                         return;
1915                     }
1916 
1917                     if (hci_classic_supported()){
1918                         // disable page and inquiry scan
1919                         if (!hci_can_send_command_packet_now()) return;
1920 
1921                         log_info("HCI_STATE_HALTING, disabling inq scans");
1922                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
1923 
1924                         // continue in next sub state
1925                         hci_stack->substate++;
1926                         break;
1927                     }
1928                     // fall through for ble-only chips
1929 
1930                 case 2:
1931                     log_info("HCI_STATE_HALTING, calling sleep");
1932 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1933                     // don't actually go to sleep, if H4 supports power management
1934                     if (bt_control_iphone_power_management_enabled()){
1935                         // SLEEP MODE reached
1936                         hci_stack->state = HCI_STATE_SLEEPING;
1937                         hci_emit_state();
1938                         break;
1939                     }
1940 #endif
1941                     // switch mode
1942                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
1943                     hci_emit_state();
1944                     break;
1945 
1946                 default:
1947                     break;
1948             }
1949             break;
1950 
1951         default:
1952             break;
1953     }
1954 }
1955 
1956 int hci_send_cmd_packet(uint8_t *packet, int size){
1957     bd_addr_t addr;
1958     hci_connection_t * conn;
1959     // house-keeping
1960 
1961     // create_connection?
1962     if (IS_COMMAND(packet, hci_create_connection)){
1963         bt_flip_addr(addr, &packet[3]);
1964         log_info("Create_connection to %s", bd_addr_to_str(addr));
1965 
1966         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1967         if (!conn){
1968             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1969             if (!conn){
1970                 // notify client that alloc failed
1971                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1972                 return 0; // don't sent packet to controller
1973             }
1974             conn->state = SEND_CREATE_CONNECTION;
1975         }
1976         log_info("conn state %u", conn->state);
1977         switch (conn->state){
1978             // if connection active exists
1979             case OPEN:
1980                 // and OPEN, emit connection complete command, don't send to controller
1981                 hci_emit_connection_complete(conn, 0);
1982                 return 0;
1983             case SEND_CREATE_CONNECTION:
1984                 // connection created by hci, e.g. dedicated bonding
1985                 break;
1986             default:
1987                 // otherwise, just ignore as it is already in the open process
1988                 return 0;
1989         }
1990         conn->state = SENT_CREATE_CONNECTION;
1991     }
1992 
1993     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1994         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1995     }
1996     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1997         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1998     }
1999 
2000     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
2001         if (hci_stack->remote_device_db){
2002             bt_flip_addr(addr, &packet[3]);
2003             hci_stack->remote_device_db->delete_link_key(&addr);
2004         }
2005     }
2006 
2007     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
2008     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
2009         bt_flip_addr(addr, &packet[3]);
2010         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2011         if (conn){
2012             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
2013         }
2014     }
2015 
2016     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
2017     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
2018     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
2019     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
2020         bt_flip_addr(addr, &packet[3]);
2021         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2022         if (conn){
2023             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
2024         }
2025     }
2026 
2027 #ifdef HAVE_BLE
2028     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
2029         hci_stack->adv_addr_type = packet[8];
2030     }
2031     if (IS_COMMAND(packet, hci_le_set_random_address)){
2032         bt_flip_addr(hci_stack->adv_address, &packet[3]);
2033     }
2034 #endif
2035 
2036     hci_stack->num_cmd_packets--;
2037     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2038 
2039     // free packet buffer for synchronous transport implementations
2040     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
2041         hci_stack->hci_packet_buffer_reserved = 0;
2042     }
2043 
2044     return err;
2045 }
2046 
2047 // disconnect because of security block
2048 void hci_disconnect_security_block(hci_con_handle_t con_handle){
2049     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2050     if (!connection) return;
2051     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2052 }
2053 
2054 
2055 // Configure Secure Simple Pairing
2056 
2057 // enable will enable SSP during init
2058 void hci_ssp_set_enable(int enable){
2059     hci_stack->ssp_enable = enable;
2060 }
2061 
2062 int hci_local_ssp_activated(){
2063     return hci_ssp_supported() && hci_stack->ssp_enable;
2064 }
2065 
2066 // if set, BTstack will respond to io capability request using authentication requirement
2067 void hci_ssp_set_io_capability(int io_capability){
2068     hci_stack->ssp_io_capability = io_capability;
2069 }
2070 void hci_ssp_set_authentication_requirement(int authentication_requirement){
2071     hci_stack->ssp_authentication_requirement = authentication_requirement;
2072 }
2073 
2074 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2075 void hci_ssp_set_auto_accept(int auto_accept){
2076     hci_stack->ssp_auto_accept = auto_accept;
2077 }
2078 
2079 /**
2080  * pre: numcmds >= 0 - it's allowed to send a command to the controller
2081  */
2082 int hci_send_cmd(const hci_cmd_t *cmd, ...){
2083 
2084     if (!hci_can_send_command_packet_now()){
2085         log_error("hci_send_cmd called but cannot send packet now");
2086         return 0;
2087     }
2088 
2089     // for HCI INITIALIZATION
2090     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
2091     hci_stack->last_cmd_opcode = cmd->opcode;
2092 
2093     hci_reserve_packet_buffer();
2094     uint8_t * packet = hci_stack->hci_packet_buffer;
2095 
2096     va_list argptr;
2097     va_start(argptr, cmd);
2098     uint16_t size = hci_create_cmd_internal(packet, cmd, argptr);
2099     va_end(argptr);
2100 
2101     return hci_send_cmd_packet(packet, size);
2102 }
2103 
2104 // Create various non-HCI events.
2105 // TODO: generalize, use table similar to hci_create_command
2106 
2107 void hci_emit_state(){
2108     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2109     uint8_t event[3];
2110     event[0] = BTSTACK_EVENT_STATE;
2111     event[1] = sizeof(event) - 2;
2112     event[2] = hci_stack->state;
2113     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2114     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2115 }
2116 
2117 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
2118     uint8_t event[13];
2119     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
2120     event[1] = sizeof(event) - 2;
2121     event[2] = status;
2122     bt_store_16(event, 3, conn->con_handle);
2123     bt_flip_addr(&event[5], conn->address);
2124     event[11] = 1; // ACL connection
2125     event[12] = 0; // encryption disabled
2126     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2127     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2128 }
2129 
2130 void hci_emit_le_connection_complete(hci_connection_t *conn, uint8_t status){
2131     uint8_t event[21];
2132     event[0] = HCI_EVENT_LE_META;
2133     event[1] = sizeof(event) - 2;
2134     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
2135     event[3] = status;
2136     bt_store_16(event, 4, conn->con_handle);
2137     event[6] = 0; // TODO: role
2138     event[7] = conn->address_type;
2139     bt_flip_addr(&event[8], conn->address);
2140     bt_store_16(event, 14, 0); // interval
2141     bt_store_16(event, 16, 0); // latency
2142     bt_store_16(event, 18, 0); // supervision timeout
2143     event[20] = 0; // master clock accuracy
2144     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2145     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2146 }
2147 
2148 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
2149     uint8_t event[6];
2150     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
2151     event[1] = sizeof(event) - 2;
2152     event[2] = 0; // status = OK
2153     bt_store_16(event, 3, handle);
2154     event[5] = reason;
2155     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2156     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2157 }
2158 
2159 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
2160     if (disable_l2cap_timeouts) return;
2161     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
2162     uint8_t event[4];
2163     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
2164     event[1] = sizeof(event) - 2;
2165     bt_store_16(event, 2, conn->con_handle);
2166     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2167     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2168 }
2169 
2170 void hci_emit_nr_connections_changed(){
2171     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
2172     uint8_t event[3];
2173     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
2174     event[1] = sizeof(event) - 2;
2175     event[2] = nr_hci_connections();
2176     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2177     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2178 }
2179 
2180 void hci_emit_hci_open_failed(){
2181     log_info("BTSTACK_EVENT_POWERON_FAILED");
2182     uint8_t event[2];
2183     event[0] = BTSTACK_EVENT_POWERON_FAILED;
2184     event[1] = sizeof(event) - 2;
2185     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2186     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2187 }
2188 
2189 #ifndef EMBEDDED
2190 void hci_emit_btstack_version() {
2191     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
2192     uint8_t event[6];
2193     event[0] = BTSTACK_EVENT_VERSION;
2194     event[1] = sizeof(event) - 2;
2195     event[2] = BTSTACK_MAJOR;
2196     event[3] = BTSTACK_MINOR;
2197     bt_store_16(event, 4, BTSTACK_REVISION);
2198     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2199     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2200 }
2201 #endif
2202 
2203 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
2204     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
2205     uint8_t event[3];
2206     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
2207     event[1] = sizeof(event) - 2;
2208     event[2] = enabled;
2209     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2210     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2211 }
2212 
2213 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
2214     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
2215     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
2216     event[1] = sizeof(event) - 2 - 1;
2217     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
2218     bt_flip_addr(&event[3], *addr);
2219     memcpy(&event[9], name, 248);
2220 
2221     event[9+248] = 0;   // assert \0 for log_info
2222     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2223 
2224     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
2225     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2226 }
2227 
2228 void hci_emit_discoverable_enabled(uint8_t enabled){
2229     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2230     uint8_t event[3];
2231     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2232     event[1] = sizeof(event) - 2;
2233     event[2] = enabled;
2234     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2235     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2236 }
2237 
2238 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2239     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2240     uint8_t event[5];
2241     int pos = 0;
2242     event[pos++] = GAP_SECURITY_LEVEL;
2243     event[pos++] = sizeof(event) - 2;
2244     bt_store_16(event, 2, con_handle);
2245     pos += 2;
2246     event[pos++] = level;
2247     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2248     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2249 }
2250 
2251 void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
2252     log_info("hci_emit_dedicated_bonding_result %u ", status);
2253     uint8_t event[9];
2254     int pos = 0;
2255     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2256     event[pos++] = sizeof(event) - 2;
2257     event[pos++] = status;
2258     bt_flip_addr( * (bd_addr_t *) &event[pos], address);
2259     pos += 6;
2260     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2261     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2262 }
2263 
2264 // query if remote side supports SSP
2265 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
2266     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2267     if (!connection) return 0;
2268     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
2269 }
2270 
2271 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2272     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2273 }
2274 
2275 // GAP API
2276 /**
2277  * @bbrief enable/disable bonding. default is enabled
2278  * @praram enabled
2279  */
2280 void gap_set_bondable_mode(int enable){
2281     hci_stack->bondable = enable ? 1 : 0;
2282 }
2283 
2284 /**
2285  * @brief map link keys to security levels
2286  */
2287 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
2288     switch (link_key_type){
2289         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
2290             return LEVEL_4;
2291         case COMBINATION_KEY:
2292         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
2293             return LEVEL_3;
2294         default:
2295             return LEVEL_2;
2296     }
2297 }
2298 
2299 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
2300     if (!connection) return LEVEL_0;
2301     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
2302     return gap_security_level_for_link_key_type(connection->link_key_type);
2303 }
2304 
2305 
2306 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
2307     log_info("gap_mitm_protection_required_for_security_level %u", level);
2308     return level > LEVEL_2;
2309 }
2310 
2311 /**
2312  * @brief get current security level
2313  */
2314 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
2315     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2316     if (!connection) return LEVEL_0;
2317     return gap_security_level_for_connection(connection);
2318 }
2319 
2320 /**
2321  * @brief request connection to device to
2322  * @result GAP_AUTHENTICATION_RESULT
2323  */
2324 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
2325     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2326     if (!connection){
2327         hci_emit_security_level(con_handle, LEVEL_0);
2328         return;
2329     }
2330     gap_security_level_t current_level = gap_security_level(con_handle);
2331     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
2332     if (current_level >= requested_level){
2333         hci_emit_security_level(con_handle, current_level);
2334         return;
2335     }
2336 
2337     connection->requested_security_level = requested_level;
2338 
2339     // would enabling ecnryption suffice (>= LEVEL_2)?
2340     if (hci_stack->remote_device_db){
2341         link_key_type_t link_key_type;
2342         link_key_t      link_key;
2343         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2344             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2345                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2346                 return;
2347             }
2348         }
2349     }
2350 
2351     // try to authenticate connection
2352     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2353     hci_run();
2354 }
2355 
2356 /**
2357  * @brief start dedicated bonding with device. disconnect after bonding
2358  * @param device
2359  * @param request MITM protection
2360  * @result GAP_DEDICATED_BONDING_COMPLETE
2361  */
2362 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2363 
2364     // create connection state machine
2365     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2366 
2367     if (!connection){
2368         return BTSTACK_MEMORY_ALLOC_FAILED;
2369     }
2370 
2371     // delete linkn key
2372     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2373 
2374     // configure LEVEL_2/3, dedicated bonding
2375     connection->state = SEND_CREATE_CONNECTION;
2376     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
2377     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
2378     connection->bonding_flags = BONDING_DEDICATED;
2379 
2380     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2381 
2382     // handle: connnection failure (connection complete != ok)
2383     // handle: authentication failure
2384     // handle: disconnect on done
2385 
2386     hci_run();
2387 
2388     return 0;
2389 }
2390 
2391 void gap_set_local_name(const char * local_name){
2392     hci_stack->local_name = local_name;
2393 }
2394 
2395 le_command_status_t le_central_start_scan(){
2396     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
2397     hci_stack->le_scanning_state = LE_START_SCAN;
2398     hci_run();
2399     return BLE_PERIPHERAL_OK;
2400 }
2401 
2402 le_command_status_t le_central_stop_scan(){
2403     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
2404     hci_stack->le_scanning_state = LE_STOP_SCAN;
2405     hci_run();
2406     return BLE_PERIPHERAL_OK;
2407 }
2408 
2409 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
2410     hci_stack->le_scan_type     = scan_type;
2411     hci_stack->le_scan_interval = scan_interval;
2412     hci_stack->le_scan_window   = scan_window;
2413     hci_run();
2414 }
2415 
2416 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
2417     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2418     if (!conn){
2419         log_info("le_central_connect: no connection exists yet, creating context");
2420         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
2421         if (!conn){
2422             // notify client that alloc failed
2423             hci_emit_le_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2424             log_info("le_central_connect: failed to alloc context");
2425             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
2426         }
2427         conn->state = SEND_CREATE_CONNECTION;
2428         log_info("le_central_connect: send create connection next");
2429         hci_run();
2430         return BLE_PERIPHERAL_OK;
2431     }
2432 
2433     if (!hci_is_le_connection(conn) ||
2434         conn->state == SEND_CREATE_CONNECTION ||
2435         conn->state == SENT_CREATE_CONNECTION) {
2436         hci_emit_le_connection_complete(conn, ERROR_CODE_COMMAND_DISALLOWED);
2437         log_error("le_central_connect: classic connection or connect is already being created");
2438         return BLE_PERIPHERAL_IN_WRONG_STATE;
2439     }
2440 
2441     log_info("le_central_connect: context exists with state %u", conn->state);
2442     hci_emit_le_connection_complete(conn, 0);
2443     hci_run();
2444     return BLE_PERIPHERAL_OK;
2445 }
2446 
2447 // @assumption: only a single outgoing LE Connection exists
2448 static hci_connection_t * le_central_get_outgoing_connection(){
2449     linked_item_t *it;
2450     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
2451         hci_connection_t * conn = (hci_connection_t *) it;
2452         if (!hci_is_le_connection(conn)) continue;
2453         switch (conn->state){
2454             case SEND_CREATE_CONNECTION:
2455             case SENT_CREATE_CONNECTION:
2456                 return conn;
2457             default:
2458                 break;
2459         };
2460     }
2461     return NULL;
2462 }
2463 
2464 le_command_status_t le_central_connect_cancel(){
2465     hci_connection_t * conn = le_central_get_outgoing_connection();
2466     switch (conn->state){
2467         case SEND_CREATE_CONNECTION:
2468             // skip sending create connection and emit event instead
2469             hci_emit_le_connection_complete(conn, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
2470             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
2471             btstack_memory_hci_connection_free( conn );
2472             break;
2473         case SENT_CREATE_CONNECTION:
2474             // request to send cancel connection
2475             conn->state = SEND_CANCEL_CONNECTION;
2476             hci_run();
2477             break;
2478         default:
2479             break;
2480     }
2481     return BLE_PERIPHERAL_OK;
2482 }
2483 
2484 /**
2485  * @brief Updates the connection parameters for a given LE connection
2486  * @param handle
2487  * @param conn_interval_min (unit: 1.25ms)
2488  * @param conn_interval_max (unit: 1.25ms)
2489  * @param conn_latency
2490  * @param supervision_timeout (unit: 10ms)
2491  * @returns 0 if ok
2492  */
2493 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
2494     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
2495     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2496     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2497     connection->le_conn_interval_min = conn_interval_min;
2498     connection->le_conn_interval_max = conn_interval_max;
2499     connection->le_conn_latency = conn_latency;
2500     connection->le_supervision_timeout = supervision_timeout;
2501     return 0;
2502 }
2503 
2504 le_command_status_t gap_disconnect(hci_con_handle_t handle){
2505     hci_connection_t * conn = hci_connection_for_handle(handle);
2506     if (!conn){
2507         hci_emit_disconnection_complete(handle, 0);
2508         return BLE_PERIPHERAL_OK;
2509     }
2510     conn->state = SEND_DISCONNECT;
2511     hci_run();
2512     return BLE_PERIPHERAL_OK;
2513 }
2514 
2515 void hci_disconnect_all(){
2516     linked_list_iterator_t it;
2517     linked_list_iterator_init(&it, &hci_stack->connections);
2518     while (linked_list_iterator_has_next(&it)){
2519         hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it);
2520         if (con->state == SENT_DISCONNECT) continue;
2521         con->state = SEND_DISCONNECT;
2522     }
2523     hci_run();
2524 }
2525