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