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