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