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