xref: /btstack/src/hci.c (revision bb82004450cb1ccbd64bd4dbb2eb157d0c51b3f7)
1 /*
2  * Copyright (C) 2009-2012 by Matthias Ringwald
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at [email protected]
34  *
35  */
36 
37 /*
38  *  hci.c
39  *
40  *  Created by Matthias Ringwald on 4/29/09.
41  *
42  */
43 
44 #include "btstack-config.h"
45 
46 #include "hci.h"
47 #include "gap.h"
48 
49 #include <stdarg.h>
50 #include <string.h>
51 #include <stdio.h>
52 
53 #ifndef EMBEDDED
54 #ifdef _WIN32
55 #include "Winsock2.h"
56 #else
57 #include <unistd.h> // gethostbyname
58 #endif
59 #include <btstack/version.h>
60 #endif
61 
62 #include "btstack_memory.h"
63 #include "debug.h"
64 #include "hci_dump.h"
65 
66 #include <btstack/linked_list.h>
67 #include <btstack/hci_cmds.h>
68 
69 #define HCI_CONNECTION_TIMEOUT_MS 10000
70 
71 #define HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP 11
72 
73 #ifdef USE_BLUETOOL
74 #include "../platforms/ios/src/bt_control_iphone.h"
75 #endif
76 
77 static void hci_update_scan_enable(void);
78 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
79 static void hci_connection_timeout_handler(timer_source_t *timer);
80 static void hci_connection_timestamp(hci_connection_t *connection);
81 static int  hci_power_control_on(void);
82 static void hci_power_control_off(void);
83 static void hci_state_reset();
84 
85 // the STACK is here
86 #ifndef HAVE_MALLOC
87 static hci_stack_t   hci_stack_static;
88 #endif
89 static hci_stack_t * hci_stack = NULL;
90 
91 // test helper
92 static uint8_t disable_l2cap_timeouts = 0;
93 
94 /**
95  * create connection for given address
96  *
97  * @return connection OR NULL, if no memory left
98  */
99 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
100 
101     log_info("create_connection_for_addr %s", bd_addr_to_str(addr));
102     hci_connection_t * conn = btstack_memory_hci_connection_get();
103     if (!conn) return NULL;
104     BD_ADDR_COPY(conn->address, addr);
105     conn->address_type = addr_type;
106     conn->con_handle = 0xffff;
107     conn->authentication_flags = AUTH_FLAGS_NONE;
108     conn->bonding_flags = 0;
109     conn->requested_security_level = LEVEL_0;
110     linked_item_set_user(&conn->timeout.item, conn);
111     conn->timeout.process = hci_connection_timeout_handler;
112     hci_connection_timestamp(conn);
113     conn->acl_recombination_length = 0;
114     conn->acl_recombination_pos = 0;
115     conn->num_acl_packets_sent = 0;
116     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
117     linked_list_add(&hci_stack->connections, (linked_item_t *) conn);
118     return conn;
119 }
120 
121 
122 /**
123  * get le connection parameter range
124 *
125  * @return le connection parameter range struct
126  */
127 le_connection_parameter_range_t gap_le_get_connection_parameter_range(){
128     return hci_stack->le_connection_parameter_range;
129 }
130 
131 /**
132  * set le connection parameter range
133  *
134  */
135 
136 void gap_le_set_connection_parameter_range(le_connection_parameter_range_t range){
137     hci_stack->le_connection_parameter_range.le_conn_interval_min = range.le_conn_interval_min;
138     hci_stack->le_connection_parameter_range.le_conn_interval_max = range.le_conn_interval_max;
139     hci_stack->le_connection_parameter_range.le_conn_interval_min = range.le_conn_latency_min;
140     hci_stack->le_connection_parameter_range.le_conn_interval_max = range.le_conn_latency_max;
141     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = range.le_supervision_timeout_min;
142     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = range.le_supervision_timeout_max;
143 }
144 
145 /**
146  * get hci connections iterator
147  *
148  * @return hci connections iterator
149  */
150 
151 void hci_connections_get_iterator(linked_list_iterator_t *it){
152     linked_list_iterator_init(it, &hci_stack->connections);
153 }
154 
155 /**
156  * get connection for a given handle
157  *
158  * @return connection OR NULL, if not found
159  */
160 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
161     linked_list_iterator_t it;
162     linked_list_iterator_init(&it, &hci_stack->connections);
163     while (linked_list_iterator_has_next(&it)){
164         hci_connection_t * item = (hci_connection_t *) linked_list_iterator_next(&it);
165         if ( item->con_handle == con_handle ) {
166             return item;
167         }
168     }
169     return NULL;
170 }
171 
172 /**
173  * get connection for given address
174  *
175  * @return connection OR NULL, if not found
176  */
177 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t * addr, bd_addr_type_t addr_type){
178     linked_list_iterator_t it;
179     linked_list_iterator_init(&it, &hci_stack->connections);
180     while (linked_list_iterator_has_next(&it)){
181         hci_connection_t * connection = (hci_connection_t *) linked_list_iterator_next(&it);
182         if (connection->address_type != addr_type)  continue;
183         if (memcmp(addr, connection->address, 6) != 0) continue;
184         return connection;
185     }
186     return NULL;
187 }
188 
189 static void hci_connection_timeout_handler(timer_source_t *timer){
190     hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item);
191 #ifdef HAVE_TIME
192     struct timeval tv;
193     gettimeofday(&tv, NULL);
194     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
195         // connections might be timed out
196         hci_emit_l2cap_check_timeout(connection);
197     }
198 #endif
199 #ifdef HAVE_TICK
200     if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
201         // connections might be timed out
202         hci_emit_l2cap_check_timeout(connection);
203     }
204 #endif
205     run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
206     run_loop_add_timer(timer);
207 }
208 
209 static void hci_connection_timestamp(hci_connection_t *connection){
210 #ifdef HAVE_TIME
211     gettimeofday(&connection->timestamp, NULL);
212 #endif
213 #ifdef HAVE_TICK
214     connection->timestamp = embedded_get_ticks();
215 #endif
216 }
217 
218 
219 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
220     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
221 }
222 
223 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
224     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
225 }
226 
227 
228 /**
229  * add authentication flags and reset timer
230  * @note: assumes classic connection
231  */
232 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
233     bd_addr_t addr;
234     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
235     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
236     if (conn) {
237         connectionSetAuthenticationFlags(conn, flags);
238         hci_connection_timestamp(conn);
239     }
240 }
241 
242 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
243     hci_connection_t * conn = hci_connection_for_handle(handle);
244     if (!conn) return 0;
245     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
246     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
247     return 0;
248 }
249 
250 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
251     if (hci_stack->remote_device_db) {
252         hci_stack->remote_device_db->delete_link_key(addr);
253     }
254 }
255 
256 int hci_is_le_connection(hci_connection_t * connection){
257     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
258     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
259 }
260 
261 
262 /**
263  * count connections
264  */
265 static int nr_hci_connections(void){
266     int count = 0;
267     linked_item_t *it;
268     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
269     return count;
270 }
271 
272 /**
273  * Dummy handler called by HCI
274  */
275 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
276 }
277 
278 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
279     hci_connection_t * connection = hci_connection_for_handle(handle);
280     if (!connection) {
281         log_error("hci_number_outgoing_packets: connection for handle %u does not exist!", handle);
282         return 0;
283     }
284     return connection->num_acl_packets_sent;
285 }
286 
287 uint8_t hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
288 
289     int num_packets_sent_classic = 0;
290     int num_packets_sent_le = 0;
291 
292     bd_addr_type_t address_type = BD_ADDR_TYPE_UNKNOWN;
293 
294     linked_item_t *it;
295     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
296         hci_connection_t * connection = (hci_connection_t *) it;
297         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
298             num_packets_sent_classic += connection->num_acl_packets_sent;
299         } else {
300             num_packets_sent_le += connection->num_acl_packets_sent;
301         }
302         if (connection->con_handle == con_handle){
303             address_type = connection->address_type;
304         }
305     }
306 
307     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
308     int free_slots_le = 0;
309 
310     if (free_slots_classic < 0){
311         log_error("hci_number_free_acl_slots: outgoing classic packets (%u) > total classic packets (%u)", num_packets_sent_classic, hci_stack->acl_packets_total_num);
312         return 0;
313     }
314 
315     if (hci_stack->le_acl_packets_total_num){
316         // if we have LE slots, they are used
317         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
318         if (free_slots_le < 0){
319             log_error("hci_number_free_acl_slots: outgoing le packets (%u) > total le packets (%u)", num_packets_sent_le, hci_stack->le_acl_packets_total_num);
320             return 0;
321         }
322     } else {
323         // otherwise, classic slots are used for LE, too
324         free_slots_classic -= num_packets_sent_le;
325         if (free_slots_classic < 0){
326             log_error("hci_number_free_acl_slots: outgoing classic + le packets (%u + %u) > total packets (%u)", num_packets_sent_classic, num_packets_sent_le, hci_stack->acl_packets_total_num);
327             return 0;
328         }
329     }
330 
331     switch (address_type){
332         case BD_ADDR_TYPE_UNKNOWN:
333             log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
334             return 0;
335 
336         case BD_ADDR_TYPE_CLASSIC:
337             return free_slots_classic;
338 
339         default:
340            if (hci_stack->le_acl_packets_total_num){
341                return free_slots_le;
342            }
343            return free_slots_classic;
344     }
345 }
346 
347 
348 // @deprecated
349 int hci_can_send_packet_now(uint8_t packet_type){
350     switch (packet_type) {
351         case HCI_ACL_DATA_PACKET:
352             return hci_can_send_prepared_acl_packet_now(0);
353         case HCI_COMMAND_DATA_PACKET:
354             return hci_can_send_command_packet_now();
355         default:
356             return 0;
357     }
358 }
359 
360 // @deprecated
361 // same as hci_can_send_packet_now, but also checks if packet buffer is free for use
362 int hci_can_send_packet_now_using_packet_buffer(uint8_t packet_type){
363 
364     if (hci_stack->hci_packet_buffer_reserved) return 0;
365 
366     switch (packet_type) {
367         case HCI_ACL_DATA_PACKET:
368             return hci_can_send_acl_packet_now(0);
369         case HCI_COMMAND_DATA_PACKET:
370             return hci_can_send_command_packet_now();
371         default:
372             return 0;
373     }
374 }
375 
376 
377 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
378 int hci_can_send_command_packet_now(void){
379     if (hci_stack->hci_packet_buffer_reserved) return 0;
380 
381     // check for async hci transport implementations
382     if (hci_stack->hci_transport->can_send_packet_now){
383         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
384             return 0;
385         }
386     }
387 
388     return hci_stack->num_cmd_packets > 0;
389 }
390 
391 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
392     // check for async hci transport implementations
393     if (hci_stack->hci_transport->can_send_packet_now){
394         if (!hci_stack->hci_transport->can_send_packet_now(HCI_ACL_DATA_PACKET)){
395             return 0;
396         }
397     }
398     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
399 }
400 
401 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
402     if (hci_stack->hci_packet_buffer_reserved) return 0;
403     return hci_can_send_prepared_acl_packet_now(con_handle);
404 }
405 
406 // used for internal checks in l2cap[-le].c
407 int hci_is_packet_buffer_reserved(void){
408     return hci_stack->hci_packet_buffer_reserved;
409 }
410 
411 // reserves outgoing packet buffer. @returns 1 if successful
412 int hci_reserve_packet_buffer(void){
413     if (hci_stack->hci_packet_buffer_reserved) {
414         log_error("hci_reserve_packet_buffer called but buffer already reserved");
415         return 0;
416     }
417     hci_stack->hci_packet_buffer_reserved = 1;
418     return 1;
419 }
420 
421 void hci_release_packet_buffer(void){
422     hci_stack->hci_packet_buffer_reserved = 0;
423 }
424 
425 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
426 int hci_transport_synchronous(void){
427     return hci_stack->hci_transport->can_send_packet_now == NULL;
428 }
429 
430 uint16_t hci_max_acl_le_data_packet_length(void){
431     return hci_stack->le_data_packets_length > 0 ? hci_stack->le_data_packets_length : hci_stack->acl_data_packet_length;
432 }
433 
434 static int hci_send_acl_packet_fragments(hci_connection_t *connection){
435 
436     // log_info("hci_send_acl_packet_fragments  %u/%u (con 0x%04x)", hci_stack->acl_fragmentation_pos, hci_stack->acl_fragmentation_total_size, connection->con_handle);
437 
438     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
439     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
440     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
441         max_acl_data_packet_length = hci_stack->le_data_packets_length;
442     }
443 
444     // testing: reduce buffer to minimum
445     // max_acl_data_packet_length = 52;
446 
447     int err;
448     // multiple packets could be send on a synchronous HCI transport
449     while (1){
450 
451         // get current data
452         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
453         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
454         int more_fragments = 0;
455 
456         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
457         if (current_acl_data_packet_length > max_acl_data_packet_length){
458             more_fragments = 1;
459             current_acl_data_packet_length = max_acl_data_packet_length;
460         }
461 
462         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
463         if (acl_header_pos > 0){
464             uint16_t handle_and_flags = READ_BT_16(hci_stack->hci_packet_buffer, 0);
465             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
466             bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
467         }
468 
469         // update header len
470         bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
471 
472         // count packet
473         connection->num_acl_packets_sent++;
474 
475         // send packet
476         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
477         const int size = current_acl_data_packet_length + 4;
478         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
479         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
480 
481         // done yet?
482         if (!more_fragments) break;
483 
484         // update start of next fragment to send
485         hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
486 
487         // can send more?
488         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
489     }
490 
491     // done
492     hci_stack->acl_fragmentation_pos = 0;
493     hci_stack->acl_fragmentation_total_size = 0;
494 
495     // release buffer now for synchronous transport
496     if (hci_transport_synchronous()){
497         hci_release_packet_buffer();
498     }
499 
500     return err;
501 }
502 
503 // pre: caller has reserved the packet buffer
504 int hci_send_acl_packet_buffer(int size){
505 
506     // log_info("hci_send_acl_packet_buffer size %u", size);
507 
508     if (!hci_stack->hci_packet_buffer_reserved) {
509         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
510         return 0;
511     }
512 
513     uint8_t * packet = hci_stack->hci_packet_buffer;
514     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
515 
516     // check for free places on Bluetooth module
517     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
518         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
519         hci_release_packet_buffer();
520         return BTSTACK_ACL_BUFFERS_FULL;
521     }
522 
523     hci_connection_t *connection = hci_connection_for_handle( con_handle);
524     if (!connection) {
525         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
526         hci_release_packet_buffer();
527         return 0;
528     }
529     hci_connection_timestamp(connection);
530 
531     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
532 
533     // setup data
534     hci_stack->acl_fragmentation_total_size = size;
535     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
536 
537     return hci_send_acl_packet_fragments(connection);
538 }
539 
540 static void acl_handler(uint8_t *packet, int size){
541 
542     // log_info("acl_handler: size %u", size);
543 
544     // get info
545     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
546     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
547     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
548     uint16_t acl_length         = READ_ACL_LENGTH(packet);
549 
550     // ignore non-registered handle
551     if (!conn){
552         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
553         return;
554     }
555 
556     // assert packet is complete
557     if (acl_length + 4 != size){
558         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
559         return;
560     }
561 
562     // update idle timestamp
563     hci_connection_timestamp(conn);
564 
565     // handle different packet types
566     switch (acl_flags & 0x03) {
567 
568         case 0x01: // continuation fragment
569 
570             // sanity check
571             if (conn->acl_recombination_pos == 0) {
572                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
573                 return;
574             }
575 
576             // append fragment payload (header already stored)
577             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
578             conn->acl_recombination_pos += acl_length;
579 
580             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
581             //        conn->acl_recombination_pos, conn->acl_recombination_length);
582 
583             // forward complete L2CAP packet if complete.
584             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
585 
586                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, &conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
587                 // reset recombination buffer
588                 conn->acl_recombination_length = 0;
589                 conn->acl_recombination_pos = 0;
590             }
591             break;
592 
593         case 0x02: { // first fragment
594 
595             // sanity check
596             if (conn->acl_recombination_pos) {
597                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x", con_handle);
598                 return;
599             }
600 
601             // peek into L2CAP packet!
602             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
603 
604             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
605 
606             // compare fragment size to L2CAP packet size
607             if (acl_length >= l2cap_length + 4){
608 
609                 // forward fragment as L2CAP packet
610                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
611 
612             } else {
613                 // store first fragment and tweak acl length for complete package
614                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
615                 conn->acl_recombination_pos    = acl_length + 4;
616                 conn->acl_recombination_length = l2cap_length;
617                 bt_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
618             }
619             break;
620 
621         }
622         default:
623             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
624             return;
625     }
626 
627     // execute main loop
628     hci_run();
629 }
630 
631 static void hci_shutdown_connection(hci_connection_t *conn){
632     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
633 
634     run_loop_remove_timer(&conn->timeout);
635 
636     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
637     btstack_memory_hci_connection_free( conn );
638 
639     // now it's gone
640     hci_emit_nr_connections_changed();
641 }
642 
643 static const uint16_t packet_type_sizes[] = {
644     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
645     HCI_ACL_DH1_SIZE, 0, 0, 0,
646     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
647     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
648 };
649 static const uint8_t  packet_type_feature_requirement_bit[] = {
650      0, // 3 slot packets
651      1, // 5 slot packets
652     25, // EDR 2 mpbs
653     26, // EDR 3 mbps
654     39, // 3 slot EDR packts
655     40, // 5 slot EDR packet
656 };
657 static const uint16_t packet_type_feature_packet_mask[] = {
658     0x0f00, // 3 slot packets
659     0xf000, // 5 slot packets
660     0x1102, // EDR 2 mpbs
661     0x2204, // EDR 3 mbps
662     0x0300, // 3 slot EDR packts
663     0x3000, // 5 slot EDR packet
664 };
665 
666 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
667     // enable packet types based on size
668     uint16_t packet_types = 0;
669     unsigned int i;
670     for (i=0;i<16;i++){
671         if (packet_type_sizes[i] == 0) continue;
672         if (packet_type_sizes[i] <= buffer_size){
673             packet_types |= 1 << i;
674         }
675     }
676     // disable packet types due to missing local supported features
677     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
678         int bit_idx = packet_type_feature_requirement_bit[i];
679         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
680         if (feature_set) continue;
681         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
682         packet_types &= ~packet_type_feature_packet_mask[i];
683     }
684     // flip bits for "may not be used"
685     packet_types ^= 0x3306;
686     return packet_types;
687 }
688 
689 uint16_t hci_usable_acl_packet_types(void){
690     return hci_stack->packet_types;
691 }
692 
693 uint8_t* hci_get_outgoing_packet_buffer(void){
694     // hci packet buffer is >= acl data packet length
695     return hci_stack->hci_packet_buffer;
696 }
697 
698 uint16_t hci_max_acl_data_packet_length(void){
699     return hci_stack->acl_data_packet_length;
700 }
701 
702 int hci_non_flushable_packet_boundary_flag_supported(void){
703     // No. 54, byte 6, bit 6
704     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
705 }
706 
707 int hci_ssp_supported(void){
708     // No. 51, byte 6, bit 3
709     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
710 }
711 
712 int hci_classic_supported(void){
713     // No. 37, byte 4, bit 5, = No BR/EDR Support
714     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
715 }
716 
717 int hci_le_supported(void){
718 #ifdef HAVE_BLE
719     // No. 37, byte 4, bit 6 = LE Supported (Controller)
720     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
721 #else
722     return 0;
723 #endif
724 }
725 
726 // get addr type and address used in advertisement packets
727 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){
728     *addr_type = hci_stack->adv_addr_type;
729     if (hci_stack->adv_addr_type){
730         memcpy(addr, hci_stack->adv_address, 6);
731     } else {
732         memcpy(addr, hci_stack->local_bd_addr, 6);
733     }
734 }
735 
736 #ifdef HAVE_BLE
737 void le_handle_advertisement_report(uint8_t *packet, int size){
738     int offset = 3;
739     int num_reports = packet[offset];
740     offset += 1;
741 
742     int i;
743     log_info("HCI: handle adv report with num reports: %d", num_reports);
744     for (i=0; i<num_reports;i++){
745         uint8_t data_length = packet[offset + 8];
746         uint8_t event_size = 10 + data_length;
747         uint8_t event[2 + event_size ];
748         int pos = 0;
749         event[pos++] = GAP_LE_ADVERTISING_REPORT;
750         event[pos++] = event_size;
751         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
752         offset += 8;
753         pos += 8;
754         event[pos++] = packet[offset + 1 + data_length]; // rssi
755         event[pos++] = packet[offset++]; //data_length;
756         memcpy(&event[pos], &packet[offset], data_length);
757         pos += data_length;
758         offset += data_length + 1; // rssi
759         hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
760         hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
761     }
762 }
763 #endif
764 
765 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
766     uint8_t command_completed = 0;
767     if ((hci_stack->substate % 2) == 0) return;
768     // odd: waiting for event
769     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
770         uint16_t opcode = READ_BT_16(packet,3);
771         if (opcode == hci_stack->last_cmd_opcode){
772             command_completed = 1;
773             log_info("Command complete for expected opcode %04x -> new substate %u", opcode, hci_stack->substate);
774         } else {
775             log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
776         }
777     }
778     if (packet[0] == HCI_EVENT_COMMAND_STATUS){
779         uint8_t  status = packet[2];
780         uint16_t opcode = READ_BT_16(packet,4);
781         if (opcode == hci_stack->last_cmd_opcode){
782             if (status){
783                 command_completed = 1;
784                 log_error("Command status error 0x%02x for expected opcode %04x -> new substate %u", status, opcode, hci_stack->substate);
785             } else {
786                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
787             }
788         } else {
789             log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
790         }
791     }
792 
793     if (!command_completed) return;
794 
795     switch(hci_stack->substate >> 1){
796         default:
797             hci_stack->substate++;
798             break;
799     }
800 }
801 
802 static void hci_initializing_state_machine(){
803         // log_info("hci_init: substate %u", hci_stack->substate);
804     if (hci_stack->substate % 2) {
805         // odd: waiting for command completion
806         return;
807     }
808     switch (hci_stack->substate >> 1){
809         case 0: // RESET
810             hci_state_reset();
811 
812             hci_send_cmd(&hci_reset);
813             if (hci_stack->config == NULL || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
814                 // skip baud change
815                 hci_stack->substate = 4; // >> 1 = 2
816             }
817             break;
818         case 1: // SEND BAUD CHANGE
819             hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
820             hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
821             hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
822             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
823             break;
824         case 2: // LOCAL BAUD CHANGE
825             log_info("Local baud rate change");
826             hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
827             hci_stack->substate += 2;
828             // break missing here for fall through
829 
830         case 3:
831             log_info("Custom init");
832             // Custom initialization
833             if (hci_stack->control && hci_stack->control->next_cmd){
834                 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
835                 if (valid_cmd){
836                     int size = 3 + hci_stack->hci_packet_buffer[2];
837                     hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
838                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
839                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
840                     hci_stack->substate = 4; // more init commands
841                     break;
842                 }
843                 log_info("hci_run: init script done");
844             }
845             // otherwise continue
846             hci_send_cmd(&hci_read_bd_addr);
847             break;
848         case 4:
849             hci_send_cmd(&hci_read_buffer_size);
850             break;
851         case 5:
852             hci_send_cmd(&hci_read_local_supported_features);
853             break;
854         case 6:
855             if (hci_le_supported()){
856                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
857             } else {
858                 // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
859                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
860             }
861 
862             // skip Classic init commands for LE only chipsets
863             if (!hci_classic_supported()){
864                 if (hci_le_supported()){
865                     hci_stack->substate = 11 << 1;    // skip all classic command
866                 } else {
867                     log_error("Neither BR/EDR nor LE supported");
868                     hci_stack->substate = 14 << 1;    // skip all
869                 }
870             }
871             break;
872         case 7:
873             if (hci_ssp_supported()){
874                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
875                 break;
876             }
877             hci_stack->substate += 2;
878             // break missing here for fall through
879 
880         case 8:
881             // ca. 15 sec
882             hci_send_cmd(&hci_write_page_timeout, 0x6000);
883             break;
884         case 9:
885             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
886             break;
887         case 10:
888             if (hci_stack->local_name){
889                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
890             } else {
891                 char hostname[30];
892 #ifdef EMBEDDED
893                 // BTstack-11:22:33:44:55:66
894                 strcpy(hostname, "BTstack ");
895                 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr));
896                 log_info("---> Name %s", hostname);
897 #else
898                 // hostname for POSIX systems
899                 gethostname(hostname, 30);
900                 hostname[29] = '\0';
901 #endif
902                 hci_send_cmd(&hci_write_local_name, hostname);
903             }
904             break;
905         case 11:
906             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
907             if (!hci_le_supported()){
908                 // SKIP LE init for Classic only configuration
909                 hci_stack->substate = 14 << 1;
910             }
911             break;
912 
913 #ifdef HAVE_BLE
914         // LE INIT
915         case 12:
916             hci_send_cmd(&hci_le_read_buffer_size);
917             break;
918         case 13:
919             // LE Supported Host = 1, Simultaneous Host = 0
920             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
921             break;
922         case 14:
923             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs
924             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0);
925             break;
926 #endif
927 
928         // DONE
929         case 15:
930             // done.
931             hci_stack->state = HCI_STATE_WORKING;
932             hci_emit_state();
933             break;
934         default:
935             break;
936     }
937     hci_stack->substate++;
938 }
939 
940 // avoid huge local variables
941 #ifndef EMBEDDED
942 static device_name_t device_name;
943 #endif
944 static void event_handler(uint8_t *packet, int size){
945 
946     uint16_t event_length = packet[1];
947 
948     // assert packet is complete
949     if (size != event_length + 2){
950         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
951         return;
952     }
953 
954     bd_addr_t addr;
955     bd_addr_type_t addr_type;
956     uint8_t link_type;
957     hci_con_handle_t handle;
958     hci_connection_t * conn;
959     int i;
960 
961     // log_info("HCI:EVENT:%02x", packet[0]);
962 
963     switch (packet[0]) {
964 
965         case HCI_EVENT_COMMAND_COMPLETE:
966             // get num cmd packets
967             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]);
968             hci_stack->num_cmd_packets = packet[2];
969 
970             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
971                 // from offset 5
972                 // status
973                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
974                 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6);
975                 // ignore: SCO data packet len (8)
976                 hci_stack->acl_packets_total_num  = packet[9];
977                 // ignore: total num SCO packets
978                 if (hci_stack->state == HCI_STATE_INITIALIZING){
979                     // determine usable ACL payload size
980                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
981                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
982                     }
983                     log_info("hci_read_buffer_size: used size %u, count %u",
984                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num);
985                 }
986             }
987 #ifdef HAVE_BLE
988             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){
989                 hci_stack->le_data_packets_length = READ_BT_16(packet, 6);
990                 hci_stack->le_acl_packets_total_num  = packet[8];
991                     // determine usable ACL payload size
992                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
993                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
994                     }
995                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
996             }
997 #endif
998             // Dump local address
999             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
1000                 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
1001                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1002                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1003             }
1004             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1005                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1006             }
1007             // Note: HCI init checks
1008             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
1009                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1010                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
1011                     hci_stack->local_supported_features[0], hci_stack->local_supported_features[1],
1012                     hci_stack->local_supported_features[2], hci_stack->local_supported_features[3],
1013                     hci_stack->local_supported_features[4], hci_stack->local_supported_features[5],
1014                     hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]);
1015 
1016                 // determine usable ACL packet types based buffer size and supported features
1017                 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]);
1018                 log_info("packet types %04x", hci_stack->packet_types);
1019 
1020                 // Classic/LE
1021                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1022             }
1023             break;
1024 
1025         case HCI_EVENT_COMMAND_STATUS:
1026             // get num cmd packets
1027             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]);
1028             hci_stack->num_cmd_packets = packet[3];
1029             break;
1030 
1031         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1032             int offset = 3;
1033             for (i=0; i<packet[2];i++){
1034                 handle = READ_BT_16(packet, offset);
1035                 offset += 2;
1036                 uint16_t num_packets = READ_BT_16(packet, offset);
1037                 offset += 2;
1038 
1039                 conn = hci_connection_for_handle(handle);
1040                 if (!conn){
1041                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1042                     continue;
1043                 }
1044 
1045                 if (conn->num_acl_packets_sent >= num_packets){
1046                     conn->num_acl_packets_sent -= num_packets;
1047                 } else {
1048                     log_error("hci_number_completed_packets, more slots freed then sent.");
1049                     conn->num_acl_packets_sent = 0;
1050                 }
1051                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1052             }
1053             break;
1054         }
1055         case HCI_EVENT_CONNECTION_REQUEST:
1056             bt_flip_addr(addr, &packet[2]);
1057             // TODO: eval COD 8-10
1058             link_type = packet[11];
1059             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1060             if (link_type == 1) { // ACL
1061                 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1062                 if (!conn) {
1063                     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1064                 }
1065                 if (!conn) {
1066                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1067                     hci_stack->decline_reason = 0x0d;
1068                     BD_ADDR_COPY(hci_stack->decline_addr, addr);
1069                     break;
1070                 }
1071                 conn->state = RECEIVED_CONNECTION_REQUEST;
1072                 hci_run();
1073             } else {
1074                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
1075                 hci_stack->decline_reason = 0x0a;
1076                 BD_ADDR_COPY(hci_stack->decline_addr, addr);
1077             }
1078             break;
1079 
1080         case HCI_EVENT_CONNECTION_COMPLETE:
1081             // Connection management
1082             bt_flip_addr(addr, &packet[5]);
1083             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1084             addr_type = BD_ADDR_TYPE_CLASSIC;
1085             conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1086             if (conn) {
1087                 if (!packet[2]){
1088                     conn->state = OPEN;
1089                     conn->con_handle = READ_BT_16(packet, 3);
1090                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1091 
1092                     // restart timer
1093                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1094                     run_loop_add_timer(&conn->timeout);
1095 
1096                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1097 
1098                     hci_emit_nr_connections_changed();
1099                 } else {
1100                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1101                     uint8_t status = packet[2];
1102                     bd_addr_t bd_address;
1103                     memcpy(&bd_address, conn->address, 6);
1104 
1105                     // connection failed, remove entry
1106                     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1107                     btstack_memory_hci_connection_free( conn );
1108 
1109                     // notify client if dedicated bonding
1110                     if (notify_dedicated_bonding_failed){
1111                         log_info("hci notify_dedicated_bonding_failed");
1112                         hci_emit_dedicated_bonding_result(bd_address, status);
1113                     }
1114 
1115                     // if authentication error, also delete link key
1116                     if (packet[2] == 0x05) {
1117                         hci_drop_link_key_for_bd_addr(&addr);
1118                     }
1119                 }
1120             }
1121             break;
1122 
1123         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1124             handle = READ_BT_16(packet, 3);
1125             conn = hci_connection_for_handle(handle);
1126             if (!conn) break;
1127             if (!packet[2]){
1128                 uint8_t * features = &packet[5];
1129                 if (features[6] & (1 << 3)){
1130                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1131                 }
1132             }
1133             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1134             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags);
1135             if (conn->bonding_flags & BONDING_DEDICATED){
1136                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1137             }
1138             break;
1139 
1140         case HCI_EVENT_LINK_KEY_REQUEST:
1141             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1142             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1143             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1144             if (hci_stack->bondable && !hci_stack->remote_device_db) break;
1145             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1146             hci_run();
1147             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1148             return;
1149 
1150         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1151             bt_flip_addr(addr, &packet[2]);
1152             conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1153             if (!conn) break;
1154             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1155             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1156             // Change Connection Encryption keeps link key type
1157             if (link_key_type != CHANGED_COMBINATION_KEY){
1158                 conn->link_key_type = link_key_type;
1159             }
1160             if (!hci_stack->remote_device_db) break;
1161             hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type);
1162             // still forward event to allow dismiss of pairing dialog
1163             break;
1164         }
1165 
1166         case HCI_EVENT_PIN_CODE_REQUEST:
1167             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1168             // non-bondable mode: pin code negative reply will be sent
1169             if (!hci_stack->bondable){
1170                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1171                 hci_run();
1172                 return;
1173             }
1174             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1175             if (!hci_stack->remote_device_db) break;
1176             bt_flip_addr(addr, &packet[2]);
1177             hci_stack->remote_device_db->delete_link_key(&addr);
1178             break;
1179 
1180         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1181             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1182             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1183             break;
1184 
1185         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
1186             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1187             if (!hci_stack->ssp_auto_accept) break;
1188             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1189             break;
1190 
1191         case HCI_EVENT_USER_PASSKEY_REQUEST:
1192             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1193             if (!hci_stack->ssp_auto_accept) break;
1194             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1195             break;
1196 
1197         case HCI_EVENT_ENCRYPTION_CHANGE:
1198             handle = READ_BT_16(packet, 3);
1199             conn = hci_connection_for_handle(handle);
1200             if (!conn) break;
1201             if (packet[2] == 0) {
1202                 if (packet[5]){
1203                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1204                 } else {
1205                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1206                 }
1207             }
1208             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1209             break;
1210 
1211         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1212             handle = READ_BT_16(packet, 3);
1213             conn = hci_connection_for_handle(handle);
1214             if (!conn) break;
1215 
1216             // dedicated bonding: send result and disconnect
1217             if (conn->bonding_flags & BONDING_DEDICATED){
1218                 conn->bonding_flags &= ~BONDING_DEDICATED;
1219                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1220                 conn->bonding_status = packet[2];
1221                 break;
1222             }
1223 
1224             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1225                 // link key sufficient for requested security
1226                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1227                 break;
1228             }
1229             // not enough
1230             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1231             break;
1232 
1233 #ifndef EMBEDDED
1234         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1235             if (!hci_stack->remote_device_db) break;
1236             if (packet[2]) break; // status not ok
1237             bt_flip_addr(addr, &packet[3]);
1238             // fix for invalid remote names - terminate on 0xff
1239             for (i=0; i<248;i++){
1240                 if (packet[9+i] == 0xff){
1241                     packet[9+i] = 0;
1242                     break;
1243                 }
1244             }
1245             memset(&device_name, 0, sizeof(device_name_t));
1246             strncpy((char*) device_name, (char*) &packet[9], 248);
1247             hci_stack->remote_device_db->put_name(&addr, &device_name);
1248             break;
1249 
1250         case HCI_EVENT_INQUIRY_RESULT:
1251         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{
1252             if (!hci_stack->remote_device_db) break;
1253             // first send inq result packet
1254             hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1255             // then send cached remote names
1256             int offset = 3;
1257             for (i=0; i<packet[2];i++){
1258                 bt_flip_addr(addr, &packet[offset]);
1259                 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2;
1260                 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){
1261                     hci_emit_remote_name_cached(&addr, &device_name);
1262                 }
1263             }
1264             return;
1265         }
1266 #endif
1267 
1268         // HCI_EVENT_DISCONNECTION_COMPLETE
1269         // has been moved down, to first notify stack before shutting connection down
1270 
1271         case HCI_EVENT_HARDWARE_ERROR:
1272             if(hci_stack->control && hci_stack->control->hw_error){
1273                 (*hci_stack->control->hw_error)();
1274             } else {
1275                 // if no special requests, just reboot stack
1276                 hci_power_control_off();
1277                 hci_power_control_on();
1278             }
1279             break;
1280 
1281         case DAEMON_EVENT_HCI_PACKET_SENT:
1282             // release packet buffer only for asynchronous transport and if there are not further fragements
1283             if (hci_transport_synchronous()) break;
1284             if (hci_stack->acl_fragmentation_total_size) break;
1285             hci_release_packet_buffer();
1286             break;
1287 
1288 #ifdef HAVE_BLE
1289         case HCI_EVENT_LE_META:
1290             switch (packet[2]){
1291                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1292                     log_info("advertising report received");
1293                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1294                     le_handle_advertisement_report(packet, size);
1295                     break;
1296                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1297                     // Connection management
1298                     bt_flip_addr(addr, &packet[8]);
1299                     addr_type = (bd_addr_type_t)packet[7];
1300                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
1301                     // LE connections are auto-accepted, so just create a connection if there isn't one already
1302                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1303                     if (packet[3]){
1304                         if (conn){
1305                             // outgoing connection failed, remove entry
1306                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1307                             btstack_memory_hci_connection_free( conn );
1308                         }
1309                         // if authentication error, also delete link key
1310                         if (packet[3] == 0x05) {
1311                             hci_drop_link_key_for_bd_addr(&addr);
1312                         }
1313                         break;
1314                     }
1315                     if (!conn){
1316                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1317                     }
1318                     if (!conn){
1319                         // no memory
1320                         break;
1321                     }
1322 
1323                     conn->state = OPEN;
1324                     conn->con_handle = READ_BT_16(packet, 4);
1325 
1326                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
1327 
1328                     // restart timer
1329                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1330                     // run_loop_add_timer(&conn->timeout);
1331 
1332                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1333 
1334                     hci_emit_nr_connections_changed();
1335                     break;
1336 
1337             // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]);
1338 
1339                 default:
1340                     break;
1341             }
1342             break;
1343 #endif
1344         default:
1345             break;
1346     }
1347 
1348     // handle BT initialization
1349     if (hci_stack->state == HCI_STATE_INITIALIZING){
1350         hci_initializing_event_handler(packet, size);
1351     }
1352 
1353     // help with BT sleep
1354     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
1355         && hci_stack->substate == 1
1356         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1357         hci_stack->substate++;
1358     }
1359 
1360     // notify upper stack
1361     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1362 
1363     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
1364     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1365         if (!packet[2]){
1366             handle = READ_BT_16(packet, 3);
1367             hci_connection_t * conn = hci_connection_for_handle(handle);
1368             if (conn) {
1369                 uint8_t status = conn->bonding_status;
1370                 uint16_t flags = conn->bonding_flags;
1371                 bd_addr_t bd_address;
1372                 memcpy(&bd_address, conn->address, 6);
1373                 hci_shutdown_connection(conn);
1374                 // connection struct is gone, don't access anymore
1375                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
1376                     hci_emit_dedicated_bonding_result(bd_address, status);
1377                 }
1378             }
1379         }
1380     }
1381 
1382 	// execute main loop
1383 	hci_run();
1384 }
1385 
1386 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1387     hci_dump_packet(packet_type, 1, packet, size);
1388     switch (packet_type) {
1389         case HCI_EVENT_PACKET:
1390             event_handler(packet, size);
1391             break;
1392         case HCI_ACL_DATA_PACKET:
1393             acl_handler(packet, size);
1394             break;
1395         default:
1396             break;
1397     }
1398 }
1399 
1400 /** Register HCI packet handlers */
1401 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1402     hci_stack->packet_handler = handler;
1403 }
1404 
1405 static void hci_state_reset(){
1406     // no connections yet
1407     hci_stack->connections = NULL;
1408 
1409     // keep discoverable/connectable as this has been requested by the client(s)
1410     // hci_stack->discoverable = 0;
1411     // hci_stack->connectable = 0;
1412     // hci_stack->bondable = 1;
1413 
1414     // buffer is free
1415     hci_stack->hci_packet_buffer_reserved = 0;
1416 
1417     // no pending cmds
1418     hci_stack->decline_reason = 0;
1419     hci_stack->new_scan_enable_value = 0xff;
1420 
1421     // LE
1422     hci_stack->adv_addr_type = 0;
1423     memset(hci_stack->adv_address, 0, 6);
1424     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1425     hci_stack->le_scan_type = 0xff;
1426     hci_stack->le_connection_parameter_range.le_conn_interval_min = 0x0006;
1427     hci_stack->le_connection_parameter_range.le_conn_interval_max = 0x0C80;
1428     hci_stack->le_connection_parameter_range.le_conn_latency_min = 0x0000;
1429     hci_stack->le_connection_parameter_range.le_conn_latency_max = 0x03E8;
1430     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = 0x000A;
1431     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 0x0C80;
1432 }
1433 
1434 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
1435 
1436 #ifdef HAVE_MALLOC
1437     if (!hci_stack) {
1438         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
1439     }
1440 #else
1441     hci_stack = &hci_stack_static;
1442 #endif
1443     memset(hci_stack, 0, sizeof(hci_stack_t));
1444 
1445     // reference to use transport layer implementation
1446     hci_stack->hci_transport = transport;
1447 
1448     // references to used control implementation
1449     hci_stack->control = control;
1450 
1451     // reference to used config
1452     hci_stack->config = config;
1453 
1454     // higher level handler
1455     hci_stack->packet_handler = dummy_handler;
1456 
1457     // store and open remote device db
1458     hci_stack->remote_device_db = remote_device_db;
1459     if (hci_stack->remote_device_db) {
1460         hci_stack->remote_device_db->open();
1461     }
1462 
1463     // max acl payload size defined in config.h
1464     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1465 
1466     // register packet handlers with transport
1467     transport->register_packet_handler(&packet_handler);
1468 
1469     hci_stack->state = HCI_STATE_OFF;
1470 
1471     // class of device
1472     hci_stack->class_of_device = 0x007a020c; // Smartphone
1473 
1474     // bondable by default
1475     hci_stack->bondable = 1;
1476 
1477     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
1478     hci_stack->ssp_enable = 1;
1479     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1480     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
1481     hci_stack->ssp_auto_accept = 1;
1482 
1483     hci_state_reset();
1484 }
1485 
1486 void hci_close(){
1487     // close remote device db
1488     if (hci_stack->remote_device_db) {
1489         hci_stack->remote_device_db->close();
1490     }
1491     while (hci_stack->connections) {
1492         // cancel all l2cap connections
1493         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
1494         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1495     }
1496     hci_power_control(HCI_POWER_OFF);
1497 
1498 #ifdef HAVE_MALLOC
1499     free(hci_stack);
1500 #endif
1501     hci_stack = NULL;
1502 }
1503 
1504 void hci_set_class_of_device(uint32_t class_of_device){
1505     hci_stack->class_of_device = class_of_device;
1506 }
1507 
1508 void hci_disable_l2cap_timeout_check(){
1509     disable_l2cap_timeouts = 1;
1510 }
1511 // State-Module-Driver overview
1512 // state                    module  low-level
1513 // HCI_STATE_OFF             off      close
1514 // HCI_STATE_INITIALIZING,   on       open
1515 // HCI_STATE_WORKING,        on       open
1516 // HCI_STATE_HALTING,        on       open
1517 // HCI_STATE_SLEEPING,    off/sleep   close
1518 // HCI_STATE_FALLING_ASLEEP  on       open
1519 
1520 static int hci_power_control_on(void){
1521 
1522     // power on
1523     int err = 0;
1524     if (hci_stack->control && hci_stack->control->on){
1525         err = (*hci_stack->control->on)(hci_stack->config);
1526     }
1527     if (err){
1528         log_error( "POWER_ON failed");
1529         hci_emit_hci_open_failed();
1530         return err;
1531     }
1532 
1533     // open low-level device
1534     err = hci_stack->hci_transport->open(hci_stack->config);
1535     if (err){
1536         log_error( "HCI_INIT failed, turning Bluetooth off again");
1537         if (hci_stack->control && hci_stack->control->off){
1538             (*hci_stack->control->off)(hci_stack->config);
1539         }
1540         hci_emit_hci_open_failed();
1541         return err;
1542     }
1543     return 0;
1544 }
1545 
1546 static void hci_power_control_off(void){
1547 
1548     log_info("hci_power_control_off");
1549 
1550     // close low-level device
1551     hci_stack->hci_transport->close(hci_stack->config);
1552 
1553     log_info("hci_power_control_off - hci_transport closed");
1554 
1555     // power off
1556     if (hci_stack->control && hci_stack->control->off){
1557         (*hci_stack->control->off)(hci_stack->config);
1558     }
1559 
1560     log_info("hci_power_control_off - control closed");
1561 
1562     hci_stack->state = HCI_STATE_OFF;
1563 }
1564 
1565 static void hci_power_control_sleep(void){
1566 
1567     log_info("hci_power_control_sleep");
1568 
1569 #if 0
1570     // don't close serial port during sleep
1571 
1572     // close low-level device
1573     hci_stack->hci_transport->close(hci_stack->config);
1574 #endif
1575 
1576     // sleep mode
1577     if (hci_stack->control && hci_stack->control->sleep){
1578         (*hci_stack->control->sleep)(hci_stack->config);
1579     }
1580 
1581     hci_stack->state = HCI_STATE_SLEEPING;
1582 }
1583 
1584 static int hci_power_control_wake(void){
1585 
1586     log_info("hci_power_control_wake");
1587 
1588     // wake on
1589     if (hci_stack->control && hci_stack->control->wake){
1590         (*hci_stack->control->wake)(hci_stack->config);
1591     }
1592 
1593 #if 0
1594     // open low-level device
1595     int err = hci_stack->hci_transport->open(hci_stack->config);
1596     if (err){
1597         log_error( "HCI_INIT failed, turning Bluetooth off again");
1598         if (hci_stack->control && hci_stack->control->off){
1599             (*hci_stack->control->off)(hci_stack->config);
1600         }
1601         hci_emit_hci_open_failed();
1602         return err;
1603     }
1604 #endif
1605 
1606     return 0;
1607 }
1608 
1609 static void hci_power_transition_to_initializing(void){
1610     // set up state machine
1611     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1612     hci_stack->hci_packet_buffer_reserved = 0;
1613     hci_stack->state = HCI_STATE_INITIALIZING;
1614     hci_stack->substate = 0;
1615 }
1616 
1617 int hci_power_control(HCI_POWER_MODE power_mode){
1618 
1619     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
1620 
1621     int err = 0;
1622     switch (hci_stack->state){
1623 
1624         case HCI_STATE_OFF:
1625             switch (power_mode){
1626                 case HCI_POWER_ON:
1627                     err = hci_power_control_on();
1628                     if (err) {
1629                         log_error("hci_power_control_on() error %u", err);
1630                         return err;
1631                     }
1632                     hci_power_transition_to_initializing();
1633                     break;
1634                 case HCI_POWER_OFF:
1635                     // do nothing
1636                     break;
1637                 case HCI_POWER_SLEEP:
1638                     // do nothing (with SLEEP == OFF)
1639                     break;
1640             }
1641             break;
1642 
1643         case HCI_STATE_INITIALIZING:
1644             switch (power_mode){
1645                 case HCI_POWER_ON:
1646                     // do nothing
1647                     break;
1648                 case HCI_POWER_OFF:
1649                     // no connections yet, just turn it off
1650                     hci_power_control_off();
1651                     break;
1652                 case HCI_POWER_SLEEP:
1653                     // no connections yet, just turn it off
1654                     hci_power_control_sleep();
1655                     break;
1656             }
1657             break;
1658 
1659         case HCI_STATE_WORKING:
1660             switch (power_mode){
1661                 case HCI_POWER_ON:
1662                     // do nothing
1663                     break;
1664                 case HCI_POWER_OFF:
1665                     // see hci_run
1666                     hci_stack->state = HCI_STATE_HALTING;
1667                     break;
1668                 case HCI_POWER_SLEEP:
1669                     // see hci_run
1670                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1671                     hci_stack->substate = 0;
1672                     break;
1673             }
1674             break;
1675 
1676         case HCI_STATE_HALTING:
1677             switch (power_mode){
1678                 case HCI_POWER_ON:
1679                     hci_power_transition_to_initializing();
1680                     break;
1681                 case HCI_POWER_OFF:
1682                     // do nothing
1683                     break;
1684                 case HCI_POWER_SLEEP:
1685                     // see hci_run
1686                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1687                     hci_stack->substate = 0;
1688                     break;
1689             }
1690             break;
1691 
1692         case HCI_STATE_FALLING_ASLEEP:
1693             switch (power_mode){
1694                 case HCI_POWER_ON:
1695 
1696 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1697                     // nothing to do, if H4 supports power management
1698                     if (bt_control_iphone_power_management_enabled()){
1699                         hci_stack->state = HCI_STATE_INITIALIZING;
1700                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1701                         break;
1702                     }
1703 #endif
1704                     hci_power_transition_to_initializing();
1705                     break;
1706                 case HCI_POWER_OFF:
1707                     // see hci_run
1708                     hci_stack->state = HCI_STATE_HALTING;
1709                     break;
1710                 case HCI_POWER_SLEEP:
1711                     // do nothing
1712                     break;
1713             }
1714             break;
1715 
1716         case HCI_STATE_SLEEPING:
1717             switch (power_mode){
1718                 case HCI_POWER_ON:
1719 
1720 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1721                     // nothing to do, if H4 supports power management
1722                     if (bt_control_iphone_power_management_enabled()){
1723                         hci_stack->state = HCI_STATE_INITIALIZING;
1724                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1725                         hci_update_scan_enable();
1726                         break;
1727                     }
1728 #endif
1729                     err = hci_power_control_wake();
1730                     if (err) return err;
1731                     hci_power_transition_to_initializing();
1732                     break;
1733                 case HCI_POWER_OFF:
1734                     hci_stack->state = HCI_STATE_HALTING;
1735                     break;
1736                 case HCI_POWER_SLEEP:
1737                     // do nothing
1738                     break;
1739             }
1740             break;
1741     }
1742 
1743     // create internal event
1744 	hci_emit_state();
1745 
1746 	// trigger next/first action
1747 	hci_run();
1748 
1749     return 0;
1750 }
1751 
1752 static void hci_update_scan_enable(void){
1753     // 2 = page scan, 1 = inq scan
1754     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1755     hci_run();
1756 }
1757 
1758 void hci_discoverable_control(uint8_t enable){
1759     if (enable) enable = 1; // normalize argument
1760 
1761     if (hci_stack->discoverable == enable){
1762         hci_emit_discoverable_enabled(hci_stack->discoverable);
1763         return;
1764     }
1765 
1766     hci_stack->discoverable = enable;
1767     hci_update_scan_enable();
1768 }
1769 
1770 void hci_connectable_control(uint8_t enable){
1771     if (enable) enable = 1; // normalize argument
1772 
1773     // don't emit event
1774     if (hci_stack->connectable == enable) return;
1775 
1776     hci_stack->connectable = enable;
1777     hci_update_scan_enable();
1778 }
1779 
1780 bd_addr_t * hci_local_bd_addr(void){
1781     return &hci_stack->local_bd_addr;
1782 }
1783 
1784 void hci_run(){
1785 
1786     hci_connection_t * connection;
1787     linked_item_t * it;
1788 
1789     // send continuation fragments first, as they block the prepared packet buffer
1790     if (hci_stack->acl_fragmentation_total_size > 0) {
1791         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
1792         if (hci_can_send_prepared_acl_packet_now(con_handle)){
1793             hci_connection_t *connection = hci_connection_for_handle(con_handle);
1794             if (connection) {
1795                 hci_send_acl_packet_fragments(connection);
1796                 return;
1797             }
1798             // connection gone -> discard further fragments
1799             hci_stack->acl_fragmentation_total_size = 0;
1800             hci_stack->acl_fragmentation_pos = 0;
1801         }
1802     }
1803 
1804     if (!hci_can_send_command_packet_now()) return;
1805 
1806     // global/non-connection oriented commands
1807 
1808     // decline incoming connections
1809     if (hci_stack->decline_reason){
1810         uint8_t reason = hci_stack->decline_reason;
1811         hci_stack->decline_reason = 0;
1812         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1813         return;
1814     }
1815 
1816     // send scan enable
1817     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
1818         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1819         hci_stack->new_scan_enable_value = 0xff;
1820         return;
1821     }
1822 
1823 #ifdef HAVE_BLE
1824     // handle le scan
1825     if (hci_stack->state == HCI_STATE_WORKING){
1826         switch(hci_stack->le_scanning_state){
1827             case LE_START_SCAN:
1828                 hci_stack->le_scanning_state = LE_SCANNING;
1829                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
1830                 return;
1831 
1832             case LE_STOP_SCAN:
1833                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
1834                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
1835                 return;
1836             default:
1837                 break;
1838         }
1839         if (hci_stack->le_scan_type != 0xff){
1840             // defaults: active scanning, accept all advertisement packets
1841             int scan_type = hci_stack->le_scan_type;
1842             hci_stack->le_scan_type = 0xff;
1843             hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->adv_addr_type, 0);
1844             return;
1845         }
1846     }
1847 #endif
1848 
1849     // send pending HCI commands
1850     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1851         connection = (hci_connection_t *) it;
1852 
1853         switch(connection->state){
1854             case SEND_CREATE_CONNECTION:
1855                 switch(connection->address_type){
1856                     case BD_ADDR_TYPE_CLASSIC:
1857                         log_info("sending hci_create_connection");
1858                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1859                         break;
1860                     default:
1861 #ifdef HAVE_BLE
1862                         log_info("sending hci_le_create_connection");
1863                         hci_send_cmd(&hci_le_create_connection,
1864                                      0x0060,    // scan interval: 60 ms
1865                                      0x0030,    // scan interval: 30 ms
1866                                      0,         // don't use whitelist
1867                                      connection->address_type, // peer address type
1868                                      connection->address,      // peer bd addr
1869                                      hci_stack->adv_addr_type, // our addr type:
1870                                      0x0008,    // conn interval min
1871                                      0x0018,    // conn interval max
1872                                      0,         // conn latency
1873                                      0x0048,    // supervision timeout
1874                                      0x0001,    // min ce length
1875                                      0x0001     // max ce length
1876                                      );
1877 
1878                         connection->state = SENT_CREATE_CONNECTION;
1879 #endif
1880                         break;
1881                 }
1882                 return;
1883 
1884             case RECEIVED_CONNECTION_REQUEST:
1885                 log_info("sending hci_accept_connection_request");
1886                 connection->state = ACCEPTED_CONNECTION_REQUEST;
1887                 hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1888                 return;
1889 
1890 #ifdef HAVE_BLE
1891             case SEND_CANCEL_CONNECTION:
1892                 connection->state = SENT_CANCEL_CONNECTION;
1893                 hci_send_cmd(&hci_le_create_connection_cancel);
1894                 return;
1895 #endif
1896             case SEND_DISCONNECT:
1897                 connection->state = SENT_DISCONNECT;
1898                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
1899                 return;
1900 
1901             default:
1902                 break;
1903         }
1904 
1905         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1906             log_info("responding to link key request");
1907             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1908             link_key_t link_key;
1909             link_key_type_t link_key_type;
1910             if ( hci_stack->remote_device_db
1911               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1912               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
1913                connection->link_key_type = link_key_type;
1914                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1915             } else {
1916                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1917             }
1918             return;
1919         }
1920 
1921         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
1922             log_info("denying to pin request");
1923             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
1924             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
1925             return;
1926         }
1927 
1928         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1929             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1930             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
1931             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1932                 // tweak authentication requirements
1933                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1934                 if (connection->bonding_flags & BONDING_DEDICATED){
1935                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
1936                 }
1937                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
1938                     authreq |= 1;
1939                 }
1940                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1941             } else {
1942                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1943             }
1944             return;
1945         }
1946 
1947         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1948             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1949             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1950             return;
1951         }
1952 
1953         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1954             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1955             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1956             return;
1957         }
1958 
1959         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1960             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
1961             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
1962             return;
1963         }
1964 
1965         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
1966             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
1967             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
1968             return;
1969         }
1970         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1971             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
1972             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
1973             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1974             return;
1975         }
1976         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
1977             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
1978             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
1979             return;
1980         }
1981         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1982             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1983             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1984             return;
1985         }
1986 
1987 #ifdef HAVE_BLE
1988         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
1989             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1990 
1991             uint16_t connection_interval_min = connection->le_conn_interval_min;
1992             connection->le_conn_interval_min = 0;
1993             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
1994                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
1995                 0x0000, 0xffff);
1996         }
1997 #endif
1998     }
1999 
2000     switch (hci_stack->state){
2001         case HCI_STATE_INITIALIZING:
2002             hci_initializing_state_machine();
2003             break;
2004 
2005         case HCI_STATE_HALTING:
2006 
2007             log_info("HCI_STATE_HALTING");
2008             // close all open connections
2009             connection =  (hci_connection_t *) hci_stack->connections;
2010             if (connection){
2011 
2012                 // send disconnect
2013                 if (!hci_can_send_command_packet_now()) return;
2014 
2015                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2016                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2017 
2018                 // send disconnected event right away - causes higher layer connections to get closed, too.
2019                 hci_shutdown_connection(connection);
2020                 return;
2021             }
2022             log_info("HCI_STATE_HALTING, calling off");
2023 
2024             // switch mode
2025             hci_power_control_off();
2026 
2027             log_info("HCI_STATE_HALTING, emitting state");
2028             hci_emit_state();
2029             log_info("HCI_STATE_HALTING, done");
2030             break;
2031 
2032         case HCI_STATE_FALLING_ASLEEP:
2033             switch(hci_stack->substate) {
2034                 case 0:
2035                     log_info("HCI_STATE_FALLING_ASLEEP");
2036                     // close all open connections
2037                     connection =  (hci_connection_t *) hci_stack->connections;
2038 
2039 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
2040                     // don't close connections, if H4 supports power management
2041                     if (bt_control_iphone_power_management_enabled()){
2042                         connection = NULL;
2043                     }
2044 #endif
2045                     if (connection){
2046 
2047                         // send disconnect
2048                         if (!hci_can_send_command_packet_now()) return;
2049 
2050                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2051                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2052 
2053                         // send disconnected event right away - causes higher layer connections to get closed, too.
2054                         hci_shutdown_connection(connection);
2055                         return;
2056                     }
2057 
2058                     if (hci_classic_supported()){
2059                         // disable page and inquiry scan
2060                         if (!hci_can_send_command_packet_now()) return;
2061 
2062                         log_info("HCI_STATE_HALTING, disabling inq scans");
2063                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
2064 
2065                         // continue in next sub state
2066                         hci_stack->substate++;
2067                         break;
2068                     }
2069                     // fall through for ble-only chips
2070 
2071                 case 2:
2072                     log_info("HCI_STATE_HALTING, calling sleep");
2073 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
2074                     // don't actually go to sleep, if H4 supports power management
2075                     if (bt_control_iphone_power_management_enabled()){
2076                         // SLEEP MODE reached
2077                         hci_stack->state = HCI_STATE_SLEEPING;
2078                         hci_emit_state();
2079                         break;
2080                     }
2081 #endif
2082                     // switch mode
2083                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
2084                     hci_emit_state();
2085                     break;
2086 
2087                 default:
2088                     break;
2089             }
2090             break;
2091 
2092         default:
2093             break;
2094     }
2095 }
2096 
2097 int hci_send_cmd_packet(uint8_t *packet, int size){
2098     bd_addr_t addr;
2099     hci_connection_t * conn;
2100     // house-keeping
2101 
2102     // create_connection?
2103     if (IS_COMMAND(packet, hci_create_connection)){
2104         bt_flip_addr(addr, &packet[3]);
2105         log_info("Create_connection to %s", bd_addr_to_str(addr));
2106 
2107         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2108         if (!conn){
2109             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2110             if (!conn){
2111                 // notify client that alloc failed
2112                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2113                 return 0; // don't sent packet to controller
2114             }
2115             conn->state = SEND_CREATE_CONNECTION;
2116         }
2117         log_info("conn state %u", conn->state);
2118         switch (conn->state){
2119             // if connection active exists
2120             case OPEN:
2121                 // and OPEN, emit connection complete command, don't send to controller
2122                 hci_emit_connection_complete(conn, 0);
2123                 return 0;
2124             case SEND_CREATE_CONNECTION:
2125                 // connection created by hci, e.g. dedicated bonding
2126                 break;
2127             default:
2128                 // otherwise, just ignore as it is already in the open process
2129                 return 0;
2130         }
2131         conn->state = SENT_CREATE_CONNECTION;
2132     }
2133 
2134     if (IS_COMMAND(packet, hci_link_key_request_reply)){
2135         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
2136     }
2137     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
2138         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
2139     }
2140 
2141     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
2142         if (hci_stack->remote_device_db){
2143             bt_flip_addr(addr, &packet[3]);
2144             hci_stack->remote_device_db->delete_link_key(&addr);
2145         }
2146     }
2147 
2148     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
2149     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
2150         bt_flip_addr(addr, &packet[3]);
2151         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2152         if (conn){
2153             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
2154         }
2155     }
2156 
2157     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
2158     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
2159     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
2160     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
2161         bt_flip_addr(addr, &packet[3]);
2162         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2163         if (conn){
2164             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
2165         }
2166     }
2167 
2168 #ifdef HAVE_BLE
2169     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
2170         hci_stack->adv_addr_type = packet[8];
2171     }
2172     if (IS_COMMAND(packet, hci_le_set_random_address)){
2173         bt_flip_addr(hci_stack->adv_address, &packet[3]);
2174     }
2175 #endif
2176 
2177     hci_stack->num_cmd_packets--;
2178 
2179     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2180     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2181 
2182     // release packet buffer for synchronous transport implementations
2183     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
2184         hci_stack->hci_packet_buffer_reserved = 0;
2185     }
2186 
2187     return err;
2188 }
2189 
2190 // disconnect because of security block
2191 void hci_disconnect_security_block(hci_con_handle_t con_handle){
2192     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2193     if (!connection) return;
2194     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2195 }
2196 
2197 
2198 // Configure Secure Simple Pairing
2199 
2200 // enable will enable SSP during init
2201 void hci_ssp_set_enable(int enable){
2202     hci_stack->ssp_enable = enable;
2203 }
2204 
2205 int hci_local_ssp_activated(){
2206     return hci_ssp_supported() && hci_stack->ssp_enable;
2207 }
2208 
2209 // if set, BTstack will respond to io capability request using authentication requirement
2210 void hci_ssp_set_io_capability(int io_capability){
2211     hci_stack->ssp_io_capability = io_capability;
2212 }
2213 void hci_ssp_set_authentication_requirement(int authentication_requirement){
2214     hci_stack->ssp_authentication_requirement = authentication_requirement;
2215 }
2216 
2217 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2218 void hci_ssp_set_auto_accept(int auto_accept){
2219     hci_stack->ssp_auto_accept = auto_accept;
2220 }
2221 
2222 /**
2223  * pre: numcmds >= 0 - it's allowed to send a command to the controller
2224  */
2225 int hci_send_cmd(const hci_cmd_t *cmd, ...){
2226 
2227     if (!hci_can_send_command_packet_now()){
2228         log_error("hci_send_cmd called but cannot send packet now");
2229         return 0;
2230     }
2231 
2232     // for HCI INITIALIZATION
2233     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
2234     hci_stack->last_cmd_opcode = cmd->opcode;
2235 
2236     hci_reserve_packet_buffer();
2237     uint8_t * packet = hci_stack->hci_packet_buffer;
2238 
2239     va_list argptr;
2240     va_start(argptr, cmd);
2241     uint16_t size = hci_create_cmd_internal(packet, cmd, argptr);
2242     va_end(argptr);
2243 
2244     return hci_send_cmd_packet(packet, size);
2245 }
2246 
2247 // Create various non-HCI events.
2248 // TODO: generalize, use table similar to hci_create_command
2249 
2250 void hci_emit_state(){
2251     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2252     uint8_t event[3];
2253     event[0] = BTSTACK_EVENT_STATE;
2254     event[1] = sizeof(event) - 2;
2255     event[2] = hci_stack->state;
2256     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2257     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2258 }
2259 
2260 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
2261     uint8_t event[13];
2262     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
2263     event[1] = sizeof(event) - 2;
2264     event[2] = status;
2265     bt_store_16(event, 3, conn->con_handle);
2266     bt_flip_addr(&event[5], conn->address);
2267     event[11] = 1; // ACL connection
2268     event[12] = 0; // encryption disabled
2269     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2270     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2271 }
2272 
2273 void hci_emit_le_connection_complete(hci_connection_t *conn, uint8_t status){
2274     uint8_t event[21];
2275     event[0] = HCI_EVENT_LE_META;
2276     event[1] = sizeof(event) - 2;
2277     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
2278     event[3] = status;
2279     bt_store_16(event, 4, conn->con_handle);
2280     event[6] = 0; // TODO: role
2281     event[7] = conn->address_type;
2282     bt_flip_addr(&event[8], conn->address);
2283     bt_store_16(event, 14, 0); // interval
2284     bt_store_16(event, 16, 0); // latency
2285     bt_store_16(event, 18, 0); // supervision timeout
2286     event[20] = 0; // master clock accuracy
2287     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2288     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2289 }
2290 
2291 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
2292     uint8_t event[6];
2293     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
2294     event[1] = sizeof(event) - 2;
2295     event[2] = 0; // status = OK
2296     bt_store_16(event, 3, handle);
2297     event[5] = reason;
2298     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2299     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2300 }
2301 
2302 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
2303     if (disable_l2cap_timeouts) return;
2304     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
2305     uint8_t event[4];
2306     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
2307     event[1] = sizeof(event) - 2;
2308     bt_store_16(event, 2, conn->con_handle);
2309     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2310     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2311 }
2312 
2313 void hci_emit_nr_connections_changed(){
2314     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
2315     uint8_t event[3];
2316     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
2317     event[1] = sizeof(event) - 2;
2318     event[2] = nr_hci_connections();
2319     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2320     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2321 }
2322 
2323 void hci_emit_hci_open_failed(){
2324     log_info("BTSTACK_EVENT_POWERON_FAILED");
2325     uint8_t event[2];
2326     event[0] = BTSTACK_EVENT_POWERON_FAILED;
2327     event[1] = sizeof(event) - 2;
2328     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2329     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2330 }
2331 
2332 #ifndef EMBEDDED
2333 void hci_emit_btstack_version() {
2334     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
2335     uint8_t event[6];
2336     event[0] = BTSTACK_EVENT_VERSION;
2337     event[1] = sizeof(event) - 2;
2338     event[2] = BTSTACK_MAJOR;
2339     event[3] = BTSTACK_MINOR;
2340     bt_store_16(event, 4, BTSTACK_REVISION);
2341     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2342     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2343 }
2344 #endif
2345 
2346 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
2347     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
2348     uint8_t event[3];
2349     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
2350     event[1] = sizeof(event) - 2;
2351     event[2] = enabled;
2352     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2353     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2354 }
2355 
2356 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
2357     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
2358     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
2359     event[1] = sizeof(event) - 2 - 1;
2360     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
2361     bt_flip_addr(&event[3], *addr);
2362     memcpy(&event[9], name, 248);
2363 
2364     event[9+248] = 0;   // assert \0 for log_info
2365     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2366 
2367     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
2368     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2369 }
2370 
2371 void hci_emit_discoverable_enabled(uint8_t enabled){
2372     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2373     uint8_t event[3];
2374     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2375     event[1] = sizeof(event) - 2;
2376     event[2] = enabled;
2377     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2378     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2379 }
2380 
2381 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2382     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2383     uint8_t event[5];
2384     int pos = 0;
2385     event[pos++] = GAP_SECURITY_LEVEL;
2386     event[pos++] = sizeof(event) - 2;
2387     bt_store_16(event, 2, con_handle);
2388     pos += 2;
2389     event[pos++] = level;
2390     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2391     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2392 }
2393 
2394 void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
2395     log_info("hci_emit_dedicated_bonding_result %u ", status);
2396     uint8_t event[9];
2397     int pos = 0;
2398     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2399     event[pos++] = sizeof(event) - 2;
2400     event[pos++] = status;
2401     bt_flip_addr( * (bd_addr_t *) &event[pos], address);
2402     pos += 6;
2403     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2404     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2405 }
2406 
2407 // query if remote side supports SSP
2408 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
2409     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2410     if (!connection) return 0;
2411     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
2412 }
2413 
2414 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2415     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2416 }
2417 
2418 // GAP API
2419 /**
2420  * @bbrief enable/disable bonding. default is enabled
2421  * @praram enabled
2422  */
2423 void gap_set_bondable_mode(int enable){
2424     hci_stack->bondable = enable ? 1 : 0;
2425 }
2426 
2427 /**
2428  * @brief map link keys to security levels
2429  */
2430 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
2431     switch (link_key_type){
2432         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
2433             return LEVEL_4;
2434         case COMBINATION_KEY:
2435         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
2436             return LEVEL_3;
2437         default:
2438             return LEVEL_2;
2439     }
2440 }
2441 
2442 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
2443     if (!connection) return LEVEL_0;
2444     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
2445     return gap_security_level_for_link_key_type(connection->link_key_type);
2446 }
2447 
2448 
2449 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
2450     log_info("gap_mitm_protection_required_for_security_level %u", level);
2451     return level > LEVEL_2;
2452 }
2453 
2454 /**
2455  * @brief get current security level
2456  */
2457 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
2458     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2459     if (!connection) return LEVEL_0;
2460     return gap_security_level_for_connection(connection);
2461 }
2462 
2463 /**
2464  * @brief request connection to device to
2465  * @result GAP_AUTHENTICATION_RESULT
2466  */
2467 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
2468     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2469     if (!connection){
2470         hci_emit_security_level(con_handle, LEVEL_0);
2471         return;
2472     }
2473     gap_security_level_t current_level = gap_security_level(con_handle);
2474     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
2475     if (current_level >= requested_level){
2476         hci_emit_security_level(con_handle, current_level);
2477         return;
2478     }
2479 
2480     connection->requested_security_level = requested_level;
2481 
2482     // would enabling ecnryption suffice (>= LEVEL_2)?
2483     if (hci_stack->remote_device_db){
2484         link_key_type_t link_key_type;
2485         link_key_t      link_key;
2486         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2487             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2488                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2489                 return;
2490             }
2491         }
2492     }
2493 
2494     // try to authenticate connection
2495     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2496     hci_run();
2497 }
2498 
2499 /**
2500  * @brief start dedicated bonding with device. disconnect after bonding
2501  * @param device
2502  * @param request MITM protection
2503  * @result GAP_DEDICATED_BONDING_COMPLETE
2504  */
2505 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2506 
2507     // create connection state machine
2508     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2509 
2510     if (!connection){
2511         return BTSTACK_MEMORY_ALLOC_FAILED;
2512     }
2513 
2514     // delete linkn key
2515     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2516 
2517     // configure LEVEL_2/3, dedicated bonding
2518     connection->state = SEND_CREATE_CONNECTION;
2519     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
2520     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
2521     connection->bonding_flags = BONDING_DEDICATED;
2522 
2523     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2524 
2525     // handle: connnection failure (connection complete != ok)
2526     // handle: authentication failure
2527     // handle: disconnect on done
2528 
2529     hci_run();
2530 
2531     return 0;
2532 }
2533 
2534 void gap_set_local_name(const char * local_name){
2535     hci_stack->local_name = local_name;
2536 }
2537 
2538 le_command_status_t le_central_start_scan(){
2539     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
2540     hci_stack->le_scanning_state = LE_START_SCAN;
2541     hci_run();
2542     return BLE_PERIPHERAL_OK;
2543 }
2544 
2545 le_command_status_t le_central_stop_scan(){
2546     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
2547     hci_stack->le_scanning_state = LE_STOP_SCAN;
2548     hci_run();
2549     return BLE_PERIPHERAL_OK;
2550 }
2551 
2552 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
2553     hci_stack->le_scan_type     = scan_type;
2554     hci_stack->le_scan_interval = scan_interval;
2555     hci_stack->le_scan_window   = scan_window;
2556     hci_run();
2557 }
2558 
2559 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
2560     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2561     if (!conn){
2562         log_info("le_central_connect: no connection exists yet, creating context");
2563         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
2564         if (!conn){
2565             // notify client that alloc failed
2566             hci_emit_le_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2567             log_info("le_central_connect: failed to alloc context");
2568             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
2569         }
2570         conn->state = SEND_CREATE_CONNECTION;
2571         log_info("le_central_connect: send create connection next");
2572         hci_run();
2573         return BLE_PERIPHERAL_OK;
2574     }
2575 
2576     if (!hci_is_le_connection(conn) ||
2577         conn->state == SEND_CREATE_CONNECTION ||
2578         conn->state == SENT_CREATE_CONNECTION) {
2579         hci_emit_le_connection_complete(conn, ERROR_CODE_COMMAND_DISALLOWED);
2580         log_error("le_central_connect: classic connection or connect is already being created");
2581         return BLE_PERIPHERAL_IN_WRONG_STATE;
2582     }
2583 
2584     log_info("le_central_connect: context exists with state %u", conn->state);
2585     hci_emit_le_connection_complete(conn, 0);
2586     hci_run();
2587     return BLE_PERIPHERAL_OK;
2588 }
2589 
2590 // @assumption: only a single outgoing LE Connection exists
2591 static hci_connection_t * le_central_get_outgoing_connection(){
2592     linked_item_t *it;
2593     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
2594         hci_connection_t * conn = (hci_connection_t *) it;
2595         if (!hci_is_le_connection(conn)) continue;
2596         switch (conn->state){
2597             case SEND_CREATE_CONNECTION:
2598             case SENT_CREATE_CONNECTION:
2599                 return conn;
2600             default:
2601                 break;
2602         };
2603     }
2604     return NULL;
2605 }
2606 
2607 le_command_status_t le_central_connect_cancel(){
2608     hci_connection_t * conn = le_central_get_outgoing_connection();
2609     switch (conn->state){
2610         case SEND_CREATE_CONNECTION:
2611             // skip sending create connection and emit event instead
2612             hci_emit_le_connection_complete(conn, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
2613             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
2614             btstack_memory_hci_connection_free( conn );
2615             break;
2616         case SENT_CREATE_CONNECTION:
2617             // request to send cancel connection
2618             conn->state = SEND_CANCEL_CONNECTION;
2619             hci_run();
2620             break;
2621         default:
2622             break;
2623     }
2624     return BLE_PERIPHERAL_OK;
2625 }
2626 
2627 /**
2628  * @brief Updates the connection parameters for a given LE connection
2629  * @param handle
2630  * @param conn_interval_min (unit: 1.25ms)
2631  * @param conn_interval_max (unit: 1.25ms)
2632  * @param conn_latency
2633  * @param supervision_timeout (unit: 10ms)
2634  * @returns 0 if ok
2635  */
2636 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
2637     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
2638     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2639     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2640     connection->le_conn_interval_min = conn_interval_min;
2641     connection->le_conn_interval_max = conn_interval_max;
2642     connection->le_conn_latency = conn_latency;
2643     connection->le_supervision_timeout = supervision_timeout;
2644     return 0;
2645 }
2646 
2647 le_command_status_t gap_disconnect(hci_con_handle_t handle){
2648     hci_connection_t * conn = hci_connection_for_handle(handle);
2649     if (!conn){
2650         hci_emit_disconnection_complete(handle, 0);
2651         return BLE_PERIPHERAL_OK;
2652     }
2653     conn->state = SEND_DISCONNECT;
2654     hci_run();
2655     return BLE_PERIPHERAL_OK;
2656 }
2657 
2658 void hci_disconnect_all(){
2659     linked_list_iterator_t it;
2660     linked_list_iterator_init(&it, &hci_stack->connections);
2661     while (linked_list_iterator_has_next(&it)){
2662         hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it);
2663         if (con->state == SENT_DISCONNECT) continue;
2664         con->state = SEND_DISCONNECT;
2665     }
2666     hci_run();
2667 }
2668