xref: /btstack/src/hci.c (revision f8fb5f6e47847f304b108bb98e6cb38f0e33ea67)
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                 hci_run();
647                 return;
648             }
649             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
650             if (!hci_stack.remote_device_db) break;
651             bt_flip_addr(addr, &packet[2]);
652             hci_stack.remote_device_db->delete_link_key(&addr);
653             break;
654 
655         case HCI_EVENT_IO_CAPABILITY_REQUEST:
656             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
657             if (!hci_stack.bondable || hci_stack.ssp_io_capability == SSP_IO_CAPABILITY_UNKNOWN) break;
658             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
659             break;
660 
661         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
662             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_USER_CONFIRM_REQUEST);
663             if (!hci_stack.ssp_auto_accept) break;
664             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
665             break;
666 
667         case HCI_EVENT_USER_PASSKEY_REQUEST:
668             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_USER_PASSKEY_REQUEST);
669             if (!hci_stack.ssp_auto_accept) break;
670             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
671             break;
672 
673 #ifndef EMBEDDED
674         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
675             if (!hci_stack.remote_device_db) break;
676             if (packet[2]) break; // status not ok
677             bt_flip_addr(addr, &packet[3]);
678             // fix for invalid remote names - terminate on 0xff
679             for (i=0; i<248;i++){
680                 if (packet[9+i] == 0xff){
681                     packet[9+i] = 0;
682                     break;
683                 }
684             }
685             memset(&device_name, 0, sizeof(device_name_t));
686             strncpy((char*) device_name, (char*) &packet[9], 248);
687             hci_stack.remote_device_db->put_name(&addr, &device_name);
688             break;
689 
690         case HCI_EVENT_INQUIRY_RESULT:
691         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
692             if (!hci_stack.remote_device_db) break;
693             // first send inq result packet
694             hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
695             // then send cached remote names
696             for (i=0; i<packet[2];i++){
697                 bt_flip_addr(addr, &packet[3+i*6]);
698                 if (hci_stack.remote_device_db->get_name(&addr, &device_name)){
699                     hci_emit_remote_name_cached(&addr, &device_name);
700                 }
701             }
702             return;
703 #endif
704 
705         case HCI_EVENT_DISCONNECTION_COMPLETE:
706             if (!packet[2]){
707                 handle = READ_BT_16(packet, 3);
708                 hci_connection_t * conn = hci_connection_for_handle(handle);
709                 if (conn) {
710                     hci_shutdown_connection(conn);
711                 }
712             }
713             break;
714 
715         case HCI_EVENT_HARDWARE_ERROR:
716             if(hci_stack.control && hci_stack.control->hw_error){
717                 (*hci_stack.control->hw_error)();
718             }
719             break;
720 
721 #ifdef HAVE_BLE
722         case HCI_EVENT_LE_META:
723             switch (packet[2]) {
724                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
725                     // Connection management
726                     bt_flip_addr(addr, &packet[8]);
727                     log_info("LE Connection_complete (status=%u) %s\n", packet[3], bd_addr_to_str(addr));
728                     // LE connections are auto-accepted, so just create a connection if there isn't one already
729                     conn = connection_for_address(addr);
730                     if (packet[3]){
731                         if (conn){
732                             // outgoing connection failed, remove entry
733                             linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
734                             btstack_memory_hci_connection_free( conn );
735 
736                         }
737                         // if authentication error, also delete link key
738                         if (packet[3] == 0x05) {
739                             hci_drop_link_key_for_bd_addr(&addr);
740                         }
741                         break;
742                     }
743                     if (!conn){
744                         conn = create_connection_for_addr(addr);
745                     }
746                     if (!conn){
747                         // no memory
748                         break;
749                     }
750 
751                     conn->state = OPEN;
752                     conn->con_handle = READ_BT_16(packet, 4);
753 
754                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
755 
756                     // restart timer
757                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
758                     // run_loop_add_timer(&conn->timeout);
759 
760                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
761 
762                     hci_emit_nr_connections_changed();
763                     break;
764 
765             // printf("LE buffer size: %u, count %u\n", READ_BT_16(packet,6), packet[8]);
766 
767                 default:
768                     break;
769             }
770             break;
771 #endif
772 
773         default:
774             break;
775     }
776 
777     // handle BT initialization
778     if (hci_stack.state == HCI_STATE_INITIALIZING){
779         if (hci_stack.substate % 2){
780             // odd: waiting for event
781             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){
782                 // wait for explicit COMMAND COMPLETE on RESET
783                 if (hci_stack.substate > 1 || COMMAND_COMPLETE_EVENT(packet, hci_reset)) {
784                     hci_stack.substate++;
785                 }
786             }
787         }
788     }
789 
790     // help with BT sleep
791     if (hci_stack.state == HCI_STATE_FALLING_ASLEEP
792         && hci_stack.substate == 1
793         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
794         hci_stack.substate++;
795     }
796 
797     hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
798 
799 	// execute main loop
800 	hci_run();
801 }
802 
803 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
804     switch (packet_type) {
805         case HCI_EVENT_PACKET:
806             event_handler(packet, size);
807             break;
808         case HCI_ACL_DATA_PACKET:
809             acl_handler(packet, size);
810             break;
811         default:
812             break;
813     }
814 }
815 
816 /** Register HCI packet handlers */
817 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
818     hci_stack.packet_handler = handler;
819 }
820 
821 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
822 
823     // reference to use transport layer implementation
824     hci_stack.hci_transport = transport;
825 
826     // references to used control implementation
827     hci_stack.control = control;
828 
829     // reference to used config
830     hci_stack.config = config;
831 
832     // no connections yet
833     hci_stack.connections = NULL;
834     hci_stack.discoverable = 0;
835     hci_stack.connectable = 0;
836     hci_stack.bondable = 1;
837 
838     // no pending cmds
839     hci_stack.decline_reason = 0;
840     hci_stack.new_scan_enable_value = 0xff;
841 
842     // higher level handler
843     hci_stack.packet_handler = dummy_handler;
844 
845     // store and open remote device db
846     hci_stack.remote_device_db = remote_device_db;
847     if (hci_stack.remote_device_db) {
848         hci_stack.remote_device_db->open();
849     }
850 
851     // max acl payload size defined in config.h
852     hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
853 
854     // register packet handlers with transport
855     transport->register_packet_handler(&packet_handler);
856 
857     hci_stack.state = HCI_STATE_OFF;
858 
859     // class of device
860     hci_stack.class_of_device = 0x007a020c; // Smartphone
861 
862     // Secure Simple Pairing default: enable, no I/O capabilities, auto accept
863     hci_stack.ssp_enable = 1;
864     hci_stack.ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
865     hci_stack.ssp_authentication_requirement = 0;
866     hci_stack.ssp_auto_accept = 1;
867 
868     // LE
869     hci_stack.adv_addr_type = 0;
870     memset(hci_stack.adv_address, 0, 6);
871 }
872 
873 void hci_close(){
874     // close remote device db
875     if (hci_stack.remote_device_db) {
876         hci_stack.remote_device_db->close();
877     }
878     while (hci_stack.connections) {
879         hci_shutdown_connection((hci_connection_t *) hci_stack.connections);
880 }
881     hci_power_control(HCI_POWER_OFF);
882 }
883 
884 // State-Module-Driver overview
885 // state                    module  low-level
886 // HCI_STATE_OFF             off      close
887 // HCI_STATE_INITIALIZING,   on       open
888 // HCI_STATE_WORKING,        on       open
889 // HCI_STATE_HALTING,        on       open
890 // HCI_STATE_SLEEPING,    off/sleep   close
891 // HCI_STATE_FALLING_ASLEEP  on       open
892 
893 static int hci_power_control_on(void){
894 
895     // power on
896     int err = 0;
897     if (hci_stack.control && hci_stack.control->on){
898         err = (*hci_stack.control->on)(hci_stack.config);
899     }
900     if (err){
901         log_error( "POWER_ON failed\n");
902         hci_emit_hci_open_failed();
903         return err;
904     }
905 
906     // open low-level device
907     err = hci_stack.hci_transport->open(hci_stack.config);
908     if (err){
909         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
910         if (hci_stack.control && hci_stack.control->off){
911             (*hci_stack.control->off)(hci_stack.config);
912         }
913         hci_emit_hci_open_failed();
914         return err;
915     }
916     return 0;
917 }
918 
919 static void hci_power_control_off(void){
920 
921     log_info("hci_power_control_off\n");
922 
923     // close low-level device
924     hci_stack.hci_transport->close(hci_stack.config);
925 
926     log_info("hci_power_control_off - hci_transport closed\n");
927 
928     // power off
929     if (hci_stack.control && hci_stack.control->off){
930         (*hci_stack.control->off)(hci_stack.config);
931     }
932 
933     log_info("hci_power_control_off - control closed\n");
934 
935     hci_stack.state = HCI_STATE_OFF;
936 }
937 
938 static void hci_power_control_sleep(void){
939 
940     log_info("hci_power_control_sleep\n");
941 
942 #if 0
943     // don't close serial port during sleep
944 
945     // close low-level device
946     hci_stack.hci_transport->close(hci_stack.config);
947 #endif
948 
949     // sleep mode
950     if (hci_stack.control && hci_stack.control->sleep){
951         (*hci_stack.control->sleep)(hci_stack.config);
952     }
953 
954     hci_stack.state = HCI_STATE_SLEEPING;
955 }
956 
957 static int hci_power_control_wake(void){
958 
959     log_info("hci_power_control_wake\n");
960 
961     // wake on
962     if (hci_stack.control && hci_stack.control->wake){
963         (*hci_stack.control->wake)(hci_stack.config);
964     }
965 
966 #if 0
967     // open low-level device
968     int err = hci_stack.hci_transport->open(hci_stack.config);
969     if (err){
970         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
971         if (hci_stack.control && hci_stack.control->off){
972             (*hci_stack.control->off)(hci_stack.config);
973         }
974         hci_emit_hci_open_failed();
975         return err;
976     }
977 #endif
978 
979     return 0;
980 }
981 
982 
983 int hci_power_control(HCI_POWER_MODE power_mode){
984 
985     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state);
986 
987     int err = 0;
988     switch (hci_stack.state){
989 
990         case HCI_STATE_OFF:
991             switch (power_mode){
992                 case HCI_POWER_ON:
993                     err = hci_power_control_on();
994                     if (err) return err;
995                     // set up state machine
996                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
997                     hci_stack.state = HCI_STATE_INITIALIZING;
998                     hci_stack.substate = 0;
999                     break;
1000                 case HCI_POWER_OFF:
1001                     // do nothing
1002                     break;
1003                 case HCI_POWER_SLEEP:
1004                     // do nothing (with SLEEP == OFF)
1005                     break;
1006             }
1007             break;
1008 
1009         case HCI_STATE_INITIALIZING:
1010             switch (power_mode){
1011                 case HCI_POWER_ON:
1012                     // do nothing
1013                     break;
1014                 case HCI_POWER_OFF:
1015                     // no connections yet, just turn it off
1016                     hci_power_control_off();
1017                     break;
1018                 case HCI_POWER_SLEEP:
1019                     // no connections yet, just turn it off
1020                     hci_power_control_sleep();
1021                     break;
1022             }
1023             break;
1024 
1025         case HCI_STATE_WORKING:
1026             switch (power_mode){
1027                 case HCI_POWER_ON:
1028                     // do nothing
1029                     break;
1030                 case HCI_POWER_OFF:
1031                     // see hci_run
1032                     hci_stack.state = HCI_STATE_HALTING;
1033                     break;
1034                 case HCI_POWER_SLEEP:
1035                     // see hci_run
1036                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
1037                     hci_stack.substate = 0;
1038                     break;
1039             }
1040             break;
1041 
1042         case HCI_STATE_HALTING:
1043             switch (power_mode){
1044                 case HCI_POWER_ON:
1045                     // set up state machine
1046                     hci_stack.state = HCI_STATE_INITIALIZING;
1047                     hci_stack.substate = 0;
1048                     break;
1049                 case HCI_POWER_OFF:
1050                     // do nothing
1051                     break;
1052                 case HCI_POWER_SLEEP:
1053                     // see hci_run
1054                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
1055                     hci_stack.substate = 0;
1056                     break;
1057             }
1058             break;
1059 
1060         case HCI_STATE_FALLING_ASLEEP:
1061             switch (power_mode){
1062                 case HCI_POWER_ON:
1063 
1064 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1065                     // nothing to do, if H4 supports power management
1066                     if (bt_control_iphone_power_management_enabled()){
1067                         hci_stack.state = HCI_STATE_INITIALIZING;
1068                         hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1069                         break;
1070                     }
1071 #endif
1072                     // set up state machine
1073                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1074                     hci_stack.state = HCI_STATE_INITIALIZING;
1075                     hci_stack.substate = 0;
1076                     break;
1077                 case HCI_POWER_OFF:
1078                     // see hci_run
1079                     hci_stack.state = HCI_STATE_HALTING;
1080                     break;
1081                 case HCI_POWER_SLEEP:
1082                     // do nothing
1083                     break;
1084             }
1085             break;
1086 
1087         case HCI_STATE_SLEEPING:
1088             switch (power_mode){
1089                 case HCI_POWER_ON:
1090 
1091 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1092                     // nothing to do, if H4 supports power management
1093                     if (bt_control_iphone_power_management_enabled()){
1094                         hci_stack.state = HCI_STATE_INITIALIZING;
1095                         hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1096                         hci_update_scan_enable();
1097                         break;
1098                     }
1099 #endif
1100                     err = hci_power_control_wake();
1101                     if (err) return err;
1102                     // set up state machine
1103                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1104                     hci_stack.state = HCI_STATE_INITIALIZING;
1105                     hci_stack.substate = 0;
1106                     break;
1107                 case HCI_POWER_OFF:
1108                     hci_stack.state = HCI_STATE_HALTING;
1109                     break;
1110                 case HCI_POWER_SLEEP:
1111                     // do nothing
1112                     break;
1113             }
1114             break;
1115     }
1116 
1117     // create internal event
1118 	hci_emit_state();
1119 
1120 	// trigger next/first action
1121 	hci_run();
1122 
1123     return 0;
1124 }
1125 
1126 static void hci_update_scan_enable(void){
1127     // 2 = page scan, 1 = inq scan
1128     hci_stack.new_scan_enable_value  = hci_stack.connectable << 1 | hci_stack.discoverable;
1129     hci_run();
1130 }
1131 
1132 void hci_discoverable_control(uint8_t enable){
1133     if (enable) enable = 1; // normalize argument
1134 
1135     if (hci_stack.discoverable == enable){
1136         hci_emit_discoverable_enabled(hci_stack.discoverable);
1137         return;
1138     }
1139 
1140     hci_stack.discoverable = enable;
1141     hci_update_scan_enable();
1142 }
1143 
1144 void hci_connectable_control(uint8_t enable){
1145     if (enable) enable = 1; // normalize argument
1146 
1147     // don't emit event
1148     if (hci_stack.connectable == enable) return;
1149 
1150     hci_stack.connectable = enable;
1151     hci_update_scan_enable();
1152 }
1153 
1154 bd_addr_t * hci_local_bd_addr(void){
1155     return &hci_stack.local_bd_addr;
1156 }
1157 
1158 void hci_run(){
1159 
1160     hci_connection_t * connection;
1161     linked_item_t * it;
1162 
1163     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1164 
1165     // global/non-connection oriented commands
1166 
1167     // decline incoming connections
1168     if (hci_stack.decline_reason){
1169         uint8_t reason = hci_stack.decline_reason;
1170         hci_stack.decline_reason = 0;
1171         hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason);
1172         return;
1173     }
1174 
1175     // send scan enable
1176     if (hci_stack.state == HCI_STATE_WORKING && hci_stack.new_scan_enable_value != 0xff && hci_classic_supported()){
1177         hci_send_cmd(&hci_write_scan_enable, hci_stack.new_scan_enable_value);
1178         hci_stack.new_scan_enable_value = 0xff;
1179         return;
1180     }
1181 
1182     // send pending HCI commands
1183     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
1184 
1185         connection = (hci_connection_t *) it;
1186 
1187         if (connection->state == RECEIVED_CONNECTION_REQUEST){
1188             log_info("sending hci_accept_connection_request\n");
1189             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1190             connection->state = ACCEPTED_CONNECTION_REQUEST;
1191             return;
1192         }
1193 
1194         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1195             link_key_t link_key;
1196             log_info("responding to link key request\n");
1197             if ( hci_stack.bondable && hci_stack.remote_device_db && hci_stack.remote_device_db->get_link_key( &connection->address, &link_key)){
1198                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1199             } else {
1200                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1201             }
1202             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1203             return;
1204         }
1205 
1206         if (connection->authentication_flags & HANDLE_PIN_CODE_REQUEST){
1207             log_info("denying to pin request\n");
1208             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1209             connectionClearAuthenticationFlags(connection, HANDLE_PIN_CODE_REQUEST);
1210             return;
1211         }
1212 
1213         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1214             if (hci_stack.bondable){
1215                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack.ssp_io_capability, NULL, hci_stack.ssp_authentication_requirement);
1216             } else {
1217                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1218             }
1219             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1220             return;
1221         }
1222 
1223         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1224             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1225             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1226             return;
1227         }
1228 
1229         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1230             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1231             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1232             return;
1233         }
1234     }
1235 
1236     switch (hci_stack.state){
1237         case HCI_STATE_INITIALIZING:
1238             // log_info("hci_init: substate %u\n", hci_stack.substate);
1239             if (hci_stack.substate % 2) {
1240                 // odd: waiting for command completion
1241                 return;
1242             }
1243             switch (hci_stack.substate >> 1){
1244                 case 0: // RESET
1245                     hci_send_cmd(&hci_reset);
1246 
1247                     if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){
1248                         // skip baud change
1249                         hci_stack.substate = 4; // >> 1 = 2
1250                     }
1251                     break;
1252                 case 1: // SEND BAUD CHANGE
1253                     hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_packet_buffer);
1254                     hci_send_cmd_packet(hci_stack.hci_packet_buffer, 3 + hci_stack.hci_packet_buffer[2]);
1255                     break;
1256                 case 2: // LOCAL BAUD CHANGE
1257                     hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main);
1258                     hci_stack.substate += 2;
1259                     // break missing here for fall through
1260 
1261                 case 3:
1262                     // Custom initialization
1263                     if (hci_stack.control && hci_stack.control->next_cmd){
1264                         int valid_cmd = (*hci_stack.control->next_cmd)(hci_stack.config, hci_stack.hci_packet_buffer);
1265                         if (valid_cmd){
1266                             int size = 3 + hci_stack.hci_packet_buffer[2];
1267                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack.hci_packet_buffer, size);
1268                             hci_stack.substate = 4; // more init commands
1269                             break;
1270                         }
1271                         log_info("hci_run: init script done\n\r");
1272                     }
1273                     // otherwise continue
1274 					hci_send_cmd(&hci_read_bd_addr);
1275 					break;
1276 				case 4:
1277 					hci_send_cmd(&hci_read_buffer_size);
1278 					break;
1279                 case 5:
1280                     hci_send_cmd(&hci_read_local_supported_features);
1281                     break;
1282                 case 6:
1283                     if (hci_le_supported()){
1284                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1285                     } else {
1286                         // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1287                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1288                     }
1289 
1290                     // skip Classic init commands for LE only chipsets
1291                     if (!hci_classic_supported()){
1292                         if (hci_le_supported()){
1293                             hci_stack.substate = 11 << 1;    // skip all classic command
1294                         } else {
1295                             log_error("Neither BR/EDR nor LE supported");
1296                             hci_stack.substate = 13 << 1;    // skip all
1297                         }
1298                     }
1299                     break;
1300                 case 7:
1301                     if (hci_ssp_supported()){
1302                         hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack.ssp_enable);
1303                         break;
1304                     }
1305                     hci_stack.substate += 2;
1306                     // break missing here for fall through
1307 
1308                 case 8:
1309                     // ca. 15 sec
1310                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1311                     break;
1312                 case 9:
1313                     hci_send_cmd(&hci_write_class_of_device, hci_stack.class_of_device);
1314                     break;
1315                 case 10:
1316                     if (hci_stack.local_name){
1317                         hci_send_cmd(&hci_write_local_name, hci_stack.local_name);
1318                     } else {
1319                         char hostname[30];
1320 #ifdef EMBEDDED
1321                         // BTstack-11:22:33:44:55:66
1322                         strcpy(hostname, "BTstack ");
1323                         strcat(hostname, bd_addr_to_str(hci_stack.local_bd_addr));
1324                         printf("---> Name %s\n", hostname);
1325 #else
1326                         // hostname for POSIX systems
1327                         gethostname(hostname, 30);
1328                         hostname[29] = '\0';
1329 #endif
1330                         hci_send_cmd(&hci_write_local_name, hostname);
1331                     }
1332                     break;
1333                 case 11:
1334 					hci_send_cmd(&hci_write_scan_enable, (hci_stack.connectable << 1) | hci_stack.discoverable); // page scan
1335                     if (!hci_le_supported()){
1336                         // SKIP LE init for Classic only configuration
1337                         hci_stack.substate = 13 << 1;
1338                     }
1339 					break;
1340 
1341 #ifdef HAVE_BLE
1342                 // LE INIT
1343                 case 12:
1344                     hci_send_cmd(&hci_le_read_buffer_size);
1345                     break;
1346                 case 13:
1347                     // LE Supported Host = 1, Simultaneous Host = 0
1348                     hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1349                     break;
1350 #endif
1351 
1352                 // DONE
1353                 case 14:
1354                     // done.
1355                     hci_stack.state = HCI_STATE_WORKING;
1356                     hci_emit_state();
1357                     break;
1358                 default:
1359                     break;
1360             }
1361             hci_stack.substate++;
1362             break;
1363 
1364         case HCI_STATE_HALTING:
1365 
1366             log_info("HCI_STATE_HALTING\n");
1367             // close all open connections
1368             connection =  (hci_connection_t *) hci_stack.connections;
1369             if (connection){
1370 
1371                 // send disconnect
1372                 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1373 
1374                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1375                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1376 
1377                 // send disconnected event right away - causes higher layer connections to get closed, too.
1378                 hci_shutdown_connection(connection);
1379                 return;
1380             }
1381             log_info("HCI_STATE_HALTING, calling off\n");
1382 
1383             // switch mode
1384             hci_power_control_off();
1385 
1386             log_info("HCI_STATE_HALTING, emitting state\n");
1387             hci_emit_state();
1388             log_info("HCI_STATE_HALTING, done\n");
1389             break;
1390 
1391         case HCI_STATE_FALLING_ASLEEP:
1392             switch(hci_stack.substate) {
1393                 case 0:
1394                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1395                     // close all open connections
1396                     connection =  (hci_connection_t *) hci_stack.connections;
1397 
1398 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1399                     // don't close connections, if H4 supports power management
1400                     if (bt_control_iphone_power_management_enabled()){
1401                         connection = NULL;
1402                     }
1403 #endif
1404                     if (connection){
1405 
1406                         // send disconnect
1407                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1408 
1409                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1410                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1411 
1412                         // send disconnected event right away - causes higher layer connections to get closed, too.
1413                         hci_shutdown_connection(connection);
1414                         return;
1415                     }
1416 
1417                     if (hci_classic_supported()){
1418                         // disable page and inquiry scan
1419                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1420 
1421                         log_info("HCI_STATE_HALTING, disabling inq scans\n");
1422                         hci_send_cmd(&hci_write_scan_enable, hci_stack.connectable << 1); // drop inquiry scan but keep page scan
1423 
1424                         // continue in next sub state
1425                         hci_stack.substate++;
1426                         break;
1427                     }
1428                     // fall through for ble-only chips
1429 
1430                 case 2:
1431                     log_info("HCI_STATE_HALTING, calling sleep\n");
1432 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1433                     // don't actually go to sleep, if H4 supports power management
1434                     if (bt_control_iphone_power_management_enabled()){
1435                         // SLEEP MODE reached
1436                         hci_stack.state = HCI_STATE_SLEEPING;
1437                         hci_emit_state();
1438                         break;
1439                     }
1440 #endif
1441                     // switch mode
1442                     hci_power_control_sleep();  // changes hci_stack.state to SLEEP
1443                     hci_emit_state();
1444                     break;
1445 
1446                 default:
1447                     break;
1448             }
1449             break;
1450 
1451         default:
1452             break;
1453     }
1454 }
1455 
1456 int hci_send_cmd_packet(uint8_t *packet, int size){
1457     bd_addr_t addr;
1458     hci_connection_t * conn;
1459     // house-keeping
1460 
1461     // create_connection?
1462     if (IS_COMMAND(packet, hci_create_connection)){
1463         bt_flip_addr(addr, &packet[3]);
1464         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1465         conn = connection_for_address(addr);
1466         if (conn) {
1467             // if connection exists
1468             if (conn->state == OPEN) {
1469                 // and OPEN, emit connection complete command
1470                 hci_emit_connection_complete(conn, 0);
1471             }
1472             //    otherwise, just ignore as it is already in the open process
1473             return 0; // don't sent packet to controller
1474 
1475         }
1476         // create connection struct and register, state = SENT_CREATE_CONNECTION
1477         conn = create_connection_for_addr(addr);
1478         if (!conn){
1479             // notify client that alloc failed
1480             hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1481             return 0; // don't sent packet to controller
1482         }
1483         conn->state = SENT_CREATE_CONNECTION;
1484     }
1485 
1486     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1487         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1488     }
1489     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1490         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1491     }
1492     if (IS_COMMAND(packet, hci_pin_code_request_reply)){
1493         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY);
1494     }
1495     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){
1496         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY);
1497     }
1498 
1499     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1500         if (hci_stack.remote_device_db){
1501             bt_flip_addr(addr, &packet[3]);
1502             hci_stack.remote_device_db->delete_link_key(&addr);
1503         }
1504     }
1505 
1506 #ifdef HAVE_BLE
1507     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
1508         hci_stack.adv_addr_type = packet[8];
1509     }
1510     if (IS_COMMAND(packet, hci_le_set_random_address)){
1511         bt_flip_addr(hci_stack.adv_address, &packet[3]);
1512     }
1513 #endif
1514 
1515 
1516     hci_stack.num_cmd_packets--;
1517     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1518 }
1519 
1520 // Configure Secure Simple Pairing
1521 
1522 // enable will enable SSP during init
1523 void hci_ssp_set_enable(int enable){
1524     hci_stack.ssp_enable = enable;
1525 }
1526 
1527 // if set, BTstack will respond to io capability request using authentication requirement
1528 void hci_ssp_set_io_capability(int io_capability){
1529     hci_stack.ssp_io_capability = io_capability;
1530 }
1531 void hci_ssp_set_authentication_requirement(int authentication_requirement){
1532     hci_stack.ssp_authentication_requirement = authentication_requirement;
1533 }
1534 
1535 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
1536 void hci_ssp_set_auto_accept(int auto_accept){
1537     hci_stack.ssp_auto_accept = auto_accept;
1538 }
1539 
1540 /**
1541  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1542  */
1543 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1544     va_list argptr;
1545     va_start(argptr, cmd);
1546     uint16_t size = hci_create_cmd_internal(hci_stack.hci_packet_buffer, cmd, argptr);
1547     va_end(argptr);
1548     return hci_send_cmd_packet(hci_stack.hci_packet_buffer, size);
1549 }
1550 
1551 // Create various non-HCI events.
1552 // TODO: generalize, use table similar to hci_create_command
1553 
1554 void hci_emit_state(){
1555     log_info("BTSTACK_EVENT_STATE %u", hci_stack.state);
1556     uint8_t event[3];
1557     event[0] = BTSTACK_EVENT_STATE;
1558     event[1] = sizeof(event) - 2;
1559     event[2] = hci_stack.state;
1560     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1561     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1562 }
1563 
1564 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1565     uint8_t event[13];
1566     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1567     event[1] = sizeof(event) - 2;
1568     event[2] = status;
1569     bt_store_16(event, 3, conn->con_handle);
1570     bt_flip_addr(&event[5], conn->address);
1571     event[11] = 1; // ACL connection
1572     event[12] = 0; // encryption disabled
1573     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1574     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1575 }
1576 
1577 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1578     uint8_t event[6];
1579     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1580     event[1] = sizeof(event) - 2;
1581     event[2] = 0; // status = OK
1582     bt_store_16(event, 3, handle);
1583     event[5] = reason;
1584     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1585     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1586 }
1587 
1588 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1589     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
1590     uint8_t event[4];
1591     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1592     event[1] = sizeof(event) - 2;
1593     bt_store_16(event, 2, conn->con_handle);
1594     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1595     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1596 }
1597 
1598 void hci_emit_nr_connections_changed(){
1599     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
1600     uint8_t event[3];
1601     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1602     event[1] = sizeof(event) - 2;
1603     event[2] = nr_hci_connections();
1604     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1605     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1606 }
1607 
1608 void hci_emit_hci_open_failed(){
1609     log_info("BTSTACK_EVENT_POWERON_FAILED");
1610     uint8_t event[2];
1611     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1612     event[1] = sizeof(event) - 2;
1613     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1614     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1615 }
1616 
1617 #ifndef EMBEDDED
1618 void hci_emit_btstack_version() {
1619     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
1620     uint8_t event[6];
1621     event[0] = BTSTACK_EVENT_VERSION;
1622     event[1] = sizeof(event) - 2;
1623     event[2] = BTSTACK_MAJOR;
1624     event[3] = BTSTACK_MINOR;
1625     bt_store_16(event, 4, BTSTACK_REVISION);
1626     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1627     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1628 }
1629 #endif
1630 
1631 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1632     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
1633     uint8_t event[3];
1634     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1635     event[1] = sizeof(event) - 2;
1636     event[2] = enabled;
1637     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1638     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1639 }
1640 
1641 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1642     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
1643     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1644     event[1] = sizeof(event) - 2 - 1;
1645     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1646     bt_flip_addr(&event[3], *addr);
1647     memcpy(&event[9], name, 248);
1648 
1649     event[9+248] = 0;   // assert \0 for log_info
1650     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
1651 
1652     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
1653     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
1654 }
1655 
1656 void hci_emit_discoverable_enabled(uint8_t enabled){
1657     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
1658     uint8_t event[3];
1659     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1660     event[1] = sizeof(event) - 2;
1661     event[2] = enabled;
1662     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1663     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1664 }
1665 
1666 // GAP API
1667 /**
1668  * @bbrief enable/disable bonding. default is enabled
1669  * @praram enabled
1670  */
1671 void gap_set_bondable_mode(int enable){
1672     hci_stack.bondable = enable ? 1 : 0;
1673 }
1674