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