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