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