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