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