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