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