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