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