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