xref: /btstack/src/hci.c (revision 4c57c146cca3ee04368839d29d9830519edc106d)
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 "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 
74 // the STACK is here
75 static hci_stack_t       hci_stack;
76 
77 /**
78  * get connection for a given handle
79  *
80  * @return connection OR NULL, if not found
81  */
82 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
83     linked_item_t *it;
84     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
85         if ( ((hci_connection_t *) it)->con_handle == con_handle){
86             return (hci_connection_t *) it;
87         }
88     }
89     return NULL;
90 }
91 
92 static void hci_connection_timeout_handler(timer_source_t *timer){
93     hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item);
94 #ifdef HAVE_TIME
95     struct timeval tv;
96     gettimeofday(&tv, NULL);
97     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
98         // connections might be timed out
99         hci_emit_l2cap_check_timeout(connection);
100     }
101 #endif
102 #ifdef HAVE_TICK
103     if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
104         // connections might be timed out
105         hci_emit_l2cap_check_timeout(connection);
106     }
107 #endif
108     run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
109     run_loop_add_timer(timer);
110 }
111 
112 static void hci_connection_timestamp(hci_connection_t *connection){
113 #ifdef HAVE_TIME
114     gettimeofday(&connection->timestamp, NULL);
115 #endif
116 #ifdef HAVE_TICK
117     connection->timestamp = embedded_get_ticks();
118 #endif
119 }
120 
121 /**
122  * create connection for given address
123  *
124  * @return connection OR NULL, if no memory left
125  */
126 static hci_connection_t * create_connection_for_addr(bd_addr_t addr){
127     hci_connection_t * conn = (hci_connection_t *) btstack_memory_hci_connection_get();
128     if (!conn) return NULL;
129     BD_ADDR_COPY(conn->address, addr);
130     conn->con_handle = 0xffff;
131     conn->authentication_flags = AUTH_FLAGS_NONE;
132     linked_item_set_user(&conn->timeout.item, conn);
133     conn->timeout.process = hci_connection_timeout_handler;
134     hci_connection_timestamp(conn);
135     conn->acl_recombination_length = 0;
136     conn->acl_recombination_pos = 0;
137     conn->num_acl_packets_sent = 0;
138     linked_list_add(&hci_stack.connections, (linked_item_t *) conn);
139     return conn;
140 }
141 
142 /**
143  * get connection for given address
144  *
145  * @return connection OR NULL, if not found
146  */
147 static hci_connection_t * connection_for_address(bd_addr_t address){
148     linked_item_t *it;
149     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
150         if ( ! BD_ADDR_CMP( ((hci_connection_t *) it)->address, address) ){
151             return (hci_connection_t *) it;
152         }
153     }
154     return NULL;
155 }
156 
157 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
158     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
159 }
160 
161 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
162     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
163 }
164 
165 
166 /**
167  * add authentication flags and reset timer
168  */
169 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
170     bd_addr_t addr;
171     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
172     hci_connection_t * conn = connection_for_address(addr);
173     if (conn) {
174         connectionSetAuthenticationFlags(conn, flags);
175         hci_connection_timestamp(conn);
176     }
177 }
178 
179 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
180     hci_connection_t * conn = hci_connection_for_handle(handle);
181     if (!conn) return 0;
182     if (!conn->authentication_flags) return 0;
183     if (conn->authentication_flags & SENT_LINK_KEY_REPLY) return 0;
184     if (conn->authentication_flags & RECV_LINK_KEY_NOTIFICATION) return 0;
185     return 1;
186 }
187 
188 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
189     if (hci_stack.remote_device_db) {
190         hci_stack.remote_device_db->delete_link_key(addr);
191     }
192 }
193 
194 
195 /**
196  * count connections
197  */
198 static int nr_hci_connections(void){
199     int count = 0;
200     linked_item_t *it;
201     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next, count++);
202     return count;
203 }
204 
205 /**
206  * Dummy handler called by HCI
207  */
208 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
209 }
210 
211 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
212     hci_connection_t * connection = hci_connection_for_handle(handle);
213     if (!connection) {
214         log_error("hci_number_outgoing_packets connectino for handle %u does not exist!\n", handle);
215         return 0;
216     }
217     return connection->num_acl_packets_sent;
218 }
219 
220 uint8_t hci_number_free_acl_slots(){
221     uint8_t free_slots = hci_stack.total_num_acl_packets;
222     linked_item_t *it;
223     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
224         hci_connection_t * connection = (hci_connection_t *) it;
225         if (free_slots < connection->num_acl_packets_sent) {
226             log_error("hci_number_free_acl_slots: sum of outgoing packets > total acl packets!\n");
227             return 0;
228         }
229         free_slots -= connection->num_acl_packets_sent;
230     }
231     return free_slots;
232 }
233 
234 int hci_can_send_packet_now(uint8_t packet_type){
235 
236     // check for async hci transport implementations
237     if (hci_stack.hci_transport->can_send_packet_now){
238         if (!hci_stack.hci_transport->can_send_packet_now(packet_type)){
239             return 0;
240         }
241     }
242 
243     // check regular Bluetooth flow control
244     switch (packet_type) {
245         case HCI_ACL_DATA_PACKET:
246             return hci_number_free_acl_slots();
247         case HCI_COMMAND_DATA_PACKET:
248             return hci_stack.num_cmd_packets;
249         default:
250             return 0;
251     }
252 }
253 
254 int hci_send_acl_packet(uint8_t *packet, int size){
255 
256     // check for free places on BT module
257     if (!hci_number_free_acl_slots()) return BTSTACK_ACL_BUFFERS_FULL;
258 
259     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
260     hci_connection_t *connection = hci_connection_for_handle( con_handle);
261     if (!connection) return 0;
262     hci_connection_timestamp(connection);
263 
264     // count packet
265     connection->num_acl_packets_sent++;
266     // log_info("hci_send_acl_packet - handle %u, sent %u\n", connection->con_handle, connection->num_acl_packets_sent);
267 
268     // send packet
269     int err = hci_stack.hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
270 
271     return err;
272 }
273 
274 static void acl_handler(uint8_t *packet, int size){
275 
276     // log_info("acl_handler: size %u", size);
277 
278     // get info
279     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
280     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
281     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
282     uint16_t acl_length         = READ_ACL_LENGTH(packet);
283 
284     // ignore non-registered handle
285     if (!conn){
286         log_error( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle);
287         return;
288     }
289 
290     // assert packet is complete
291     if (acl_length + 4 != size){
292         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
293         return;
294     }
295 
296     // update idle timestamp
297     hci_connection_timestamp(conn);
298 
299     // handle different packet types
300     switch (acl_flags & 0x03) {
301 
302         case 0x01: // continuation fragment
303 
304             // sanity check
305             if (conn->acl_recombination_pos == 0) {
306                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle);
307                 return;
308             }
309 
310             // append fragment payload (header already stored)
311             memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length );
312             conn->acl_recombination_pos += acl_length;
313 
314             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n", acl_length,
315             //        conn->acl_recombination_pos, conn->acl_recombination_length);
316 
317             // forward complete L2CAP packet if complete.
318             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
319 
320                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos);
321                 // reset recombination buffer
322                 conn->acl_recombination_length = 0;
323                 conn->acl_recombination_pos = 0;
324             }
325             break;
326 
327         case 0x02: { // first fragment
328 
329             // sanity check
330             if (conn->acl_recombination_pos) {
331                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle);
332                 return;
333             }
334 
335             // peek into L2CAP packet!
336             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
337 
338             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length);
339 
340             // compare fragment size to L2CAP packet size
341             if (acl_length >= l2cap_length + 4){
342 
343                 // forward fragment as L2CAP packet
344                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
345 
346             } else {
347                 // store first fragment and tweak acl length for complete package
348                 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4);
349                 conn->acl_recombination_pos    = acl_length + 4;
350                 conn->acl_recombination_length = l2cap_length;
351                 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4);
352             }
353             break;
354 
355         }
356         default:
357             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03);
358             return;
359     }
360 
361     // execute main loop
362     hci_run();
363 }
364 
365 static void hci_shutdown_connection(hci_connection_t *conn){
366     log_info("Connection closed: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
367 
368     // cancel all l2cap connections
369     hci_emit_disconnection_complete(conn->con_handle, 0x16);    // terminated by local host
370 
371     run_loop_remove_timer(&conn->timeout);
372 
373     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
374     btstack_memory_hci_connection_free( conn );
375 
376     // now it's gone
377     hci_emit_nr_connections_changed();
378 }
379 
380 static const uint16_t packet_type_sizes[] = {
381     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
382     HCI_ACL_DH1_SIZE, 0, 0, 0,
383     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
384     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
385 };
386 static const uint8_t  packet_type_feature_requirement_bit[] = {
387      0, // 3 slot packets
388      1, // 5 slot packets
389     25, // EDR 2 mpbs
390     26, // EDR 3 mbps
391     39, // 3 slot EDR packts
392     40, // 5 slot EDR packet
393 };
394 static const uint16_t packet_type_feature_packet_mask[] = {
395     0x0f00, // 3 slot packets
396     0xf000, // 5 slot packets
397     0x1102, // EDR 2 mpbs
398     0x2204, // EDR 3 mbps
399     0x0300, // 3 slot EDR packts
400     0x3000, // 5 slot EDR packet
401 };
402 
403 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
404     // enable packet types based on size
405     uint16_t packet_types = 0;
406     int i;
407     for (i=0;i<16;i++){
408         if (packet_type_sizes[i] == 0) continue;
409         if (packet_type_sizes[i] <= buffer_size){
410             packet_types |= 1 << i;
411         }
412     }
413     // disable packet types due to missing local supported features
414     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
415         int bit_idx = packet_type_feature_requirement_bit[i];
416         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
417         if (feature_set) continue;
418         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
419         packet_types &= ~packet_type_feature_packet_mask[i];
420     }
421     // flip bits for "may not be used"
422     packet_types ^= 0x3306;
423     return packet_types;
424 }
425 
426 uint16_t hci_usable_acl_packet_types(void){
427     return hci_stack.packet_types;
428 }
429 
430 uint8_t* hci_get_outgoing_acl_packet_buffer(void){
431     // hci packet buffer is >= acl data packet length
432     return hci_stack.hci_packet_buffer;
433 }
434 
435 uint16_t hci_max_acl_data_packet_length(void){
436     return hci_stack.acl_data_packet_length;
437 }
438 
439 int hci_ssp_supported(void){
440     // No 51, byte 6, bit 3
441     return (hci_stack.local_supported_features[6] & (1 << 3)) != 0;
442 }
443 
444 int hci_classic_supported(void){
445     // No 37, byte 4, bit 5, = No BR/EDR Support
446     return (hci_stack.local_supported_features[4] & (1 << 5)) == 0;
447 }
448 
449 int hci_le_supported(void){
450     // No 37, byte 4, bit 6 = LE Supported (Controller)
451 #ifdef HAVE_BLE
452     return (hci_stack.local_supported_features[4] & (1 << 6)) != 0;
453 #else
454     return 0;
455 #endif
456 }
457 
458 // get addr type and address used in advertisement packets
459 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){
460     *addr_type = hci_stack.adv_addr_type;
461     if (hci_stack.adv_addr_type){
462         memcpy(addr, hci_stack.adv_address, 6);
463     } else {
464         memcpy(addr, hci_stack.local_bd_addr, 6);
465     }
466 }
467 
468 // avoid huge local variables
469 #ifndef EMBEDDED
470 static device_name_t device_name;
471 #endif
472 static void event_handler(uint8_t *packet, int size){
473 
474     uint16_t event_length = packet[1];
475 
476     // assert packet is complete
477     if (size != event_length + 2){
478         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
479         return;
480     }
481 
482     bd_addr_t addr;
483     uint8_t link_type;
484     hci_con_handle_t handle;
485     hci_connection_t * conn;
486     int i;
487 
488     // printf("HCI:EVENT:%02x\n", packet[0]);
489 
490     switch (packet[0]) {
491 
492         case HCI_EVENT_COMMAND_COMPLETE:
493             // get num cmd packets
494             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u\n", hci_stack.num_cmd_packets, packet[2]);
495             hci_stack.num_cmd_packets = packet[2];
496 
497             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
498                 // from offset 5
499                 // status
500                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
501                 hci_stack.acl_data_packet_length = READ_BT_16(packet, 6);
502                 // ignore: SCO data packet len (8)
503                 hci_stack.total_num_acl_packets  = packet[9];
504                 // ignore: total num SCO packets
505                 if (hci_stack.state == HCI_STATE_INITIALIZING){
506                     // determine usable ACL payload size
507                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack.acl_data_packet_length){
508                         hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
509                     }
510                     log_info("hci_read_buffer_size: used size %u, count %u\n",
511                              hci_stack.acl_data_packet_length, hci_stack.total_num_acl_packets);
512                 }
513             }
514 #ifdef HAVE_BLE
515             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){
516                 hci_stack.le_data_packet_length = READ_BT_16(packet, 6);
517                 hci_stack.total_num_le_packets  = packet[8];
518                 log_info("hci_le_read_buffer_size: size %u, count %u\n", hci_stack.le_data_packet_length, hci_stack.total_num_le_packets);
519             }
520 #endif
521             // Dump local address
522             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
523                 bt_flip_addr(hci_stack.local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
524                 log_info("Local Address, Status: 0x%02x: Addr: %s\n",
525                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack.local_bd_addr));
526             }
527             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
528                 hci_emit_discoverable_enabled(hci_stack.discoverable);
529             }
530             // Note: HCI init checks
531             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
532                 memcpy(hci_stack.local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
533                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
534                     hci_stack.local_supported_features[0], hci_stack.local_supported_features[1],
535                     hci_stack.local_supported_features[2], hci_stack.local_supported_features[3],
536                     hci_stack.local_supported_features[4], hci_stack.local_supported_features[5],
537                     hci_stack.local_supported_features[6], hci_stack.local_supported_features[7]);
538 
539                 // determine usable ACL packet types based buffer size and supported features
540                 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]);
541                 log_info("packet types %04x", hci_stack.packet_types);
542 
543                 // Classic/LE
544                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
545             }
546             break;
547 
548         case HCI_EVENT_COMMAND_STATUS:
549             // get num cmd packets
550             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u\n", hci_stack.num_cmd_packets, packet[3]);
551             hci_stack.num_cmd_packets = packet[3];
552             break;
553 
554         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
555             for (i=0; i<packet[2];i++){
556                 handle = READ_BT_16(packet, 3 + 2*i);
557                 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i);
558                 conn = hci_connection_for_handle(handle);
559                 if (!conn){
560                     log_error("hci_number_completed_packet lists unused con handle %u\n", handle);
561                     continue;
562                 }
563                 conn->num_acl_packets_sent -= num_packets;
564                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent);
565             }
566             break;
567 
568         case HCI_EVENT_CONNECTION_REQUEST:
569             bt_flip_addr(addr, &packet[2]);
570             // TODO: eval COD 8-10
571             link_type = packet[11];
572             log_info("Connection_incoming: %s, type %u\n", bd_addr_to_str(addr), link_type);
573             if (link_type == 1) { // ACL
574                 conn = connection_for_address(addr);
575                 if (!conn) {
576                     conn = create_connection_for_addr(addr);
577                 }
578                 if (!conn) {
579                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
580                     hci_stack.decline_reason = 0x0d;
581                     BD_ADDR_COPY(hci_stack.decline_addr, addr);
582                     break;
583                 }
584                 conn->state = RECEIVED_CONNECTION_REQUEST;
585                 hci_run();
586             } else {
587                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
588                 hci_stack.decline_reason = 0x0a;
589                 BD_ADDR_COPY(hci_stack.decline_addr, addr);
590             }
591             break;
592 
593         case HCI_EVENT_CONNECTION_COMPLETE:
594             // Connection management
595             bt_flip_addr(addr, &packet[5]);
596             log_info("Connection_complete (status=%u) %s\n", packet[2], bd_addr_to_str(addr));
597             conn = connection_for_address(addr);
598             if (conn) {
599                 if (!packet[2]){
600                     conn->state = OPEN;
601                     conn->con_handle = READ_BT_16(packet, 3);
602 
603                     // restart timer
604                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
605                     run_loop_add_timer(&conn->timeout);
606 
607                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
608 
609                     hci_emit_nr_connections_changed();
610                 } else {
611                     // connection failed, remove entry
612                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
613                     btstack_memory_hci_connection_free( conn );
614 
615                     // if authentication error, also delete link key
616                     if (packet[2] == 0x05) {
617                         hci_drop_link_key_for_bd_addr(&addr);
618                     }
619                 }
620             }
621             break;
622 
623         case HCI_EVENT_LINK_KEY_REQUEST:
624             log_info("HCI_EVENT_LINK_KEY_REQUEST\n");
625             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
626             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
627             if (hci_stack.bondable && !hci_stack.remote_device_db) break;
628             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
629             hci_run();
630             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
631             return;
632 
633         case HCI_EVENT_LINK_KEY_NOTIFICATION:
634             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_NOTIFICATION);
635             if (!hci_stack.remote_device_db) break;
636             bt_flip_addr(addr, &packet[2]);
637             hci_stack.remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8]);
638             // still forward event to allow dismiss of pairing dialog
639             break;
640 
641         case HCI_EVENT_PIN_CODE_REQUEST:
642             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_PIN_CODE_REQUEST);
643             // non-bondable mode: pin code negative reply will be sent
644             if (!hci_stack.bondable){
645                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_PIN_CODE_REQUEST);
646                 break;
647             }
648             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
649             if (!hci_stack.remote_device_db) break;
650             bt_flip_addr(addr, &packet[2]);
651             hci_stack.remote_device_db->delete_link_key(&addr);
652             break;
653 
654         case HCI_EVENT_IO_CAPABILITY_REQUEST:
655             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
656             if (hci_stack.ssp_io_capability == SSP_IO_CAPABILITY_UNKNOWN) break;
657             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
658             break;
659 
660         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
661             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_USER_CONFIRM_REQUEST);
662             if (!hci_stack.ssp_auto_accept) break;
663             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
664             break;
665 
666         case HCI_EVENT_USER_PASSKEY_REQUEST:
667             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_USER_PASSKEY_REQUEST);
668             if (!hci_stack.ssp_auto_accept) break;
669             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
670             break;
671 
672 #ifndef EMBEDDED
673         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
674             if (!hci_stack.remote_device_db) break;
675             if (packet[2]) break; // status not ok
676             bt_flip_addr(addr, &packet[3]);
677             // fix for invalid remote names - terminate on 0xff
678             for (i=0; i<248;i++){
679                 if (packet[9+i] == 0xff){
680                     packet[9+i] = 0;
681                     break;
682                 }
683             }
684             memset(&device_name, 0, sizeof(device_name_t));
685             strncpy((char*) device_name, (char*) &packet[9], 248);
686             hci_stack.remote_device_db->put_name(&addr, &device_name);
687             break;
688 
689         case HCI_EVENT_INQUIRY_RESULT:
690         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
691             if (!hci_stack.remote_device_db) break;
692             // first send inq result packet
693             hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
694             // then send cached remote names
695             for (i=0; i<packet[2];i++){
696                 bt_flip_addr(addr, &packet[3+i*6]);
697                 if (hci_stack.remote_device_db->get_name(&addr, &device_name)){
698                     hci_emit_remote_name_cached(&addr, &device_name);
699                 }
700             }
701             return;
702 #endif
703 
704         case HCI_EVENT_DISCONNECTION_COMPLETE:
705             if (!packet[2]){
706                 handle = READ_BT_16(packet, 3);
707                 hci_connection_t * conn = hci_connection_for_handle(handle);
708                 if (conn) {
709                     hci_shutdown_connection(conn);
710                 }
711             }
712             break;
713 
714         case HCI_EVENT_HARDWARE_ERROR:
715             if(hci_stack.control && hci_stack.control->hw_error){
716                 (*hci_stack.control->hw_error)();
717             }
718             break;
719 
720 #ifdef HAVE_BLE
721         case HCI_EVENT_LE_META:
722             switch (packet[2]) {
723                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
724                     // Connection management
725                     bt_flip_addr(addr, &packet[8]);
726                     log_info("LE Connection_complete (status=%u) %s\n", packet[3], bd_addr_to_str(addr));
727                     // LE connections are auto-accepted, so just create a connection if there isn't one already
728                     conn = connection_for_address(addr);
729                     if (packet[3]){
730                         if (conn){
731                             // outgoing connection failed, remove entry
732                             linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
733                             btstack_memory_hci_connection_free( conn );
734 
735                         }
736                         // if authentication error, also delete link key
737                         if (packet[3] == 0x05) {
738                             hci_drop_link_key_for_bd_addr(&addr);
739                         }
740                         break;
741                     }
742                     if (!conn){
743                         conn = create_connection_for_addr(addr);
744                     }
745                     if (!conn){
746                         // no memory
747                         break;
748                     }
749 
750                     conn->state = OPEN;
751                     conn->con_handle = READ_BT_16(packet, 4);
752 
753                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
754 
755                     // restart timer
756                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
757                     // run_loop_add_timer(&conn->timeout);
758 
759                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
760 
761                     hci_emit_nr_connections_changed();
762                     break;
763 
764             // printf("LE buffer size: %u, count %u\n", READ_BT_16(packet,6), packet[8]);
765 
766                 default:
767                     break;
768             }
769             break;
770 #endif
771 
772         default:
773             break;
774     }
775 
776     // handle BT initialization
777     if (hci_stack.state == HCI_STATE_INITIALIZING){
778         if (hci_stack.substate % 2){
779             // odd: waiting for event
780             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){
781                 // wait for explicit COMMAND COMPLETE on RESET
782                 if (hci_stack.substate > 1 || COMMAND_COMPLETE_EVENT(packet, hci_reset)) {
783                     hci_stack.substate++;
784                 }
785             }
786         }
787     }
788 
789     // help with BT sleep
790     if (hci_stack.state == HCI_STATE_FALLING_ASLEEP
791         && hci_stack.substate == 1
792         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
793         hci_stack.substate++;
794     }
795 
796     hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
797 
798 	// execute main loop
799 	hci_run();
800 }
801 
802 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
803     switch (packet_type) {
804         case HCI_EVENT_PACKET:
805             event_handler(packet, size);
806             break;
807         case HCI_ACL_DATA_PACKET:
808             acl_handler(packet, size);
809             break;
810         default:
811             break;
812     }
813 }
814 
815 /** Register HCI packet handlers */
816 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
817     hci_stack.packet_handler = handler;
818 }
819 
820 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
821 
822     // reference to use transport layer implementation
823     hci_stack.hci_transport = transport;
824 
825     // references to used control implementation
826     hci_stack.control = control;
827 
828     // reference to used config
829     hci_stack.config = config;
830 
831     // no connections yet
832     hci_stack.connections = NULL;
833     hci_stack.discoverable = 0;
834     hci_stack.connectable = 0;
835     hci_stack.bondable = 1;
836 
837     // no pending cmds
838     hci_stack.decline_reason = 0;
839     hci_stack.new_scan_enable_value = 0xff;
840 
841     // higher level handler
842     hci_stack.packet_handler = dummy_handler;
843 
844     // store and open remote device db
845     hci_stack.remote_device_db = remote_device_db;
846     if (hci_stack.remote_device_db) {
847         hci_stack.remote_device_db->open();
848     }
849 
850     // max acl payload size defined in config.h
851     hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
852 
853     // register packet handlers with transport
854     transport->register_packet_handler(&packet_handler);
855 
856     hci_stack.state = HCI_STATE_OFF;
857 
858     // class of device
859     hci_stack.class_of_device = 0x007a020c; // Smartphone
860 
861     // Secure Simple Pairing default: enable, no I/O capabilities, auto accept
862     hci_stack.ssp_enable = 1;
863     hci_stack.ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
864     hci_stack.ssp_authentication_requirement = 0;
865     hci_stack.ssp_auto_accept = 1;
866 
867     // LE
868     hci_stack.adv_addr_type = 0;
869     memset(hci_stack.adv_address, 0, 6);
870 }
871 
872 void hci_close(){
873     // close remote device db
874     if (hci_stack.remote_device_db) {
875         hci_stack.remote_device_db->close();
876     }
877     while (hci_stack.connections) {
878         hci_shutdown_connection((hci_connection_t *) hci_stack.connections);
879 }
880     hci_power_control(HCI_POWER_OFF);
881 }
882 
883 // State-Module-Driver overview
884 // state                    module  low-level
885 // HCI_STATE_OFF             off      close
886 // HCI_STATE_INITIALIZING,   on       open
887 // HCI_STATE_WORKING,        on       open
888 // HCI_STATE_HALTING,        on       open
889 // HCI_STATE_SLEEPING,    off/sleep   close
890 // HCI_STATE_FALLING_ASLEEP  on       open
891 
892 static int hci_power_control_on(void){
893 
894     // power on
895     int err = 0;
896     if (hci_stack.control && hci_stack.control->on){
897         err = (*hci_stack.control->on)(hci_stack.config);
898     }
899     if (err){
900         log_error( "POWER_ON failed\n");
901         hci_emit_hci_open_failed();
902         return err;
903     }
904 
905     // open low-level device
906     err = hci_stack.hci_transport->open(hci_stack.config);
907     if (err){
908         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
909         if (hci_stack.control && hci_stack.control->off){
910             (*hci_stack.control->off)(hci_stack.config);
911         }
912         hci_emit_hci_open_failed();
913         return err;
914     }
915     return 0;
916 }
917 
918 static void hci_power_control_off(void){
919 
920     log_info("hci_power_control_off\n");
921 
922     // close low-level device
923     hci_stack.hci_transport->close(hci_stack.config);
924 
925     log_info("hci_power_control_off - hci_transport closed\n");
926 
927     // power off
928     if (hci_stack.control && hci_stack.control->off){
929         (*hci_stack.control->off)(hci_stack.config);
930     }
931 
932     log_info("hci_power_control_off - control closed\n");
933 
934     hci_stack.state = HCI_STATE_OFF;
935 }
936 
937 static void hci_power_control_sleep(void){
938 
939     log_info("hci_power_control_sleep\n");
940 
941 #if 0
942     // don't close serial port during sleep
943 
944     // close low-level device
945     hci_stack.hci_transport->close(hci_stack.config);
946 #endif
947 
948     // sleep mode
949     if (hci_stack.control && hci_stack.control->sleep){
950         (*hci_stack.control->sleep)(hci_stack.config);
951     }
952 
953     hci_stack.state = HCI_STATE_SLEEPING;
954 }
955 
956 static int hci_power_control_wake(void){
957 
958     log_info("hci_power_control_wake\n");
959 
960     // wake on
961     if (hci_stack.control && hci_stack.control->wake){
962         (*hci_stack.control->wake)(hci_stack.config);
963     }
964 
965 #if 0
966     // open low-level device
967     int err = hci_stack.hci_transport->open(hci_stack.config);
968     if (err){
969         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
970         if (hci_stack.control && hci_stack.control->off){
971             (*hci_stack.control->off)(hci_stack.config);
972         }
973         hci_emit_hci_open_failed();
974         return err;
975     }
976 #endif
977 
978     return 0;
979 }
980 
981 
982 int hci_power_control(HCI_POWER_MODE power_mode){
983 
984     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state);
985 
986     int err = 0;
987     switch (hci_stack.state){
988 
989         case HCI_STATE_OFF:
990             switch (power_mode){
991                 case HCI_POWER_ON:
992                     err = hci_power_control_on();
993                     if (err) return err;
994                     // set up state machine
995                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
996                     hci_stack.state = HCI_STATE_INITIALIZING;
997                     hci_stack.substate = 0;
998                     break;
999                 case HCI_POWER_OFF:
1000                     // do nothing
1001                     break;
1002                 case HCI_POWER_SLEEP:
1003                     // do nothing (with SLEEP == OFF)
1004                     break;
1005             }
1006             break;
1007 
1008         case HCI_STATE_INITIALIZING:
1009             switch (power_mode){
1010                 case HCI_POWER_ON:
1011                     // do nothing
1012                     break;
1013                 case HCI_POWER_OFF:
1014                     // no connections yet, just turn it off
1015                     hci_power_control_off();
1016                     break;
1017                 case HCI_POWER_SLEEP:
1018                     // no connections yet, just turn it off
1019                     hci_power_control_sleep();
1020                     break;
1021             }
1022             break;
1023 
1024         case HCI_STATE_WORKING:
1025             switch (power_mode){
1026                 case HCI_POWER_ON:
1027                     // do nothing
1028                     break;
1029                 case HCI_POWER_OFF:
1030                     // see hci_run
1031                     hci_stack.state = HCI_STATE_HALTING;
1032                     break;
1033                 case HCI_POWER_SLEEP:
1034                     // see hci_run
1035                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
1036                     hci_stack.substate = 0;
1037                     break;
1038             }
1039             break;
1040 
1041         case HCI_STATE_HALTING:
1042             switch (power_mode){
1043                 case HCI_POWER_ON:
1044                     // set up state machine
1045                     hci_stack.state = HCI_STATE_INITIALIZING;
1046                     hci_stack.substate = 0;
1047                     break;
1048                 case HCI_POWER_OFF:
1049                     // do nothing
1050                     break;
1051                 case HCI_POWER_SLEEP:
1052                     // see hci_run
1053                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
1054                     hci_stack.substate = 0;
1055                     break;
1056             }
1057             break;
1058 
1059         case HCI_STATE_FALLING_ASLEEP:
1060             switch (power_mode){
1061                 case HCI_POWER_ON:
1062 
1063 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1064                     // nothing to do, if H4 supports power management
1065                     if (bt_control_iphone_power_management_enabled()){
1066                         hci_stack.state = HCI_STATE_INITIALIZING;
1067                         hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1068                         break;
1069                     }
1070 #endif
1071                     // set up state machine
1072                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1073                     hci_stack.state = HCI_STATE_INITIALIZING;
1074                     hci_stack.substate = 0;
1075                     break;
1076                 case HCI_POWER_OFF:
1077                     // see hci_run
1078                     hci_stack.state = HCI_STATE_HALTING;
1079                     break;
1080                 case HCI_POWER_SLEEP:
1081                     // do nothing
1082                     break;
1083             }
1084             break;
1085 
1086         case HCI_STATE_SLEEPING:
1087             switch (power_mode){
1088                 case HCI_POWER_ON:
1089 
1090 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1091                     // nothing to do, if H4 supports power management
1092                     if (bt_control_iphone_power_management_enabled()){
1093                         hci_stack.state = HCI_STATE_INITIALIZING;
1094                         hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1095                         hci_update_scan_enable();
1096                         break;
1097                     }
1098 #endif
1099                     err = hci_power_control_wake();
1100                     if (err) return err;
1101                     // set up state machine
1102                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1103                     hci_stack.state = HCI_STATE_INITIALIZING;
1104                     hci_stack.substate = 0;
1105                     break;
1106                 case HCI_POWER_OFF:
1107                     hci_stack.state = HCI_STATE_HALTING;
1108                     break;
1109                 case HCI_POWER_SLEEP:
1110                     // do nothing
1111                     break;
1112             }
1113             break;
1114     }
1115 
1116     // create internal event
1117 	hci_emit_state();
1118 
1119 	// trigger next/first action
1120 	hci_run();
1121 
1122     return 0;
1123 }
1124 
1125 static void hci_update_scan_enable(void){
1126     // 2 = page scan, 1 = inq scan
1127     hci_stack.new_scan_enable_value  = hci_stack.connectable << 1 | hci_stack.discoverable;
1128     hci_run();
1129 }
1130 
1131 void hci_discoverable_control(uint8_t enable){
1132     if (enable) enable = 1; // normalize argument
1133 
1134     if (hci_stack.discoverable == enable){
1135         hci_emit_discoverable_enabled(hci_stack.discoverable);
1136         return;
1137     }
1138 
1139     hci_stack.discoverable = enable;
1140     hci_update_scan_enable();
1141 }
1142 
1143 void hci_connectable_control(uint8_t enable){
1144     if (enable) enable = 1; // normalize argument
1145 
1146     // don't emit event
1147     if (hci_stack.connectable == enable) return;
1148 
1149     hci_stack.connectable = enable;
1150     hci_update_scan_enable();
1151 }
1152 
1153 bd_addr_t * hci_local_bd_addr(void){
1154     return &hci_stack.local_bd_addr;
1155 }
1156 
1157 void hci_run(){
1158 
1159     hci_connection_t * connection;
1160     linked_item_t * it;
1161 
1162     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1163 
1164     // global/non-connection oriented commands
1165 
1166     // decline incoming connections
1167     if (hci_stack.decline_reason){
1168         uint8_t reason = hci_stack.decline_reason;
1169         hci_stack.decline_reason = 0;
1170         hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason);
1171         return;
1172     }
1173 
1174     // send scan enable
1175     if (hci_stack.state == HCI_STATE_WORKING && hci_stack.new_scan_enable_value != 0xff && hci_classic_supported()){
1176         hci_send_cmd(&hci_write_scan_enable, hci_stack.new_scan_enable_value);
1177         hci_stack.new_scan_enable_value = 0xff;
1178         return;
1179     }
1180 
1181     // send pending HCI commands
1182     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
1183 
1184         connection = (hci_connection_t *) it;
1185 
1186         if (connection->state == RECEIVED_CONNECTION_REQUEST){
1187             log_info("sending hci_accept_connection_request\n");
1188             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1189             connection->state = ACCEPTED_CONNECTION_REQUEST;
1190             return;
1191         }
1192 
1193         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1194             link_key_t link_key;
1195             log_info("responding to link key request\n");
1196             if ( hci_stack.bondable && hci_stack.remote_device_db && hci_stack.remote_device_db->get_link_key( &connection->address, &link_key)){
1197                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1198             } else {
1199                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1200             }
1201             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1202             return;
1203         }
1204 
1205         if (connection->authentication_flags & HANDLE_PIN_CODE_REQUEST){
1206             log_info("denying to pin request\n");
1207             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1208             connectionClearAuthenticationFlags(connection, HANDLE_PIN_CODE_REQUEST);
1209             return;
1210         }
1211 
1212         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1213             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack.ssp_io_capability, NULL, hci_stack.ssp_authentication_requirement);
1214             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1215             return;
1216         }
1217 
1218         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1219             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1220             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1221             return;
1222         }
1223 
1224         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1225             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1226             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1227             return;
1228         }
1229     }
1230 
1231     switch (hci_stack.state){
1232         case HCI_STATE_INITIALIZING:
1233             // log_info("hci_init: substate %u\n", hci_stack.substate);
1234             if (hci_stack.substate % 2) {
1235                 // odd: waiting for command completion
1236                 return;
1237             }
1238             switch (hci_stack.substate >> 1){
1239                 case 0: // RESET
1240                     hci_send_cmd(&hci_reset);
1241 
1242                     if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){
1243                         // skip baud change
1244                         hci_stack.substate = 4; // >> 1 = 2
1245                     }
1246                     break;
1247                 case 1: // SEND BAUD CHANGE
1248                     hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_packet_buffer);
1249                     hci_send_cmd_packet(hci_stack.hci_packet_buffer, 3 + hci_stack.hci_packet_buffer[2]);
1250                     break;
1251                 case 2: // LOCAL BAUD CHANGE
1252                     hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main);
1253                     hci_stack.substate += 2;
1254                     // break missing here for fall through
1255 
1256                 case 3:
1257                     // Custom initialization
1258                     if (hci_stack.control && hci_stack.control->next_cmd){
1259                         int valid_cmd = (*hci_stack.control->next_cmd)(hci_stack.config, hci_stack.hci_packet_buffer);
1260                         if (valid_cmd){
1261                             int size = 3 + hci_stack.hci_packet_buffer[2];
1262                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack.hci_packet_buffer, size);
1263                             hci_stack.substate = 4; // more init commands
1264                             break;
1265                         }
1266                         log_info("hci_run: init script done\n\r");
1267                     }
1268                     // otherwise continue
1269 					hci_send_cmd(&hci_read_bd_addr);
1270 					break;
1271 				case 4:
1272 					hci_send_cmd(&hci_read_buffer_size);
1273 					break;
1274                 case 5:
1275                     hci_send_cmd(&hci_read_local_supported_features);
1276                     break;
1277                 case 6:
1278                     if (hci_le_supported()){
1279                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1280                     } else {
1281                         // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1282                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1283                     }
1284 
1285                     // skip Classic init commands for LE only chipsets
1286                     if (!hci_classic_supported()){
1287                         if (hci_le_supported()){
1288                             hci_stack.substate = 11 << 1;    // skip all classic command
1289                         } else {
1290                             log_error("Neither BR/EDR nor LE supported");
1291                             hci_stack.substate = 13 << 1;    // skip all
1292                         }
1293                     }
1294                     break;
1295                 case 7:
1296                     if (hci_ssp_supported()){
1297                         hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack.ssp_enable);
1298                         break;
1299                     }
1300                     hci_stack.substate += 2;
1301                     // break missing here for fall through
1302 
1303                 case 8:
1304                     // ca. 15 sec
1305                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1306                     break;
1307                 case 9:
1308                     hci_send_cmd(&hci_write_class_of_device, hci_stack.class_of_device);
1309                     break;
1310                 case 10:
1311                     if (hci_stack.local_name){
1312                         hci_send_cmd(&hci_write_local_name, hci_stack.local_name);
1313                     } else {
1314                         char hostname[30];
1315 #ifdef EMBEDDED
1316                         // BTstack-11:22:33:44:55:66
1317                         strcpy(hostname, "BTstack ");
1318                         strcat(hostname, bd_addr_to_str(hci_stack.local_bd_addr));
1319                         printf("---> Name %s\n", hostname);
1320 #else
1321                         // hostname for POSIX systems
1322                         gethostname(hostname, 30);
1323                         hostname[29] = '\0';
1324 #endif
1325                         hci_send_cmd(&hci_write_local_name, hostname);
1326                     }
1327                     break;
1328                 case 11:
1329 					hci_send_cmd(&hci_write_scan_enable, (hci_stack.connectable << 1) | hci_stack.discoverable); // page scan
1330                     if (!hci_le_supported()){
1331                         // SKIP LE init for Classic only configuration
1332                         hci_stack.substate = 13 << 1;
1333                     }
1334 					break;
1335 
1336 #ifdef HAVE_BLE
1337                 // LE INIT
1338                 case 12:
1339                     hci_send_cmd(&hci_le_read_buffer_size);
1340                     break;
1341                 case 13:
1342                     // LE Supported Host = 1, Simultaneous Host = 0
1343                     hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1344                     break;
1345 #endif
1346 
1347                 // DONE
1348                 case 14:
1349                     // done.
1350                     hci_stack.state = HCI_STATE_WORKING;
1351                     hci_emit_state();
1352                     break;
1353                 default:
1354                     break;
1355             }
1356             hci_stack.substate++;
1357             break;
1358 
1359         case HCI_STATE_HALTING:
1360 
1361             log_info("HCI_STATE_HALTING\n");
1362             // close all open connections
1363             connection =  (hci_connection_t *) hci_stack.connections;
1364             if (connection){
1365 
1366                 // send disconnect
1367                 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1368 
1369                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1370                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1371 
1372                 // send disconnected event right away - causes higher layer connections to get closed, too.
1373                 hci_shutdown_connection(connection);
1374                 return;
1375             }
1376             log_info("HCI_STATE_HALTING, calling off\n");
1377 
1378             // switch mode
1379             hci_power_control_off();
1380 
1381             log_info("HCI_STATE_HALTING, emitting state\n");
1382             hci_emit_state();
1383             log_info("HCI_STATE_HALTING, done\n");
1384             break;
1385 
1386         case HCI_STATE_FALLING_ASLEEP:
1387             switch(hci_stack.substate) {
1388                 case 0:
1389                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1390                     // close all open connections
1391                     connection =  (hci_connection_t *) hci_stack.connections;
1392 
1393 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1394                     // don't close connections, if H4 supports power management
1395                     if (bt_control_iphone_power_management_enabled()){
1396                         connection = NULL;
1397                     }
1398 #endif
1399                     if (connection){
1400 
1401                         // send disconnect
1402                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1403 
1404                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1405                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1406 
1407                         // send disconnected event right away - causes higher layer connections to get closed, too.
1408                         hci_shutdown_connection(connection);
1409                         return;
1410                     }
1411 
1412                     if (hci_classic_supported()){
1413                         // disable page and inquiry scan
1414                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1415 
1416                         log_info("HCI_STATE_HALTING, disabling inq scans\n");
1417                         hci_send_cmd(&hci_write_scan_enable, hci_stack.connectable << 1); // drop inquiry scan but keep page scan
1418 
1419                         // continue in next sub state
1420                         hci_stack.substate++;
1421                         break;
1422                     }
1423                     // fall through for ble-only chips
1424 
1425                 case 2:
1426                     log_info("HCI_STATE_HALTING, calling sleep\n");
1427 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1428                     // don't actually go to sleep, if H4 supports power management
1429                     if (bt_control_iphone_power_management_enabled()){
1430                         // SLEEP MODE reached
1431                         hci_stack.state = HCI_STATE_SLEEPING;
1432                         hci_emit_state();
1433                         break;
1434                     }
1435 #endif
1436                     // switch mode
1437                     hci_power_control_sleep();  // changes hci_stack.state to SLEEP
1438                     hci_emit_state();
1439                     break;
1440 
1441                 default:
1442                     break;
1443             }
1444             break;
1445 
1446         default:
1447             break;
1448     }
1449 }
1450 
1451 int hci_send_cmd_packet(uint8_t *packet, int size){
1452     bd_addr_t addr;
1453     hci_connection_t * conn;
1454     // house-keeping
1455 
1456     // create_connection?
1457     if (IS_COMMAND(packet, hci_create_connection)){
1458         bt_flip_addr(addr, &packet[3]);
1459         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1460         conn = connection_for_address(addr);
1461         if (conn) {
1462             // if connection exists
1463             if (conn->state == OPEN) {
1464                 // and OPEN, emit connection complete command
1465                 hci_emit_connection_complete(conn, 0);
1466             }
1467             //    otherwise, just ignore as it is already in the open process
1468             return 0; // don't sent packet to controller
1469 
1470         }
1471         // create connection struct and register, state = SENT_CREATE_CONNECTION
1472         conn = create_connection_for_addr(addr);
1473         if (!conn){
1474             // notify client that alloc failed
1475             hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1476             return 0; // don't sent packet to controller
1477         }
1478         conn->state = SENT_CREATE_CONNECTION;
1479     }
1480 
1481     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1482         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1483     }
1484     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1485         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1486     }
1487     if (IS_COMMAND(packet, hci_pin_code_request_reply)){
1488         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY);
1489     }
1490     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){
1491         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY);
1492     }
1493 
1494     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1495         if (hci_stack.remote_device_db){
1496             bt_flip_addr(addr, &packet[3]);
1497             hci_stack.remote_device_db->delete_link_key(&addr);
1498         }
1499     }
1500 
1501 #ifdef HAVE_BLE
1502     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
1503         hci_stack.adv_addr_type = packet[8];
1504     }
1505     if (IS_COMMAND(packet, hci_le_set_random_address)){
1506         bt_flip_addr(hci_stack.adv_address, &packet[3]);
1507     }
1508 #endif
1509 
1510 
1511     hci_stack.num_cmd_packets--;
1512     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1513 }
1514 
1515 // Configure Secure Simple Pairing
1516 
1517 // enable will enable SSP during init
1518 void hci_ssp_set_enable(int enable){
1519     hci_stack.ssp_enable = enable;
1520 }
1521 
1522 // if set, BTstack will respond to io capability request using authentication requirement
1523 void hci_ssp_set_io_capability(int io_capability){
1524     hci_stack.ssp_io_capability = io_capability;
1525 }
1526 void hci_ssp_set_authentication_requirement(int authentication_requirement){
1527     hci_stack.ssp_authentication_requirement = authentication_requirement;
1528 }
1529 
1530 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
1531 void hci_ssp_set_auto_accept(int auto_accept){
1532     hci_stack.ssp_auto_accept = auto_accept;
1533 }
1534 
1535 /**
1536  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1537  */
1538 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1539     va_list argptr;
1540     va_start(argptr, cmd);
1541     uint16_t size = hci_create_cmd_internal(hci_stack.hci_packet_buffer, cmd, argptr);
1542     va_end(argptr);
1543     return hci_send_cmd_packet(hci_stack.hci_packet_buffer, size);
1544 }
1545 
1546 // Create various non-HCI events.
1547 // TODO: generalize, use table similar to hci_create_command
1548 
1549 void hci_emit_state(){
1550     log_info("BTSTACK_EVENT_STATE %u", hci_stack.state);
1551     uint8_t event[3];
1552     event[0] = BTSTACK_EVENT_STATE;
1553     event[1] = sizeof(event) - 2;
1554     event[2] = hci_stack.state;
1555     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1556     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1557 }
1558 
1559 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1560     uint8_t event[13];
1561     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1562     event[1] = sizeof(event) - 2;
1563     event[2] = status;
1564     bt_store_16(event, 3, conn->con_handle);
1565     bt_flip_addr(&event[5], conn->address);
1566     event[11] = 1; // ACL connection
1567     event[12] = 0; // encryption disabled
1568     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1569     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1570 }
1571 
1572 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1573     uint8_t event[6];
1574     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1575     event[1] = sizeof(event) - 2;
1576     event[2] = 0; // status = OK
1577     bt_store_16(event, 3, handle);
1578     event[5] = reason;
1579     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1580     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1581 }
1582 
1583 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1584     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
1585     uint8_t event[4];
1586     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1587     event[1] = sizeof(event) - 2;
1588     bt_store_16(event, 2, conn->con_handle);
1589     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1590     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1591 }
1592 
1593 void hci_emit_nr_connections_changed(){
1594     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
1595     uint8_t event[3];
1596     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1597     event[1] = sizeof(event) - 2;
1598     event[2] = nr_hci_connections();
1599     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1600     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1601 }
1602 
1603 void hci_emit_hci_open_failed(){
1604     log_info("BTSTACK_EVENT_POWERON_FAILED");
1605     uint8_t event[2];
1606     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1607     event[1] = sizeof(event) - 2;
1608     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1609     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1610 }
1611 
1612 #ifndef EMBEDDED
1613 void hci_emit_btstack_version() {
1614     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
1615     uint8_t event[6];
1616     event[0] = BTSTACK_EVENT_VERSION;
1617     event[1] = sizeof(event) - 2;
1618     event[2] = BTSTACK_MAJOR;
1619     event[3] = BTSTACK_MINOR;
1620     bt_store_16(event, 4, BTSTACK_REVISION);
1621     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1622     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1623 }
1624 #endif
1625 
1626 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1627     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
1628     uint8_t event[3];
1629     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1630     event[1] = sizeof(event) - 2;
1631     event[2] = enabled;
1632     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1633     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1634 }
1635 
1636 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1637     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
1638     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1639     event[1] = sizeof(event) - 2 - 1;
1640     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1641     bt_flip_addr(&event[3], *addr);
1642     memcpy(&event[9], name, 248);
1643 
1644     event[9+248] = 0;   // assert \0 for log_info
1645     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
1646 
1647     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
1648     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
1649 }
1650 
1651 void hci_emit_discoverable_enabled(uint8_t enabled){
1652     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
1653     uint8_t event[3];
1654     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1655     event[1] = sizeof(event) - 2;
1656     event[2] = enabled;
1657     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1658     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1659 }
1660 
1661 // GAP API
1662 /**
1663  * @bbrief enable/disable bonding. default is enabled
1664  * @praram enabled
1665  */
1666 void gap_set_bondable_mode(int enable){
1667     hci_stack.bondable = enable ? 1 : 0;
1668 }
1669