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