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