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