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