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