xref: /btstack/src/hci.c (revision 1eb2563e8a879e8d115d41616c44ad3f5871ea12)
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             if (gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
715                 // link key sufficient for requested security
716                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
717                 return;
718             } else {
719                 // not enough
720                hci_emit_security_level(handle, gap_security_level_for_connection(conn));
721             }
722             break;
723 
724 #ifndef EMBEDDED
725         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
726             if (!hci_stack.remote_device_db) break;
727             if (packet[2]) break; // status not ok
728             bt_flip_addr(addr, &packet[3]);
729             // fix for invalid remote names - terminate on 0xff
730             for (i=0; i<248;i++){
731                 if (packet[9+i] == 0xff){
732                     packet[9+i] = 0;
733                     break;
734                 }
735             }
736             memset(&device_name, 0, sizeof(device_name_t));
737             strncpy((char*) device_name, (char*) &packet[9], 248);
738             hci_stack.remote_device_db->put_name(&addr, &device_name);
739             break;
740 
741         case HCI_EVENT_INQUIRY_RESULT:
742         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
743             if (!hci_stack.remote_device_db) break;
744             // first send inq result packet
745             hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
746             // then send cached remote names
747             for (i=0; i<packet[2];i++){
748                 bt_flip_addr(addr, &packet[3+i*6]);
749                 if (hci_stack.remote_device_db->get_name(&addr, &device_name)){
750                     hci_emit_remote_name_cached(&addr, &device_name);
751                 }
752             }
753             return;
754 #endif
755 
756         case HCI_EVENT_DISCONNECTION_COMPLETE:
757             if (!packet[2]){
758                 handle = READ_BT_16(packet, 3);
759                 hci_connection_t * conn = hci_connection_for_handle(handle);
760                 if (conn) {
761                     hci_shutdown_connection(conn);
762                 }
763             }
764             break;
765 
766         case HCI_EVENT_HARDWARE_ERROR:
767             if(hci_stack.control && hci_stack.control->hw_error){
768                 (*hci_stack.control->hw_error)();
769             }
770             break;
771 
772 #ifdef HAVE_BLE
773         case HCI_EVENT_LE_META:
774             switch (packet[2]) {
775                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
776                     // Connection management
777                     bt_flip_addr(addr, &packet[8]);
778                     log_info("LE Connection_complete (status=%u) %s\n", packet[3], bd_addr_to_str(addr));
779                     // LE connections are auto-accepted, so just create a connection if there isn't one already
780                     conn = connection_for_address(addr);
781                     if (packet[3]){
782                         if (conn){
783                             // outgoing connection failed, remove entry
784                             linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
785                             btstack_memory_hci_connection_free( conn );
786 
787                         }
788                         // if authentication error, also delete link key
789                         if (packet[3] == 0x05) {
790                             hci_drop_link_key_for_bd_addr(&addr);
791                         }
792                         break;
793                     }
794                     if (!conn){
795                         conn = create_connection_for_addr(addr);
796                     }
797                     if (!conn){
798                         // no memory
799                         break;
800                     }
801 
802                     conn->state = OPEN;
803                     conn->con_handle = READ_BT_16(packet, 4);
804 
805                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
806 
807                     // restart timer
808                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
809                     // run_loop_add_timer(&conn->timeout);
810 
811                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
812 
813                     hci_emit_nr_connections_changed();
814                     break;
815 
816             // printf("LE buffer size: %u, count %u\n", READ_BT_16(packet,6), packet[8]);
817 
818                 default:
819                     break;
820             }
821             break;
822 #endif
823 
824         default:
825             break;
826     }
827 
828     // handle BT initialization
829     if (hci_stack.state == HCI_STATE_INITIALIZING){
830         if (hci_stack.substate % 2){
831             // odd: waiting for event
832             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){
833                 // wait for explicit COMMAND COMPLETE on RESET
834                 if (hci_stack.substate > 1 || COMMAND_COMPLETE_EVENT(packet, hci_reset)) {
835                     hci_stack.substate++;
836                 }
837             }
838         }
839     }
840 
841     // help with BT sleep
842     if (hci_stack.state == HCI_STATE_FALLING_ASLEEP
843         && hci_stack.substate == 1
844         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
845         hci_stack.substate++;
846     }
847 
848     hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
849 
850 	// execute main loop
851 	hci_run();
852 }
853 
854 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
855     switch (packet_type) {
856         case HCI_EVENT_PACKET:
857             event_handler(packet, size);
858             break;
859         case HCI_ACL_DATA_PACKET:
860             acl_handler(packet, size);
861             break;
862         default:
863             break;
864     }
865 }
866 
867 /** Register HCI packet handlers */
868 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
869     hci_stack.packet_handler = handler;
870 }
871 
872 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
873 
874     // reference to use transport layer implementation
875     hci_stack.hci_transport = transport;
876 
877     // references to used control implementation
878     hci_stack.control = control;
879 
880     // reference to used config
881     hci_stack.config = config;
882 
883     // no connections yet
884     hci_stack.connections = NULL;
885     hci_stack.discoverable = 0;
886     hci_stack.connectable = 0;
887     hci_stack.bondable = 1;
888 
889     // no pending cmds
890     hci_stack.decline_reason = 0;
891     hci_stack.new_scan_enable_value = 0xff;
892 
893     // higher level handler
894     hci_stack.packet_handler = dummy_handler;
895 
896     // store and open remote device db
897     hci_stack.remote_device_db = remote_device_db;
898     if (hci_stack.remote_device_db) {
899         hci_stack.remote_device_db->open();
900     }
901 
902     // max acl payload size defined in config.h
903     hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
904 
905     // register packet handlers with transport
906     transport->register_packet_handler(&packet_handler);
907 
908     hci_stack.state = HCI_STATE_OFF;
909 
910     // class of device
911     hci_stack.class_of_device = 0x007a020c; // Smartphone
912 
913     // Secure Simple Pairing default: enable, no I/O capabilities, auto accept
914     hci_stack.ssp_enable = 1;
915     hci_stack.ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
916     hci_stack.ssp_authentication_requirement = 0;
917     hci_stack.ssp_auto_accept = 1;
918 
919     // LE
920     hci_stack.adv_addr_type = 0;
921     memset(hci_stack.adv_address, 0, 6);
922 }
923 
924 void hci_close(){
925     // close remote device db
926     if (hci_stack.remote_device_db) {
927         hci_stack.remote_device_db->close();
928     }
929     while (hci_stack.connections) {
930         hci_shutdown_connection((hci_connection_t *) hci_stack.connections);
931 }
932     hci_power_control(HCI_POWER_OFF);
933 }
934 
935 // State-Module-Driver overview
936 // state                    module  low-level
937 // HCI_STATE_OFF             off      close
938 // HCI_STATE_INITIALIZING,   on       open
939 // HCI_STATE_WORKING,        on       open
940 // HCI_STATE_HALTING,        on       open
941 // HCI_STATE_SLEEPING,    off/sleep   close
942 // HCI_STATE_FALLING_ASLEEP  on       open
943 
944 static int hci_power_control_on(void){
945 
946     // power on
947     int err = 0;
948     if (hci_stack.control && hci_stack.control->on){
949         err = (*hci_stack.control->on)(hci_stack.config);
950     }
951     if (err){
952         log_error( "POWER_ON failed\n");
953         hci_emit_hci_open_failed();
954         return err;
955     }
956 
957     // open low-level device
958     err = hci_stack.hci_transport->open(hci_stack.config);
959     if (err){
960         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
961         if (hci_stack.control && hci_stack.control->off){
962             (*hci_stack.control->off)(hci_stack.config);
963         }
964         hci_emit_hci_open_failed();
965         return err;
966     }
967     return 0;
968 }
969 
970 static void hci_power_control_off(void){
971 
972     log_info("hci_power_control_off\n");
973 
974     // close low-level device
975     hci_stack.hci_transport->close(hci_stack.config);
976 
977     log_info("hci_power_control_off - hci_transport closed\n");
978 
979     // power off
980     if (hci_stack.control && hci_stack.control->off){
981         (*hci_stack.control->off)(hci_stack.config);
982     }
983 
984     log_info("hci_power_control_off - control closed\n");
985 
986     hci_stack.state = HCI_STATE_OFF;
987 }
988 
989 static void hci_power_control_sleep(void){
990 
991     log_info("hci_power_control_sleep\n");
992 
993 #if 0
994     // don't close serial port during sleep
995 
996     // close low-level device
997     hci_stack.hci_transport->close(hci_stack.config);
998 #endif
999 
1000     // sleep mode
1001     if (hci_stack.control && hci_stack.control->sleep){
1002         (*hci_stack.control->sleep)(hci_stack.config);
1003     }
1004 
1005     hci_stack.state = HCI_STATE_SLEEPING;
1006 }
1007 
1008 static int hci_power_control_wake(void){
1009 
1010     log_info("hci_power_control_wake\n");
1011 
1012     // wake on
1013     if (hci_stack.control && hci_stack.control->wake){
1014         (*hci_stack.control->wake)(hci_stack.config);
1015     }
1016 
1017 #if 0
1018     // open low-level device
1019     int err = hci_stack.hci_transport->open(hci_stack.config);
1020     if (err){
1021         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
1022         if (hci_stack.control && hci_stack.control->off){
1023             (*hci_stack.control->off)(hci_stack.config);
1024         }
1025         hci_emit_hci_open_failed();
1026         return err;
1027     }
1028 #endif
1029 
1030     return 0;
1031 }
1032 
1033 
1034 int hci_power_control(HCI_POWER_MODE power_mode){
1035 
1036     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state);
1037 
1038     int err = 0;
1039     switch (hci_stack.state){
1040 
1041         case HCI_STATE_OFF:
1042             switch (power_mode){
1043                 case HCI_POWER_ON:
1044                     err = hci_power_control_on();
1045                     if (err) return err;
1046                     // set up state machine
1047                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1048                     hci_stack.state = HCI_STATE_INITIALIZING;
1049                     hci_stack.substate = 0;
1050                     break;
1051                 case HCI_POWER_OFF:
1052                     // do nothing
1053                     break;
1054                 case HCI_POWER_SLEEP:
1055                     // do nothing (with SLEEP == OFF)
1056                     break;
1057             }
1058             break;
1059 
1060         case HCI_STATE_INITIALIZING:
1061             switch (power_mode){
1062                 case HCI_POWER_ON:
1063                     // do nothing
1064                     break;
1065                 case HCI_POWER_OFF:
1066                     // no connections yet, just turn it off
1067                     hci_power_control_off();
1068                     break;
1069                 case HCI_POWER_SLEEP:
1070                     // no connections yet, just turn it off
1071                     hci_power_control_sleep();
1072                     break;
1073             }
1074             break;
1075 
1076         case HCI_STATE_WORKING:
1077             switch (power_mode){
1078                 case HCI_POWER_ON:
1079                     // do nothing
1080                     break;
1081                 case HCI_POWER_OFF:
1082                     // see hci_run
1083                     hci_stack.state = HCI_STATE_HALTING;
1084                     break;
1085                 case HCI_POWER_SLEEP:
1086                     // see hci_run
1087                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
1088                     hci_stack.substate = 0;
1089                     break;
1090             }
1091             break;
1092 
1093         case HCI_STATE_HALTING:
1094             switch (power_mode){
1095                 case HCI_POWER_ON:
1096                     // set up state machine
1097                     hci_stack.state = HCI_STATE_INITIALIZING;
1098                     hci_stack.substate = 0;
1099                     break;
1100                 case HCI_POWER_OFF:
1101                     // do nothing
1102                     break;
1103                 case HCI_POWER_SLEEP:
1104                     // see hci_run
1105                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
1106                     hci_stack.substate = 0;
1107                     break;
1108             }
1109             break;
1110 
1111         case HCI_STATE_FALLING_ASLEEP:
1112             switch (power_mode){
1113                 case HCI_POWER_ON:
1114 
1115 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1116                     // nothing to do, if H4 supports power management
1117                     if (bt_control_iphone_power_management_enabled()){
1118                         hci_stack.state = HCI_STATE_INITIALIZING;
1119                         hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1120                         break;
1121                     }
1122 #endif
1123                     // set up state machine
1124                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1125                     hci_stack.state = HCI_STATE_INITIALIZING;
1126                     hci_stack.substate = 0;
1127                     break;
1128                 case HCI_POWER_OFF:
1129                     // see hci_run
1130                     hci_stack.state = HCI_STATE_HALTING;
1131                     break;
1132                 case HCI_POWER_SLEEP:
1133                     // do nothing
1134                     break;
1135             }
1136             break;
1137 
1138         case HCI_STATE_SLEEPING:
1139             switch (power_mode){
1140                 case HCI_POWER_ON:
1141 
1142 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1143                     // nothing to do, if H4 supports power management
1144                     if (bt_control_iphone_power_management_enabled()){
1145                         hci_stack.state = HCI_STATE_INITIALIZING;
1146                         hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1147                         hci_update_scan_enable();
1148                         break;
1149                     }
1150 #endif
1151                     err = hci_power_control_wake();
1152                     if (err) return err;
1153                     // set up state machine
1154                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1155                     hci_stack.state = HCI_STATE_INITIALIZING;
1156                     hci_stack.substate = 0;
1157                     break;
1158                 case HCI_POWER_OFF:
1159                     hci_stack.state = HCI_STATE_HALTING;
1160                     break;
1161                 case HCI_POWER_SLEEP:
1162                     // do nothing
1163                     break;
1164             }
1165             break;
1166     }
1167 
1168     // create internal event
1169 	hci_emit_state();
1170 
1171 	// trigger next/first action
1172 	hci_run();
1173 
1174     return 0;
1175 }
1176 
1177 static void hci_update_scan_enable(void){
1178     // 2 = page scan, 1 = inq scan
1179     hci_stack.new_scan_enable_value  = hci_stack.connectable << 1 | hci_stack.discoverable;
1180     hci_run();
1181 }
1182 
1183 void hci_discoverable_control(uint8_t enable){
1184     if (enable) enable = 1; // normalize argument
1185 
1186     if (hci_stack.discoverable == enable){
1187         hci_emit_discoverable_enabled(hci_stack.discoverable);
1188         return;
1189     }
1190 
1191     hci_stack.discoverable = enable;
1192     hci_update_scan_enable();
1193 }
1194 
1195 void hci_connectable_control(uint8_t enable){
1196     if (enable) enable = 1; // normalize argument
1197 
1198     // don't emit event
1199     if (hci_stack.connectable == enable) return;
1200 
1201     hci_stack.connectable = enable;
1202     hci_update_scan_enable();
1203 }
1204 
1205 bd_addr_t * hci_local_bd_addr(void){
1206     return &hci_stack.local_bd_addr;
1207 }
1208 
1209 void hci_run(){
1210 
1211     hci_connection_t * connection;
1212     linked_item_t * it;
1213 
1214     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1215 
1216     // global/non-connection oriented commands
1217 
1218     // decline incoming connections
1219     if (hci_stack.decline_reason){
1220         uint8_t reason = hci_stack.decline_reason;
1221         hci_stack.decline_reason = 0;
1222         hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason);
1223         return;
1224     }
1225 
1226     // send scan enable
1227     if (hci_stack.state == HCI_STATE_WORKING && hci_stack.new_scan_enable_value != 0xff && hci_classic_supported()){
1228         hci_send_cmd(&hci_write_scan_enable, hci_stack.new_scan_enable_value);
1229         hci_stack.new_scan_enable_value = 0xff;
1230         return;
1231     }
1232 
1233     // send pending HCI commands
1234     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
1235 
1236         connection = (hci_connection_t *) it;
1237 
1238         if (connection->state == RECEIVED_CONNECTION_REQUEST){
1239             log_info("sending hci_accept_connection_request\n");
1240             connection->state = ACCEPTED_CONNECTION_REQUEST;
1241             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1242             return;
1243         }
1244 
1245         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1246             log_info("responding to link key request\n");
1247             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1248             link_key_t link_key;
1249             link_key_type_t link_key_type;
1250             if ( hci_stack.remote_device_db
1251               && hci_stack.remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1252               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
1253                connection->link_key_type = link_key_type;
1254                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1255             } else {
1256                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1257             }
1258             return;
1259         }
1260 
1261         if (connection->authentication_flags & HANDLE_PIN_CODE_REQUEST){
1262             log_info("denying to pin request\n");
1263             connectionClearAuthenticationFlags(connection, HANDLE_PIN_CODE_REQUEST);
1264             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1265             return;
1266         }
1267 
1268         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1269             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1270             if (hci_stack.bondable && hci_stack.ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){
1271                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack.ssp_io_capability, NULL, hci_stack.ssp_authentication_requirement);
1272             } else {
1273                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1274             }
1275             return;
1276         }
1277 
1278         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1279             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1280             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1281             return;
1282         }
1283 
1284         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1285             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1286             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1287             return;
1288         }
1289 
1290         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1291             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
1292             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
1293             return;
1294         }
1295 
1296         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
1297             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
1298             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
1299             return;
1300         }
1301         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
1302             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
1303             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
1304             return;
1305         }
1306         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1307             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1308             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1309             return;
1310         }
1311     }
1312 
1313     switch (hci_stack.state){
1314         case HCI_STATE_INITIALIZING:
1315             // log_info("hci_init: substate %u\n", hci_stack.substate);
1316             if (hci_stack.substate % 2) {
1317                 // odd: waiting for command completion
1318                 return;
1319             }
1320             switch (hci_stack.substate >> 1){
1321                 case 0: // RESET
1322                     hci_send_cmd(&hci_reset);
1323 
1324                     if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){
1325                         // skip baud change
1326                         hci_stack.substate = 4; // >> 1 = 2
1327                     }
1328                     break;
1329                 case 1: // SEND BAUD CHANGE
1330                     hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_packet_buffer);
1331                     hci_send_cmd_packet(hci_stack.hci_packet_buffer, 3 + hci_stack.hci_packet_buffer[2]);
1332                     break;
1333                 case 2: // LOCAL BAUD CHANGE
1334                     hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main);
1335                     hci_stack.substate += 2;
1336                     // break missing here for fall through
1337 
1338                 case 3:
1339                     // Custom initialization
1340                     if (hci_stack.control && hci_stack.control->next_cmd){
1341                         int valid_cmd = (*hci_stack.control->next_cmd)(hci_stack.config, hci_stack.hci_packet_buffer);
1342                         if (valid_cmd){
1343                             int size = 3 + hci_stack.hci_packet_buffer[2];
1344                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack.hci_packet_buffer, size);
1345                             hci_stack.substate = 4; // more init commands
1346                             break;
1347                         }
1348                         log_info("hci_run: init script done\n\r");
1349                     }
1350                     // otherwise continue
1351 					hci_send_cmd(&hci_read_bd_addr);
1352 					break;
1353 				case 4:
1354 					hci_send_cmd(&hci_read_buffer_size);
1355 					break;
1356                 case 5:
1357                     hci_send_cmd(&hci_read_local_supported_features);
1358                     break;
1359                 case 6:
1360                     if (hci_le_supported()){
1361                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1362                     } else {
1363                         // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1364                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1365                     }
1366 
1367                     // skip Classic init commands for LE only chipsets
1368                     if (!hci_classic_supported()){
1369                         if (hci_le_supported()){
1370                             hci_stack.substate = 11 << 1;    // skip all classic command
1371                         } else {
1372                             log_error("Neither BR/EDR nor LE supported");
1373                             hci_stack.substate = 13 << 1;    // skip all
1374                         }
1375                     }
1376                     break;
1377                 case 7:
1378                     if (hci_ssp_supported()){
1379                         hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack.ssp_enable);
1380                         break;
1381                     }
1382                     hci_stack.substate += 2;
1383                     // break missing here for fall through
1384 
1385                 case 8:
1386                     // ca. 15 sec
1387                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1388                     break;
1389                 case 9:
1390                     hci_send_cmd(&hci_write_class_of_device, hci_stack.class_of_device);
1391                     break;
1392                 case 10:
1393                     if (hci_stack.local_name){
1394                         hci_send_cmd(&hci_write_local_name, hci_stack.local_name);
1395                     } else {
1396                         char hostname[30];
1397 #ifdef EMBEDDED
1398                         // BTstack-11:22:33:44:55:66
1399                         strcpy(hostname, "BTstack ");
1400                         strcat(hostname, bd_addr_to_str(hci_stack.local_bd_addr));
1401                         printf("---> Name %s\n", hostname);
1402 #else
1403                         // hostname for POSIX systems
1404                         gethostname(hostname, 30);
1405                         hostname[29] = '\0';
1406 #endif
1407                         hci_send_cmd(&hci_write_local_name, hostname);
1408                     }
1409                     break;
1410                 case 11:
1411 					hci_send_cmd(&hci_write_scan_enable, (hci_stack.connectable << 1) | hci_stack.discoverable); // page scan
1412                     if (!hci_le_supported()){
1413                         // SKIP LE init for Classic only configuration
1414                         hci_stack.substate = 13 << 1;
1415                     }
1416 					break;
1417 
1418 #ifdef HAVE_BLE
1419                 // LE INIT
1420                 case 12:
1421                     hci_send_cmd(&hci_le_read_buffer_size);
1422                     break;
1423                 case 13:
1424                     // LE Supported Host = 1, Simultaneous Host = 0
1425                     hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1426                     break;
1427 #endif
1428 
1429                 // DONE
1430                 case 14:
1431                     // done.
1432                     hci_stack.state = HCI_STATE_WORKING;
1433                     hci_emit_state();
1434                     break;
1435                 default:
1436                     break;
1437             }
1438             hci_stack.substate++;
1439             break;
1440 
1441         case HCI_STATE_HALTING:
1442 
1443             log_info("HCI_STATE_HALTING\n");
1444             // close all open connections
1445             connection =  (hci_connection_t *) hci_stack.connections;
1446             if (connection){
1447 
1448                 // send disconnect
1449                 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1450 
1451                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1452                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1453 
1454                 // send disconnected event right away - causes higher layer connections to get closed, too.
1455                 hci_shutdown_connection(connection);
1456                 return;
1457             }
1458             log_info("HCI_STATE_HALTING, calling off\n");
1459 
1460             // switch mode
1461             hci_power_control_off();
1462 
1463             log_info("HCI_STATE_HALTING, emitting state\n");
1464             hci_emit_state();
1465             log_info("HCI_STATE_HALTING, done\n");
1466             break;
1467 
1468         case HCI_STATE_FALLING_ASLEEP:
1469             switch(hci_stack.substate) {
1470                 case 0:
1471                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1472                     // close all open connections
1473                     connection =  (hci_connection_t *) hci_stack.connections;
1474 
1475 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1476                     // don't close connections, if H4 supports power management
1477                     if (bt_control_iphone_power_management_enabled()){
1478                         connection = NULL;
1479                     }
1480 #endif
1481                     if (connection){
1482 
1483                         // send disconnect
1484                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1485 
1486                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1487                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1488 
1489                         // send disconnected event right away - causes higher layer connections to get closed, too.
1490                         hci_shutdown_connection(connection);
1491                         return;
1492                     }
1493 
1494                     if (hci_classic_supported()){
1495                         // disable page and inquiry scan
1496                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1497 
1498                         log_info("HCI_STATE_HALTING, disabling inq scans\n");
1499                         hci_send_cmd(&hci_write_scan_enable, hci_stack.connectable << 1); // drop inquiry scan but keep page scan
1500 
1501                         // continue in next sub state
1502                         hci_stack.substate++;
1503                         break;
1504                     }
1505                     // fall through for ble-only chips
1506 
1507                 case 2:
1508                     log_info("HCI_STATE_HALTING, calling sleep\n");
1509 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1510                     // don't actually go to sleep, if H4 supports power management
1511                     if (bt_control_iphone_power_management_enabled()){
1512                         // SLEEP MODE reached
1513                         hci_stack.state = HCI_STATE_SLEEPING;
1514                         hci_emit_state();
1515                         break;
1516                     }
1517 #endif
1518                     // switch mode
1519                     hci_power_control_sleep();  // changes hci_stack.state to SLEEP
1520                     hci_emit_state();
1521                     break;
1522 
1523                 default:
1524                     break;
1525             }
1526             break;
1527 
1528         default:
1529             break;
1530     }
1531 }
1532 
1533 int hci_send_cmd_packet(uint8_t *packet, int size){
1534     bd_addr_t addr;
1535     hci_connection_t * conn;
1536     // house-keeping
1537 
1538     // create_connection?
1539     if (IS_COMMAND(packet, hci_create_connection)){
1540         bt_flip_addr(addr, &packet[3]);
1541         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1542         conn = connection_for_address(addr);
1543         if (conn) {
1544             // if connection exists
1545             if (conn->state == OPEN) {
1546                 // and OPEN, emit connection complete command
1547                 hci_emit_connection_complete(conn, 0);
1548             }
1549             //    otherwise, just ignore as it is already in the open process
1550             return 0; // don't sent packet to controller
1551 
1552         }
1553         // create connection struct and register, state = SENT_CREATE_CONNECTION
1554         conn = create_connection_for_addr(addr);
1555         if (!conn){
1556             // notify client that alloc failed
1557             hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1558             return 0; // don't sent packet to controller
1559         }
1560         conn->state = SENT_CREATE_CONNECTION;
1561     }
1562 
1563     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1564         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1565     }
1566     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1567         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1568     }
1569 
1570     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1571         if (hci_stack.remote_device_db){
1572             bt_flip_addr(addr, &packet[3]);
1573             hci_stack.remote_device_db->delete_link_key(&addr);
1574         }
1575     }
1576 
1577 #ifdef HAVE_BLE
1578     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
1579         hci_stack.adv_addr_type = packet[8];
1580     }
1581     if (IS_COMMAND(packet, hci_le_set_random_address)){
1582         bt_flip_addr(hci_stack.adv_address, &packet[3]);
1583     }
1584 #endif
1585 
1586 
1587     hci_stack.num_cmd_packets--;
1588     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1589 }
1590 
1591 // disconnect because of security block
1592 void hci_disconnect_security_block(hci_con_handle_t con_handle){
1593     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1594     if (!connection) return;
1595     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
1596 }
1597 
1598 
1599 // Configure Secure Simple Pairing
1600 
1601 // enable will enable SSP during init
1602 void hci_ssp_set_enable(int enable){
1603     hci_stack.ssp_enable = enable;
1604 }
1605 
1606 int hci_local_ssp_activated(){
1607     return hci_ssp_supported() && hci_stack.ssp_enable;
1608 }
1609 
1610 // if set, BTstack will respond to io capability request using authentication requirement
1611 void hci_ssp_set_io_capability(int io_capability){
1612     hci_stack.ssp_io_capability = io_capability;
1613 }
1614 void hci_ssp_set_authentication_requirement(int authentication_requirement){
1615     hci_stack.ssp_authentication_requirement = authentication_requirement;
1616 }
1617 
1618 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
1619 void hci_ssp_set_auto_accept(int auto_accept){
1620     hci_stack.ssp_auto_accept = auto_accept;
1621 }
1622 
1623 /**
1624  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1625  */
1626 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1627     va_list argptr;
1628     va_start(argptr, cmd);
1629     uint16_t size = hci_create_cmd_internal(hci_stack.hci_packet_buffer, cmd, argptr);
1630     va_end(argptr);
1631     return hci_send_cmd_packet(hci_stack.hci_packet_buffer, size);
1632 }
1633 
1634 // Create various non-HCI events.
1635 // TODO: generalize, use table similar to hci_create_command
1636 
1637 void hci_emit_state(){
1638     log_info("BTSTACK_EVENT_STATE %u", hci_stack.state);
1639     uint8_t event[3];
1640     event[0] = BTSTACK_EVENT_STATE;
1641     event[1] = sizeof(event) - 2;
1642     event[2] = hci_stack.state;
1643     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1644     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1645 }
1646 
1647 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1648     uint8_t event[13];
1649     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1650     event[1] = sizeof(event) - 2;
1651     event[2] = status;
1652     bt_store_16(event, 3, conn->con_handle);
1653     bt_flip_addr(&event[5], conn->address);
1654     event[11] = 1; // ACL connection
1655     event[12] = 0; // encryption disabled
1656     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1657     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1658 }
1659 
1660 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1661     uint8_t event[6];
1662     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1663     event[1] = sizeof(event) - 2;
1664     event[2] = 0; // status = OK
1665     bt_store_16(event, 3, handle);
1666     event[5] = reason;
1667     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1668     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1669 }
1670 
1671 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1672     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
1673     uint8_t event[4];
1674     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1675     event[1] = sizeof(event) - 2;
1676     bt_store_16(event, 2, conn->con_handle);
1677     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1678     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1679 }
1680 
1681 void hci_emit_nr_connections_changed(){
1682     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
1683     uint8_t event[3];
1684     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1685     event[1] = sizeof(event) - 2;
1686     event[2] = nr_hci_connections();
1687     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1688     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1689 }
1690 
1691 void hci_emit_hci_open_failed(){
1692     log_info("BTSTACK_EVENT_POWERON_FAILED");
1693     uint8_t event[2];
1694     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1695     event[1] = sizeof(event) - 2;
1696     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1697     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1698 }
1699 
1700 #ifndef EMBEDDED
1701 void hci_emit_btstack_version() {
1702     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
1703     uint8_t event[6];
1704     event[0] = BTSTACK_EVENT_VERSION;
1705     event[1] = sizeof(event) - 2;
1706     event[2] = BTSTACK_MAJOR;
1707     event[3] = BTSTACK_MINOR;
1708     bt_store_16(event, 4, BTSTACK_REVISION);
1709     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1710     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1711 }
1712 #endif
1713 
1714 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1715     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
1716     uint8_t event[3];
1717     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1718     event[1] = sizeof(event) - 2;
1719     event[2] = enabled;
1720     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1721     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1722 }
1723 
1724 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1725     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
1726     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1727     event[1] = sizeof(event) - 2 - 1;
1728     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1729     bt_flip_addr(&event[3], *addr);
1730     memcpy(&event[9], name, 248);
1731 
1732     event[9+248] = 0;   // assert \0 for log_info
1733     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
1734 
1735     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
1736     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
1737 }
1738 
1739 void hci_emit_discoverable_enabled(uint8_t enabled){
1740     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
1741     uint8_t event[3];
1742     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1743     event[1] = sizeof(event) - 2;
1744     event[2] = enabled;
1745     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1746     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1747 }
1748 
1749 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
1750     uint8_t event[5];
1751     int pos = 0;
1752     event[pos++] = GAP_SECURITY_LEVEL;
1753     event[pos++] = sizeof(event) - 2;
1754     bt_store_16(event, 2, con_handle);
1755     pos += 2;
1756     event[pos++] = level;
1757     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1758     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1759 }
1760 
1761 // query if remote side supports SSP
1762 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
1763     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1764     if (!connection) return 0;
1765     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
1766 }
1767 
1768 // GAP API
1769 /**
1770  * @bbrief enable/disable bonding. default is enabled
1771  * @praram enabled
1772  */
1773 void gap_set_bondable_mode(int enable){
1774     hci_stack.bondable = enable ? 1 : 0;
1775 }
1776 
1777 /**
1778  * @brief map link keys to security levels
1779  */
1780 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
1781     switch (link_key_type){
1782         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
1783             return LEVEL_4;
1784         case COMBINATION_KEY:
1785         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
1786             return LEVEL_3;
1787         default:
1788             return LEVEL_2;
1789     }
1790 }
1791 
1792 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
1793     if (!connection) return LEVEL_0;
1794     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
1795     return gap_security_level_for_link_key_type(connection->link_key_type);
1796 }
1797 
1798 
1799 /**
1800  * @brief get current security level
1801  */
1802 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
1803     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1804     if (!connection) return LEVEL_0;
1805     return gap_security_level_for_connection(connection);
1806 }
1807 
1808 /**
1809  * @brief request connection to device to
1810  * @result GAP_AUTHENTICATION_RESULT
1811  */
1812 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
1813     hci_connection_t * connection = hci_connection_for_handle(con_handle);
1814     if (!connection){
1815         hci_emit_security_level(con_handle, LEVEL_0);
1816         return;
1817     }
1818     gap_security_level_t current_level = gap_security_level(con_handle);
1819     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
1820     if (current_level >= requested_level){
1821         hci_emit_security_level(con_handle, current_level);
1822         return;
1823     }
1824 
1825     connection->requested_security_level = requested_level;
1826 
1827     // would enabling ecnryption suffice?
1828     if (hci_stack.remote_device_db){
1829         link_key_type_t link_key_type;
1830         link_key_t      link_key;
1831         if (hci_stack.remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
1832             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
1833                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1834                 return;
1835             }
1836         }
1837     }
1838 
1839     // try to authenticate connection
1840     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1841     // connection->bonding_flags |= BONDING_REQUESTED;
1842 }
1843