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