xref: /btstack/src/hci.c (revision dbe1a7904eb75b8d09c618566461d9d5384b6c16)
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 * 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 = 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 = 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 = 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     // get info
276     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
277     hci_connection_t *conn      = connection_for_handle(con_handle);
278     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
279     uint16_t acl_length         = READ_ACL_LENGTH(packet);
280 
281     // ignore non-registered handle
282     if (!conn){
283         log_error( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle);
284         return;
285     }
286 
287     // update idle timestamp
288     hci_connection_timestamp(conn);
289 
290     // handle different packet types
291     switch (acl_flags & 0x03) {
292 
293         case 0x01: // continuation fragment
294 
295             // sanity check
296             if (conn->acl_recombination_pos == 0) {
297                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle);
298                 return;
299             }
300 
301             // append fragment payload (header already stored)
302             memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length );
303             conn->acl_recombination_pos += acl_length;
304 
305             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n", acl_length,
306             //        conn->acl_recombination_pos, conn->acl_recombination_length);
307 
308             // forward complete L2CAP packet if complete.
309             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
310 
311                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos);
312                 // reset recombination buffer
313                 conn->acl_recombination_length = 0;
314                 conn->acl_recombination_pos = 0;
315             }
316             break;
317 
318         case 0x02: { // first fragment
319 
320             // sanity check
321             if (conn->acl_recombination_pos) {
322                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle);
323                 return;
324             }
325 
326             // peek into L2CAP packet!
327             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
328 
329             // log_error( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length);
330 
331             // compare fragment size to L2CAP packet size
332             if (acl_length >= l2cap_length + 4){
333 
334                 // forward fragment as L2CAP packet
335                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
336 
337             } else {
338                 // store first fragment and tweak acl length for complete package
339                 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4);
340                 conn->acl_recombination_pos    = acl_length + 4;
341                 conn->acl_recombination_length = l2cap_length;
342                 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4);
343             }
344             break;
345 
346         }
347         default:
348             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03);
349             return;
350     }
351 
352     // execute main loop
353     hci_run();
354 }
355 
356 static void hci_shutdown_connection(hci_connection_t *conn){
357     log_info("Connection closed: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
358 
359     // cancel all l2cap connections
360     hci_emit_disconnection_complete(conn->con_handle, 0x16);    // terminated by local host
361 
362     run_loop_remove_timer(&conn->timeout);
363 
364     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
365     btstack_memory_hci_connection_free( conn );
366 
367     // now it's gone
368     hci_emit_nr_connections_changed();
369 }
370 
371 static const uint16_t packet_type_sizes[] = {
372     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
373     HCI_ACL_DH1_SIZE, 0, 0, 0,
374     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
375     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
376 };
377 
378 static uint16_t hci_acl_packet_types_for_buffer_size(uint16_t buffer_size){
379     uint16_t packet_types = 0;
380     int i;
381     for (i=0;i<16;i++){
382         if (packet_type_sizes[i] == 0) continue;
383         if (packet_type_sizes[i] <= buffer_size){
384             packet_types |= 1 << i;
385         }
386     }
387     // flip bits for "may not be used"
388     packet_types ^= 0x3306;
389     return packet_types;
390 }
391 
392 uint16_t hci_usable_acl_packet_types(void){
393     return hci_stack.packet_types;
394 }
395 
396 uint8_t* hci_get_outgoing_acl_packet_buffer(void){
397     // hci packet buffer is >= acl data packet length
398     return hci_stack.hci_packet_buffer;
399 }
400 
401 uint16_t hci_max_acl_data_packet_length(){
402     return hci_stack.acl_data_packet_length;
403 }
404 
405 // avoid huge local variables
406 #ifndef EMBEDDED
407 static device_name_t device_name;
408 #endif
409 static void event_handler(uint8_t *packet, int size){
410     bd_addr_t addr;
411     uint8_t link_type;
412     hci_con_handle_t handle;
413     hci_connection_t * conn;
414     int i;
415 
416     // printf("HCI:EVENT:%02x\n", packet[0]);
417 
418     switch (packet[0]) {
419 
420         case HCI_EVENT_COMMAND_COMPLETE:
421             // get num cmd packets
422             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u\n", hci_stack.num_cmd_packets, packet[2]);
423             hci_stack.num_cmd_packets = packet[2];
424 
425             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
426                 // from offset 5
427                 // status
428                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
429                 hci_stack.acl_data_packet_length = READ_BT_16(packet, 6);
430                 // ignore: SCO data packet len (8)
431                 hci_stack.total_num_acl_packets  = packet[9];
432                 // ignore: total num SCO packets
433                 if (hci_stack.state == HCI_STATE_INITIALIZING){
434                     // determine usable ACL payload size
435                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack.acl_data_packet_length){
436                         hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
437                     }
438                     // determine usable ACL packet types
439                     hci_stack.packet_types = hci_acl_packet_types_for_buffer_size(hci_stack.acl_data_packet_length);
440 
441                     log_info("hci_read_buffer_size: used size %u, count %u, packet types %04x\n",
442                              hci_stack.acl_data_packet_length, hci_stack.total_num_acl_packets, hci_stack.packet_types);
443                 }
444             }
445             // Dump local address
446             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
447                 bt_flip_addr(hci_stack.local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
448                 log_info("Local Address, Status: 0x%02x: Addr: %s\n",
449                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack.local_bd_addr));
450             }
451             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
452                 hci_emit_discoverable_enabled(hci_stack.discoverable);
453             }
454             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
455                 memcpy(hci_stack.local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], 8);
456                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
457                     hci_stack.local_supported_features[0], hci_stack.local_supported_features[1],
458                     hci_stack.local_supported_features[2], hci_stack.local_supported_features[3],
459                     hci_stack.local_supported_features[4], hci_stack.local_supported_features[5],
460                     hci_stack.local_supported_features[6], hci_stack.local_supported_features[7]);
461             }
462             break;
463 
464         case HCI_EVENT_COMMAND_STATUS:
465             // get num cmd packets
466             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u\n", hci_stack.num_cmd_packets, packet[3]);
467             hci_stack.num_cmd_packets = packet[3];
468             break;
469 
470         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
471             for (i=0; i<packet[2];i++){
472                 handle = READ_BT_16(packet, 3 + 2*i);
473                 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i);
474                 conn = connection_for_handle(handle);
475                 if (!conn){
476                     log_error("hci_number_completed_packet lists unused con handle %u\n", handle);
477                     continue;
478                 }
479                 conn->num_acl_packets_sent -= num_packets;
480                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent);
481             }
482             break;
483 
484         case HCI_EVENT_CONNECTION_REQUEST:
485             bt_flip_addr(addr, &packet[2]);
486             // TODO: eval COD 8-10
487             link_type = packet[11];
488             log_info("Connection_incoming: %s, type %u\n", bd_addr_to_str(addr), link_type);
489             if (link_type == 1) { // ACL
490                 conn = connection_for_address(addr);
491                 if (!conn) {
492                     conn = create_connection_for_addr(addr);
493                 }
494                 if (!conn) {
495                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
496                     hci_stack.decline_reason = 0x0d;
497                     BD_ADDR_COPY(hci_stack.decline_addr, addr);
498                     break;
499                 }
500                 conn->state = RECEIVED_CONNECTION_REQUEST;
501                 hci_run();
502             } else {
503                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
504                 hci_stack.decline_reason = 0x0a;
505                 BD_ADDR_COPY(hci_stack.decline_addr, addr);
506             }
507             break;
508 
509         case HCI_EVENT_CONNECTION_COMPLETE:
510             // Connection management
511             bt_flip_addr(addr, &packet[5]);
512             log_info("Connection_complete (status=%u) %s\n", packet[2], bd_addr_to_str(addr));
513             conn = connection_for_address(addr);
514             if (conn) {
515                 if (!packet[2]){
516                     conn->state = OPEN;
517                     conn->con_handle = READ_BT_16(packet, 3);
518 
519                     // restart timer
520                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
521                     run_loop_add_timer(&conn->timeout);
522 
523                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
524 
525                     hci_emit_nr_connections_changed();
526                 } else {
527                     // connection failed, remove entry
528                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
529                     btstack_memory_hci_connection_free( conn );
530 
531                     // if authentication error, also delete link key
532                     if (packet[2] == 0x05) {
533                         hci_drop_link_key_for_bd_addr(&addr);
534                     }
535                 }
536             }
537             break;
538 
539         case HCI_EVENT_LINK_KEY_REQUEST:
540             log_info("HCI_EVENT_LINK_KEY_REQUEST\n");
541             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
542             if (!hci_stack.remote_device_db) break;
543             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
544             hci_run();
545             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
546             return;
547 
548         case HCI_EVENT_LINK_KEY_NOTIFICATION:
549             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_NOTIFICATION);
550             if (!hci_stack.remote_device_db) break;
551             bt_flip_addr(addr, &packet[2]);
552             hci_stack.remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8]);
553             // still forward event to allow dismiss of pairing dialog
554             break;
555 
556         case HCI_EVENT_PIN_CODE_REQUEST:
557             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_PIN_CODE_REQUEST);
558             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
559             if (!hci_stack.remote_device_db) break;
560             bt_flip_addr(addr, &packet[2]);
561             hci_stack.remote_device_db->delete_link_key(&addr);
562             break;
563 
564         case HCI_EVENT_IO_CAPABILITY_REQUEST:
565             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
566             if (hci_stack.ssp_io_capability == SSP_IO_CAPABILITY_UNKNOWN) break;
567             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
568             break;
569 
570         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
571             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_USER_CONFIRM_REQUEST);
572             if (!hci_stack.ssp_auto_accept) break;
573             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
574             break;
575 
576         case HCI_EVENT_USER_PASSKEY_REQUEST:
577             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_USER_PASSKEY_REQUEST);
578             if (!hci_stack.ssp_auto_accept) break;
579             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
580             break;
581 
582 #ifndef EMBEDDED
583         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
584             if (!hci_stack.remote_device_db) break;
585             if (packet[2]) break; // status not ok
586             bt_flip_addr(addr, &packet[3]);
587             // fix for invalid remote names - terminate on 0xff
588             for (i=0; i<248;i++){
589                 if (packet[9+i] == 0xff){
590                     packet[9+i] = 0;
591                     break;
592                 }
593             }
594             memset(&device_name, 0, sizeof(device_name_t));
595             strncpy((char*) device_name, (char*) &packet[9], 248);
596             hci_stack.remote_device_db->put_name(&addr, &device_name);
597             break;
598 
599         case HCI_EVENT_INQUIRY_RESULT:
600         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
601             if (!hci_stack.remote_device_db) break;
602             // first send inq result packet
603             hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
604             // then send cached remote names
605             for (i=0; i<packet[2];i++){
606                 bt_flip_addr(addr, &packet[3+i*6]);
607                 if (hci_stack.remote_device_db->get_name(&addr, &device_name)){
608                     hci_emit_remote_name_cached(&addr, &device_name);
609                 }
610             }
611             return;
612 #endif
613 
614         case HCI_EVENT_DISCONNECTION_COMPLETE:
615             if (!packet[2]){
616                 handle = READ_BT_16(packet, 3);
617                 hci_connection_t * conn = connection_for_handle(handle);
618                 if (conn) {
619                     hci_shutdown_connection(conn);
620                 }
621             }
622             break;
623 
624         case HCI_EVENT_HARDWARE_ERROR:
625             if(hci_stack.control->hw_error){
626                 (*hci_stack.control->hw_error)();
627             }
628             break;
629 
630 #ifdef HAVE_BLE
631         case HCI_EVENT_LE_META:
632             switch (packet[2]) {
633                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
634                     // Connection management
635                     bt_flip_addr(addr, &packet[8]);
636                     log_info("LE Connection_complete (status=%u) %s\n", packet[3], bd_addr_to_str(addr));
637                     // LE connections are auto-accepted, so just create a connection if there isn't one already
638                     conn = connection_for_address(addr);
639                     if (packet[3]){
640                         if (conn){
641                             // outgoing connection failed, remove entry
642                             linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
643                             btstack_memory_hci_connection_free( conn );
644 
645                         }
646                         // if authentication error, also delete link key
647                         if (packet[3] == 0x05) {
648                             hci_drop_link_key_for_bd_addr(&addr);
649                         }
650                         break;
651                     }
652                     if (!conn){
653                         conn = create_connection_for_addr(addr);
654                     }
655                     if (!conn){
656                         // no memory
657                         break;
658                     }
659 
660                     conn->state = OPEN;
661                     conn->con_handle = READ_BT_16(packet, 4);
662 
663                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
664 
665                     // restart timer
666                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
667                     // run_loop_add_timer(&conn->timeout);
668 
669                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
670 
671                     hci_emit_nr_connections_changed();
672                     break;
673 
674                 default:
675                     break;
676             }
677             break;
678 #endif
679 
680         default:
681             break;
682     }
683 
684     // handle BT initialization
685     if (hci_stack.state == HCI_STATE_INITIALIZING){
686         // handle H4 synchronization loss on restart
687         // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){
688         //    hci_stack.substate = 0;
689         // }
690         // handle normal init sequence
691         if (hci_stack.substate % 2){
692             // odd: waiting for event
693             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){
694                 hci_stack.substate++;
695             }
696         }
697     }
698 
699     // help with BT sleep
700     if (hci_stack.state == HCI_STATE_FALLING_ASLEEP
701         && hci_stack.substate == 1
702         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
703         hci_stack.substate++;
704     }
705 
706     hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
707 
708 	// execute main loop
709 	hci_run();
710 }
711 
712 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
713     switch (packet_type) {
714         case HCI_EVENT_PACKET:
715             event_handler(packet, size);
716             break;
717         case HCI_ACL_DATA_PACKET:
718             acl_handler(packet, size);
719             break;
720         default:
721             break;
722     }
723 }
724 
725 /** Register HCI packet handlers */
726 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
727     hci_stack.packet_handler = handler;
728 }
729 
730 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
731 
732     // reference to use transport layer implementation
733     hci_stack.hci_transport = transport;
734 
735     // references to used control implementation
736     hci_stack.control = control;
737 
738     // reference to used config
739     hci_stack.config = config;
740 
741     // no connections yet
742     hci_stack.connections = NULL;
743     hci_stack.discoverable = 0;
744     hci_stack.connectable = 0;
745 
746     // no pending cmds
747     hci_stack.decline_reason = 0;
748     hci_stack.new_scan_enable_value = 0xff;
749 
750     // higher level handler
751     hci_stack.packet_handler = dummy_handler;
752 
753     // store and open remote device db
754     hci_stack.remote_device_db = remote_device_db;
755     if (hci_stack.remote_device_db) {
756         hci_stack.remote_device_db->open();
757     }
758 
759     // max acl payload size defined in config.h
760     hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
761 
762     // register packet handlers with transport
763     transport->register_packet_handler(&packet_handler);
764 
765     hci_stack.state = HCI_STATE_OFF;
766 
767     // class of device
768     hci_stack.class_of_device = 0x007a020c; // Smartphone
769 
770     // Secure Simple Pairing
771     hci_stack.ssp_enable = 0;
772     hci_stack.ssp_io_capability = SSP_IO_CAPABILITY_UNKNOWN;
773     hci_stack.ssp_authentication_requirement = 0;
774 }
775 
776 void hci_close(){
777     // close remote device db
778     if (hci_stack.remote_device_db) {
779         hci_stack.remote_device_db->close();
780     }
781     while (hci_stack.connections) {
782         hci_shutdown_connection((hci_connection_t *) hci_stack.connections);
783 }
784     hci_power_control(HCI_POWER_OFF);
785 }
786 
787 // State-Module-Driver overview
788 // state                    module  low-level
789 // HCI_STATE_OFF             off      close
790 // HCI_STATE_INITIALIZING,   on       open
791 // HCI_STATE_WORKING,        on       open
792 // HCI_STATE_HALTING,        on       open
793 // HCI_STATE_SLEEPING,    off/sleep   close
794 // HCI_STATE_FALLING_ASLEEP  on       open
795 
796 static int hci_power_control_on(void){
797 
798     // power on
799     int err = 0;
800     if (hci_stack.control && hci_stack.control->on){
801         err = (*hci_stack.control->on)(hci_stack.config);
802     }
803     if (err){
804         log_error( "POWER_ON failed\n");
805         hci_emit_hci_open_failed();
806         return err;
807     }
808 
809     // open low-level device
810     err = hci_stack.hci_transport->open(hci_stack.config);
811     if (err){
812         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
813         if (hci_stack.control && hci_stack.control->off){
814             (*hci_stack.control->off)(hci_stack.config);
815         }
816         hci_emit_hci_open_failed();
817         return err;
818     }
819     return 0;
820 }
821 
822 static void hci_power_control_off(void){
823 
824     log_info("hci_power_control_off\n");
825 
826     // close low-level device
827     hci_stack.hci_transport->close(hci_stack.config);
828 
829     log_info("hci_power_control_off - hci_transport closed\n");
830 
831     // power off
832     if (hci_stack.control && hci_stack.control->off){
833         (*hci_stack.control->off)(hci_stack.config);
834     }
835 
836     log_info("hci_power_control_off - control closed\n");
837 
838     hci_stack.state = HCI_STATE_OFF;
839 }
840 
841 static void hci_power_control_sleep(void){
842 
843     log_info("hci_power_control_sleep\n");
844 
845 #if 0
846     // don't close serial port during sleep
847 
848     // close low-level device
849     hci_stack.hci_transport->close(hci_stack.config);
850 #endif
851 
852     // sleep mode
853     if (hci_stack.control && hci_stack.control->sleep){
854         (*hci_stack.control->sleep)(hci_stack.config);
855     }
856 
857     hci_stack.state = HCI_STATE_SLEEPING;
858 }
859 
860 static int hci_power_control_wake(void){
861 
862     log_info("hci_power_control_wake\n");
863 
864     // wake on
865     if (hci_stack.control && hci_stack.control->wake){
866         (*hci_stack.control->wake)(hci_stack.config);
867     }
868 
869 #if 0
870     // open low-level device
871     int err = hci_stack.hci_transport->open(hci_stack.config);
872     if (err){
873         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
874         if (hci_stack.control && hci_stack.control->off){
875             (*hci_stack.control->off)(hci_stack.config);
876         }
877         hci_emit_hci_open_failed();
878         return err;
879     }
880 #endif
881 
882     return 0;
883 }
884 
885 
886 int hci_power_control(HCI_POWER_MODE power_mode){
887 
888     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state);
889 
890     int err = 0;
891     switch (hci_stack.state){
892 
893         case HCI_STATE_OFF:
894             switch (power_mode){
895                 case HCI_POWER_ON:
896                     err = hci_power_control_on();
897                     if (err) return err;
898                     // set up state machine
899                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
900                     hci_stack.state = HCI_STATE_INITIALIZING;
901                     hci_stack.substate = 0;
902                     break;
903                 case HCI_POWER_OFF:
904                     // do nothing
905                     break;
906                 case HCI_POWER_SLEEP:
907                     // do nothing (with SLEEP == OFF)
908                     break;
909             }
910             break;
911 
912         case HCI_STATE_INITIALIZING:
913             switch (power_mode){
914                 case HCI_POWER_ON:
915                     // do nothing
916                     break;
917                 case HCI_POWER_OFF:
918                     // no connections yet, just turn it off
919                     hci_power_control_off();
920                     break;
921                 case HCI_POWER_SLEEP:
922                     // no connections yet, just turn it off
923                     hci_power_control_sleep();
924                     break;
925             }
926             break;
927 
928         case HCI_STATE_WORKING:
929             switch (power_mode){
930                 case HCI_POWER_ON:
931                     // do nothing
932                     break;
933                 case HCI_POWER_OFF:
934                     // see hci_run
935                     hci_stack.state = HCI_STATE_HALTING;
936                     break;
937                 case HCI_POWER_SLEEP:
938                     // see hci_run
939                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
940                     hci_stack.substate = 0;
941                     break;
942             }
943             break;
944 
945         case HCI_STATE_HALTING:
946             switch (power_mode){
947                 case HCI_POWER_ON:
948                     // set up state machine
949                     hci_stack.state = HCI_STATE_INITIALIZING;
950                     hci_stack.substate = 0;
951                     break;
952                 case HCI_POWER_OFF:
953                     // do nothing
954                     break;
955                 case HCI_POWER_SLEEP:
956                     // see hci_run
957                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
958                     hci_stack.substate = 0;
959                     break;
960             }
961             break;
962 
963         case HCI_STATE_FALLING_ASLEEP:
964             switch (power_mode){
965                 case HCI_POWER_ON:
966 
967 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
968                     // nothing to do, if H4 supports power management
969                     if (bt_control_iphone_power_management_enabled()){
970                         hci_stack.state = HCI_STATE_INITIALIZING;
971                         hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
972                         break;
973                     }
974 #endif
975                     // set up state machine
976                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
977                     hci_stack.state = HCI_STATE_INITIALIZING;
978                     hci_stack.substate = 0;
979                     break;
980                 case HCI_POWER_OFF:
981                     // see hci_run
982                     hci_stack.state = HCI_STATE_HALTING;
983                     break;
984                 case HCI_POWER_SLEEP:
985                     // do nothing
986                     break;
987             }
988             break;
989 
990         case HCI_STATE_SLEEPING:
991             switch (power_mode){
992                 case HCI_POWER_ON:
993 
994 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
995                     // nothing to do, if H4 supports power management
996                     if (bt_control_iphone_power_management_enabled()){
997                         hci_stack.state = HCI_STATE_INITIALIZING;
998                         hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
999                         hci_update_scan_enable();
1000                         break;
1001                     }
1002 #endif
1003                     err = hci_power_control_wake();
1004                     if (err) return err;
1005                     // set up state machine
1006                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1007                     hci_stack.state = HCI_STATE_INITIALIZING;
1008                     hci_stack.substate = 0;
1009                     break;
1010                 case HCI_POWER_OFF:
1011                     hci_stack.state = HCI_STATE_HALTING;
1012                     break;
1013                 case HCI_POWER_SLEEP:
1014                     // do nothing
1015                     break;
1016             }
1017             break;
1018     }
1019 
1020     // create internal event
1021 	hci_emit_state();
1022 
1023 	// trigger next/first action
1024 	hci_run();
1025 
1026     return 0;
1027 }
1028 
1029 static void hci_update_scan_enable(void){
1030     // 2 = page scan, 1 = inq scan
1031     hci_stack.new_scan_enable_value  = hci_stack.connectable << 1 | hci_stack.discoverable;
1032     hci_run();
1033 }
1034 
1035 void hci_discoverable_control(uint8_t enable){
1036     if (enable) enable = 1; // normalize argument
1037 
1038     if (hci_stack.discoverable == enable){
1039         hci_emit_discoverable_enabled(hci_stack.discoverable);
1040         return;
1041     }
1042 
1043     hci_stack.discoverable = enable;
1044     hci_update_scan_enable();
1045 }
1046 
1047 void hci_connectable_control(uint8_t enable){
1048     if (enable) enable = 1; // normalize argument
1049 
1050     // don't emit event
1051     if (hci_stack.connectable == enable) return;
1052 
1053     hci_stack.connectable = enable;
1054     hci_update_scan_enable();
1055 }
1056 
1057 void hci_run(){
1058 
1059     hci_connection_t * connection;
1060     linked_item_t * it;
1061 
1062     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1063 
1064     // global/non-connection oriented commands
1065 
1066     // decline incoming connections
1067     if (hci_stack.decline_reason){
1068         uint8_t reason = hci_stack.decline_reason;
1069         hci_stack.decline_reason = 0;
1070         hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason);
1071         return;
1072     }
1073 
1074     // send scan enable
1075     if (hci_stack.state == HCI_STATE_WORKING && hci_stack.new_scan_enable_value != 0xff){
1076         hci_send_cmd(&hci_write_scan_enable, hci_stack.new_scan_enable_value);
1077         hci_stack.new_scan_enable_value = 0xff;
1078         return;
1079     }
1080 
1081     // send pending HCI commands
1082     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
1083 
1084         connection = (hci_connection_t *) it;
1085 
1086         if (connection->state == RECEIVED_CONNECTION_REQUEST){
1087             log_info("sending hci_accept_connection_request\n");
1088             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1089             connection->state = ACCEPTED_CONNECTION_REQUEST;
1090             return;
1091         }
1092 
1093         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1094             link_key_t link_key;
1095             log_info("responding to link key request\n");
1096             if ( hci_stack.remote_device_db->get_link_key( &connection->address, &link_key)){
1097                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1098             } else {
1099                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1100             }
1101             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1102             return;
1103         }
1104 
1105         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1106             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack.ssp_io_capability, NULL, hci_stack.ssp_authentication_requirement);
1107             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1108             return;
1109         }
1110 
1111         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1112             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1113             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1114             return;
1115         }
1116 
1117         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1118             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1119             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1120             return;
1121         }
1122     }
1123 
1124     switch (hci_stack.state){
1125         case HCI_STATE_INITIALIZING:
1126             // log_info("hci_init: substate %u\n", hci_stack.substate);
1127             if (hci_stack.substate % 2) {
1128                 // odd: waiting for command completion
1129                 return;
1130             }
1131             switch (hci_stack.substate >> 1){
1132                 case 0: // RESET
1133                     hci_send_cmd(&hci_reset);
1134                     if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){
1135                         // skip baud change
1136                         hci_stack.substate = 4; // >> 1 = 2
1137                     }
1138                     break;
1139                 case 1: // SEND BAUD CHANGE
1140                     hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_packet_buffer);
1141                     hci_send_cmd_packet(hci_stack.hci_packet_buffer, 3 + hci_stack.hci_packet_buffer[2]);
1142                     break;
1143                 case 2: // LOCAL BAUD CHANGE
1144                     hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main);
1145                     hci_stack.substate += 2;
1146                     // break missing here for fall through
1147 
1148                 case 3:
1149                     // custom initialization
1150                     if (hci_stack.control && hci_stack.control->next_cmd){
1151                         int valid_cmd = (*hci_stack.control->next_cmd)(hci_stack.config, hci_stack.hci_packet_buffer);
1152                         if (valid_cmd){
1153                             int size = 3 + hci_stack.hci_packet_buffer[2];
1154                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack.hci_packet_buffer, size);
1155                             hci_stack.substate = 4; // more init commands
1156                             break;
1157                         }
1158                         log_info("hci_run: init script done\n\r");
1159                     }
1160                     // otherwise continue
1161 					hci_send_cmd(&hci_read_bd_addr);
1162 					break;
1163 				case 4:
1164 					hci_send_cmd(&hci_read_buffer_size);
1165 					break;
1166                 case 5:
1167                     // ca. 15 sec
1168                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1169                     break;
1170                 case 6:
1171                     hci_send_cmd(&hci_read_local_supported_features);
1172                     break;
1173                 case 7:
1174                     hci_send_cmd(&hci_write_class_of_device, hci_stack.class_of_device);
1175                     break;
1176                 case 8:
1177                     if (hci_stack.local_name){
1178                         hci_send_cmd(&hci_write_local_name, hci_stack.local_name);
1179                     } else {
1180                         char hostname[30];
1181 #ifdef EMBEDDED
1182                         // BTstack-11:22:33:44:55:66
1183                         strcpy(hostname, "BTstack ");
1184                         strcat(hostname, bd_addr_to_str(hci_stack.local_bd_addr));
1185                         printf("---> Name %s\n", hostname);
1186 #else
1187                         // hostname for POSIX systems
1188                         gethostname(hostname, 30);
1189                         hostname[29] = '\0';
1190 #endif
1191                         hci_send_cmd(&hci_write_local_name, hostname);
1192                     }
1193                     break;
1194                 case 9:
1195                     hci_send_cmd(&hci_set_event_mask,0xffffffff, 0xFFFFFFFF); ///0x1DFFFFFF
1196                     break;
1197                 case 10:
1198                     hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack.ssp_enable);
1199                     break;
1200                 case 11:
1201 					hci_send_cmd(&hci_write_scan_enable, (hci_stack.connectable << 1) | hci_stack.discoverable); // page scan
1202 					break;
1203                 case 12:
1204                     // done.
1205                     hci_stack.state = HCI_STATE_WORKING;
1206                     hci_emit_state();
1207                     break;
1208                 default:
1209                     break;
1210             }
1211             hci_stack.substate++;
1212             break;
1213 
1214         case HCI_STATE_HALTING:
1215 
1216             log_info("HCI_STATE_HALTING\n");
1217             // close all open connections
1218             connection =  (hci_connection_t *) hci_stack.connections;
1219             if (connection){
1220 
1221                 // send disconnect
1222                 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1223 
1224                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1225                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1226 
1227                 // send disconnected event right away - causes higher layer connections to get closed, too.
1228                 hci_shutdown_connection(connection);
1229                 return;
1230             }
1231             log_info("HCI_STATE_HALTING, calling off\n");
1232 
1233             // switch mode
1234             hci_power_control_off();
1235 
1236             log_info("HCI_STATE_HALTING, emitting state\n");
1237             hci_emit_state();
1238             log_info("HCI_STATE_HALTING, done\n");
1239             break;
1240 
1241         case HCI_STATE_FALLING_ASLEEP:
1242             switch(hci_stack.substate) {
1243                 case 0:
1244                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1245                     // close all open connections
1246                     connection =  (hci_connection_t *) hci_stack.connections;
1247 
1248 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1249                     // don't close connections, if H4 supports power management
1250                     if (bt_control_iphone_power_management_enabled()){
1251                         connection = NULL;
1252                     }
1253 #endif
1254                     if (connection){
1255 
1256                         // send disconnect
1257                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1258 
1259                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1260                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1261 
1262                         // send disconnected event right away - causes higher layer connections to get closed, too.
1263                         hci_shutdown_connection(connection);
1264                         return;
1265                     }
1266 
1267                     // disable page and inquiry scan
1268                     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1269 
1270                     log_info("HCI_STATE_HALTING, disabling inq cans\n");
1271                     hci_send_cmd(&hci_write_scan_enable, hci_stack.connectable << 1); // drop inquiry scan but keep page scan
1272 
1273                     // continue in next sub state
1274                     hci_stack.substate++;
1275                     break;
1276                 case 1:
1277                     // wait for command complete "hci_write_scan_enable" in event_handler();
1278                     break;
1279                 case 2:
1280                     log_info("HCI_STATE_HALTING, calling sleep\n");
1281 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1282                     // don't actually go to sleep, if H4 supports power management
1283                     if (bt_control_iphone_power_management_enabled()){
1284                         // SLEEP MODE reached
1285                         hci_stack.state = HCI_STATE_SLEEPING;
1286                         hci_emit_state();
1287                         break;
1288                     }
1289 #endif
1290                     // switch mode
1291                     hci_power_control_sleep();  // changes hci_stack.state to SLEEP
1292                     hci_emit_state();
1293                     break;
1294 
1295                 default:
1296                     break;
1297             }
1298             break;
1299 
1300         default:
1301             break;
1302     }
1303 }
1304 
1305 int hci_send_cmd_packet(uint8_t *packet, int size){
1306     bd_addr_t addr;
1307     hci_connection_t * conn;
1308     // house-keeping
1309 
1310     // create_connection?
1311     if (IS_COMMAND(packet, hci_create_connection)){
1312         bt_flip_addr(addr, &packet[3]);
1313         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1314         conn = connection_for_address(addr);
1315         if (conn) {
1316             // if connection exists
1317             if (conn->state == OPEN) {
1318                 // and OPEN, emit connection complete command
1319                 hci_emit_connection_complete(conn, 0);
1320             }
1321             //    otherwise, just ignore as it is already in the open process
1322             return 0; // don't sent packet to controller
1323 
1324         }
1325         // create connection struct and register, state = SENT_CREATE_CONNECTION
1326         conn = create_connection_for_addr(addr);
1327         if (!conn){
1328             // notify client that alloc failed
1329             hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1330             return 0; // don't sent packet to controller
1331         }
1332         conn->state = SENT_CREATE_CONNECTION;
1333     }
1334 
1335     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1336         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1337     }
1338     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1339         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1340     }
1341     if (IS_COMMAND(packet, hci_pin_code_request_reply)){
1342         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY);
1343     }
1344     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){
1345         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY);
1346     }
1347 
1348     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1349         if (hci_stack.remote_device_db){
1350             bt_flip_addr(addr, &packet[3]);
1351             hci_stack.remote_device_db->delete_link_key(&addr);
1352         }
1353     }
1354 
1355     hci_stack.num_cmd_packets--;
1356     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1357 }
1358 
1359 // Configure Secure Simple Pairing
1360 
1361 // enable will enable SSP during init
1362 void hci_ssp_set_enable(int enable){
1363     hci_stack.ssp_enable = enable;
1364 }
1365 
1366 // if set, BTstack will respond to io capability request using authentication requirement
1367 void hci_ssp_set_io_capability(int io_capability){
1368     hci_stack.ssp_io_capability = io_capability;
1369 }
1370 void hci_ssp_set_authentication_requirement(int authentication_requirement){
1371     hci_stack.ssp_authentication_requirement = authentication_requirement;
1372 }
1373 
1374 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
1375 void hci_ssp_set_auto_accept(int auto_accept){
1376     hci_stack.ssp_auto_accept = auto_accept;
1377 }
1378 
1379 /**
1380  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1381  */
1382 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1383     va_list argptr;
1384     va_start(argptr, cmd);
1385     uint16_t size = hci_create_cmd_internal(hci_stack.hci_packet_buffer, cmd, argptr);
1386     va_end(argptr);
1387     return hci_send_cmd_packet(hci_stack.hci_packet_buffer, size);
1388 }
1389 
1390 // Create various non-HCI events.
1391 // TODO: generalize, use table similar to hci_create_command
1392 
1393 void hci_emit_state(){
1394     log_info("BTSTACK_EVENT_STATE %u", hci_stack.state);
1395     uint8_t event[3];
1396     event[0] = BTSTACK_EVENT_STATE;
1397     event[1] = sizeof(event) - 2;
1398     event[2] = hci_stack.state;
1399     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1400     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1401 }
1402 
1403 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1404     uint8_t event[13];
1405     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1406     event[1] = sizeof(event) - 2;
1407     event[2] = status;
1408     bt_store_16(event, 3, conn->con_handle);
1409     bt_flip_addr(&event[5], conn->address);
1410     event[11] = 1; // ACL connection
1411     event[12] = 0; // encryption disabled
1412     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1413     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1414 }
1415 
1416 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1417     uint8_t event[6];
1418     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1419     event[1] = sizeof(event) - 2;
1420     event[2] = 0; // status = OK
1421     bt_store_16(event, 3, handle);
1422     event[5] = reason;
1423     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1424     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1425 }
1426 
1427 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1428     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
1429     uint8_t event[4];
1430     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1431     event[1] = sizeof(event) - 2;
1432     bt_store_16(event, 2, conn->con_handle);
1433     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1434     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1435 }
1436 
1437 void hci_emit_nr_connections_changed(){
1438     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
1439     uint8_t event[3];
1440     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1441     event[1] = sizeof(event) - 2;
1442     event[2] = nr_hci_connections();
1443     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1444     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1445 }
1446 
1447 void hci_emit_hci_open_failed(){
1448     log_info("BTSTACK_EVENT_POWERON_FAILED");
1449     uint8_t event[2];
1450     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1451     event[1] = sizeof(event) - 2;
1452     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1453     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1454 }
1455 
1456 #ifndef EMBEDDED
1457 void hci_emit_btstack_version() {
1458     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
1459     uint8_t event[6];
1460     event[0] = BTSTACK_EVENT_VERSION;
1461     event[1] = sizeof(event) - 2;
1462     event[2] = BTSTACK_MAJOR;
1463     event[3] = BTSTACK_MINOR;
1464     bt_store_16(event, 4, BTSTACK_REVISION);
1465     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1466     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1467 }
1468 #endif
1469 
1470 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1471     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
1472     uint8_t event[3];
1473     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1474     event[1] = sizeof(event) - 2;
1475     event[2] = enabled;
1476     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1477     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1478 }
1479 
1480 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1481     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
1482     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1483     event[1] = sizeof(event) - 2 - 1;
1484     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1485     bt_flip_addr(&event[3], *addr);
1486     memcpy(&event[9], name, 248);
1487 
1488     event[9+248] = 0;   // assert \0 for log_info
1489     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
1490 
1491     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
1492     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
1493 }
1494 
1495 void hci_emit_discoverable_enabled(uint8_t enabled){
1496     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
1497     uint8_t event[3];
1498     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1499     event[1] = sizeof(event) - 2;
1500     event[2] = enabled;
1501     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1502     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1503 }
1504