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