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