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