xref: /btstack/src/hci.c (revision 28ca2b4607e125f45dc135e6777e2b6822e52f41)
1 /*
2  * Copyright (C) 2009 by Matthias Ringwald
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  *
17  * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
21  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 /*
33  *  hci.c
34  *
35  *  Created by Matthias Ringwald on 4/29/09.
36  *
37  */
38 
39 #include "config.h"
40 
41 #include "hci.h"
42 
43 #include <stdarg.h>
44 #include <string.h>
45 #include <stdio.h>
46 
47 #ifndef EMBEDDED
48 #include <unistd.h> // gethostbyname
49 #include <btstack/version.h>
50 #endif
51 
52 #include "btstack_memory.h"
53 #include "debug.h"
54 #include "hci_dump.h"
55 
56 #include <btstack/hci_cmds.h>
57 
58 #define HCI_CONNECTION_TIMEOUT_MS 10000
59 
60 #ifdef USE_BLUETOOL
61 #include "bt_control_iphone.h"
62 #endif
63 
64 static void hci_update_scan_enable(void);
65 
66 // the STACK is here
67 static hci_stack_t       hci_stack;
68 
69 /**
70  * get connection for a given handle
71  *
72  * @return connection OR NULL, if not found
73  */
74 hci_connection_t * connection_for_handle(hci_con_handle_t con_handle){
75     linked_item_t *it;
76     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
77         if ( ((hci_connection_t *) it)->con_handle == con_handle){
78             return (hci_connection_t *) it;
79         }
80     }
81     return NULL;
82 }
83 
84 static void hci_connection_timeout_handler(timer_source_t *timer){
85     hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item);
86 #ifdef HAVE_TIME
87     struct timeval tv;
88     gettimeofday(&tv, NULL);
89     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
90         // connections might be timed out
91         hci_emit_l2cap_check_timeout(connection);
92     }
93 #endif
94 #ifdef HAVE_TICK
95     if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
96         // connections might be timed out
97         hci_emit_l2cap_check_timeout(connection);
98     }
99 #endif
100     run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
101     run_loop_add_timer(timer);
102 }
103 
104 static void hci_connection_timestamp(hci_connection_t *connection){
105 #ifdef HAVE_TIME
106     gettimeofday(&connection->timestamp, NULL);
107 #endif
108 #ifdef HAVE_TICK
109     connection->timestamp = embedded_get_ticks();
110 #endif
111 }
112 
113 /**
114  * create connection for given address
115  *
116  * @return connection OR NULL, if no memory left
117  */
118 static hci_connection_t * create_connection_for_addr(bd_addr_t addr){
119     hci_connection_t * conn = (hci_connection_t *) btstack_memory_hci_connection_get();
120     if (!conn) return NULL;
121     BD_ADDR_COPY(conn->address, addr);
122     conn->con_handle = 0xffff;
123     conn->authentication_flags = AUTH_FLAGS_NONE;
124     linked_item_set_user(&conn->timeout.item, conn);
125     conn->timeout.process = hci_connection_timeout_handler;
126     hci_connection_timestamp(conn);
127     conn->acl_recombination_length = 0;
128     conn->acl_recombination_pos = 0;
129     conn->num_acl_packets_sent = 0;
130     linked_list_add(&hci_stack.connections, (linked_item_t *) conn);
131     return conn;
132 }
133 
134 /**
135  * get connection for given address
136  *
137  * @return connection OR NULL, if not found
138  */
139 static hci_connection_t * connection_for_address(bd_addr_t address){
140     linked_item_t *it;
141     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
142         if ( ! BD_ADDR_CMP( ((hci_connection_t *) it)->address, address) ){
143             return (hci_connection_t *) it;
144         }
145     }
146     return NULL;
147 }
148 
149 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
150     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
151 }
152 
153 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
154     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
155 }
156 
157 
158 /**
159  * add authentication flags and reset timer
160  */
161 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
162     bd_addr_t addr;
163     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
164     hci_connection_t * conn = connection_for_address(addr);
165     if (conn) {
166         connectionSetAuthenticationFlags(conn, flags);
167         hci_connection_timestamp(conn);
168     }
169 }
170 
171 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
172     hci_connection_t * conn = connection_for_handle(handle);
173     if (!conn) return 0;
174     if (!conn->authentication_flags) return 0;
175     if (conn->authentication_flags & SENT_LINK_KEY_REPLY) return 0;
176     if (conn->authentication_flags & RECV_LINK_KEY_NOTIFICATION) return 0;
177     return 1;
178 }
179 
180 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
181     if (hci_stack.remote_device_db) {
182         hci_stack.remote_device_db->delete_link_key(addr);
183     }
184 }
185 
186 
187 /**
188  * count connections
189  */
190 static int nr_hci_connections(void){
191     int count = 0;
192     linked_item_t *it;
193     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next, count++);
194     return count;
195 }
196 
197 /**
198  * Dummy handler called by HCI
199  */
200 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
201 }
202 
203 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
204     hci_connection_t * connection = connection_for_handle(handle);
205     if (!connection) {
206         log_error("hci_number_outgoing_packets connectino for handle %u does not exist!\n", handle);
207         return 0;
208     }
209     return connection->num_acl_packets_sent;
210 }
211 
212 uint8_t hci_number_free_acl_slots(){
213     uint8_t free_slots = hci_stack.total_num_acl_packets;
214     linked_item_t *it;
215     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
216         hci_connection_t * connection = (hci_connection_t *) it;
217         if (free_slots < connection->num_acl_packets_sent) {
218             log_error("hci_number_free_acl_slots: sum of outgoing packets > total acl packets!\n");
219             return 0;
220         }
221         free_slots -= connection->num_acl_packets_sent;
222     }
223     return free_slots;
224 }
225 
226 int hci_can_send_packet_now(uint8_t packet_type){
227 
228     // check for async hci transport implementations
229     if (hci_stack.hci_transport->can_send_packet_now){
230         if (!hci_stack.hci_transport->can_send_packet_now(packet_type)){
231             return 0;
232         }
233     }
234 
235     // check regular Bluetooth flow control
236     switch (packet_type) {
237         case HCI_ACL_DATA_PACKET:
238             return hci_number_free_acl_slots();
239         case HCI_COMMAND_DATA_PACKET:
240             return hci_stack.num_cmd_packets;
241         default:
242             return 0;
243     }
244 }
245 
246 int hci_send_acl_packet(uint8_t *packet, int size){
247 
248     // check for free places on BT module
249     if (!hci_number_free_acl_slots()) return BTSTACK_ACL_BUFFERS_FULL;
250 
251     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
252     hci_connection_t *connection = connection_for_handle( con_handle);
253     if (!connection) return 0;
254     hci_connection_timestamp(connection);
255 
256     // count packet
257     connection->num_acl_packets_sent++;
258     // log_info("hci_send_acl_packet - handle %u, sent %u\n", connection->con_handle, connection->num_acl_packets_sent);
259 
260     // send packet
261     int err = hci_stack.hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
262 
263     return err;
264 }
265 
266 static void acl_handler(uint8_t *packet, int size){
267 
268     // get info
269     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
270     hci_connection_t *conn      = connection_for_handle(con_handle);
271     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
272     uint16_t acl_length         = READ_ACL_LENGTH(packet);
273 
274     // ignore non-registered handle
275     if (!conn){
276         log_error( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle);
277         return;
278     }
279 
280     // update idle timestamp
281     hci_connection_timestamp(conn);
282 
283     // handle different packet types
284     switch (acl_flags & 0x03) {
285 
286         case 0x01: // continuation fragment
287 
288             // sanity check
289             if (conn->acl_recombination_pos == 0) {
290                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle);
291                 return;
292             }
293 
294             // append fragment payload (header already stored)
295             memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length );
296             conn->acl_recombination_pos += acl_length;
297 
298             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n", acl_length,
299             //        conn->acl_recombination_pos, conn->acl_recombination_length);
300 
301             // forward complete L2CAP packet if complete.
302             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
303 
304                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos);
305                 // reset recombination buffer
306                 conn->acl_recombination_length = 0;
307                 conn->acl_recombination_pos = 0;
308             }
309             break;
310 
311         case 0x02: { // first fragment
312 
313             // sanity check
314             if (conn->acl_recombination_pos) {
315                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle);
316                 return;
317             }
318 
319             // peek into L2CAP packet!
320             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
321 
322             // log_error( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length);
323 
324             // compare fragment size to L2CAP packet size
325             if (acl_length >= l2cap_length + 4){
326 
327                 // forward fragment as L2CAP packet
328                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
329 
330             } else {
331                 // store first fragment and tweak acl length for complete package
332                 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4);
333                 conn->acl_recombination_pos    = acl_length + 4;
334                 conn->acl_recombination_length = l2cap_length;
335                 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4);
336             }
337             break;
338 
339         }
340         default:
341             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03);
342             return;
343     }
344 
345     // execute main loop
346     hci_run();
347 }
348 
349 static void hci_shutdown_connection(hci_connection_t *conn){
350     log_info("Connection closed: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
351 
352     // cancel all l2cap connections
353     hci_emit_disconnection_complete(conn->con_handle, 0x16);    // terminated by local host
354 
355     run_loop_remove_timer(&conn->timeout);
356 
357     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
358     btstack_memory_hci_connection_free( conn );
359 
360     // now it's gone
361     hci_emit_nr_connections_changed();
362 }
363 
364 static const uint16_t packet_type_sizes[] = {
365     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
366     HCI_ACL_DH1_SIZE, 0, 0, 0,
367     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
368     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
369 };
370 
371 static uint16_t hci_acl_packet_types_for_buffer_size(uint16_t buffer_size){
372     uint16_t packet_types = 0;
373     int i;
374     for (i=0;i<16;i++){
375         if (packet_type_sizes[i] == 0) continue;
376         if (packet_type_sizes[i] <= buffer_size){
377             packet_types |= 1 << i;
378         }
379     }
380     // flip bits for "may not be used"
381     packet_types ^= 0x3306;
382     return packet_types;
383 }
384 
385 uint16_t hci_usable_acl_packet_types(void){
386     return hci_stack.packet_types;
387 }
388 
389 uint8_t* hci_get_outgoing_acl_packet_buffer(void){
390     // hci packet buffer is >= acl data packet length
391     return hci_stack.hci_packet_buffer;
392 }
393 
394 uint16_t hci_max_acl_data_packet_length(){
395     return hci_stack.acl_data_packet_length;
396 }
397 
398 // avoid huge local variables
399 #ifndef EMBEDDED
400 static device_name_t device_name;
401 #endif
402 static void event_handler(uint8_t *packet, int size){
403     bd_addr_t addr;
404     uint8_t link_type;
405     hci_con_handle_t handle;
406     hci_connection_t * conn;
407     int i;
408 
409     // printf("HCI:EVENT:%02x\n", packet[0]);
410 
411     switch (packet[0]) {
412 
413         case HCI_EVENT_COMMAND_COMPLETE:
414             // get num cmd packets
415             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u\n", hci_stack.num_cmd_packets, packet[2]);
416             hci_stack.num_cmd_packets = packet[2];
417 
418             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
419                 // from offset 5
420                 // status
421                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
422                 hci_stack.acl_data_packet_length = READ_BT_16(packet, 6);
423                 // ignore: SCO data packet len (8)
424                 hci_stack.total_num_acl_packets  = packet[9];
425                 // ignore: total num SCO packets
426                 if (hci_stack.state == HCI_STATE_INITIALIZING){
427                     // determine usable ACL payload size
428                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack.acl_data_packet_length){
429                         hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
430                     }
431                     // determine usable ACL packet types
432                     hci_stack.packet_types = hci_acl_packet_types_for_buffer_size(hci_stack.acl_data_packet_length);
433 
434                     log_error("hci_read_buffer_size: used size %u, count %u, packet types %04x\n",
435                              hci_stack.acl_data_packet_length, hci_stack.total_num_acl_packets, hci_stack.packet_types);
436                 }
437             }
438             // Dump local address
439             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
440                 bd_addr_t addr;
441                 bt_flip_addr(addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
442                 log_info("Local Address, Status: 0x%02x: Addr: %s\n",
443                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(addr));
444             }
445             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
446                 hci_emit_discoverable_enabled(hci_stack.discoverable);
447             }
448             break;
449 
450         case HCI_EVENT_COMMAND_STATUS:
451             // get num cmd packets
452             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u\n", hci_stack.num_cmd_packets, packet[3]);
453             hci_stack.num_cmd_packets = packet[3];
454             break;
455 
456         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
457             for (i=0; i<packet[2];i++){
458                 handle = READ_BT_16(packet, 3 + 2*i);
459                 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i);
460                 conn = connection_for_handle(handle);
461                 if (!conn){
462                     log_error("hci_number_completed_packet lists unused con handle %u\n", handle);
463                     continue;
464                 }
465                 conn->num_acl_packets_sent -= num_packets;
466                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent);
467             }
468             break;
469 
470         case HCI_EVENT_CONNECTION_REQUEST:
471             bt_flip_addr(addr, &packet[2]);
472             // TODO: eval COD 8-10
473             link_type = packet[11];
474             log_info("Connection_incoming: %s, type %u\n", bd_addr_to_str(addr), link_type);
475             if (link_type == 1) { // ACL
476                 conn = connection_for_address(addr);
477                 if (!conn) {
478                     conn = create_connection_for_addr(addr);
479                 }
480                 if (!conn) {
481                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
482                     hci_stack.decline_reason = 0x0d;
483                     BD_ADDR_COPY(hci_stack.decline_addr, addr);
484                     break;
485                 }
486                 conn->state = RECEIVED_CONNECTION_REQUEST;
487                 hci_run();
488             } else {
489                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
490                 hci_stack.decline_reason = 0x0a;
491                 BD_ADDR_COPY(hci_stack.decline_addr, addr);
492             }
493             break;
494 
495         case HCI_EVENT_CONNECTION_COMPLETE:
496             // Connection management
497             bt_flip_addr(addr, &packet[5]);
498             log_info("Connection_complete (status=%u) %s\n", packet[2], bd_addr_to_str(addr));
499             conn = connection_for_address(addr);
500             if (conn) {
501                 if (!packet[2]){
502                     conn->state = OPEN;
503                     conn->con_handle = READ_BT_16(packet, 3);
504 
505                     // restart timer
506                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
507                     run_loop_add_timer(&conn->timeout);
508 
509                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
510 
511                     hci_emit_nr_connections_changed();
512                 } else {
513                     // connection failed, remove entry
514                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
515                     btstack_memory_hci_connection_free( conn );
516 
517                     // if authentication error, also delete link key
518                     if (packet[2] == 0x05) {
519                         hci_drop_link_key_for_bd_addr(&addr);
520                     }
521                 }
522             }
523             break;
524 
525         case HCI_EVENT_LINK_KEY_REQUEST:
526             log_info("HCI_EVENT_LINK_KEY_REQUEST\n");
527             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
528             if (!hci_stack.remote_device_db) break;
529             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
530             hci_run();
531             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
532             return;
533 
534         case HCI_EVENT_LINK_KEY_NOTIFICATION:
535             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_NOTIFICATION);
536             if (!hci_stack.remote_device_db) break;
537             bt_flip_addr(addr, &packet[2]);
538             hci_stack.remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8]);
539             // still forward event to allow dismiss of pairing dialog
540             break;
541 
542         case HCI_EVENT_PIN_CODE_REQUEST:
543             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_PIN_CODE_REQUEST);
544             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
545             if (!hci_stack.remote_device_db) break;
546             bt_flip_addr(addr, &packet[2]);
547             hci_stack.remote_device_db->delete_link_key(&addr);
548             break;
549 
550 #ifndef EMBEDDED
551         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
552             if (!hci_stack.remote_device_db) break;
553             if (packet[2]) break; // status not ok
554             bt_flip_addr(addr, &packet[3]);
555             // fix for invalid remote names - terminate on 0xff
556             for (i=0; i<248;i++){
557                 if (packet[9+i] == 0xff){
558                     packet[9+i] = 0;
559                     break;
560                 }
561             }
562             memset(&device_name, 0, sizeof(device_name_t));
563             strncpy((char*) device_name, (char*) &packet[9], 248);
564             hci_stack.remote_device_db->put_name(&addr, &device_name);
565             break;
566 
567         case HCI_EVENT_INQUIRY_RESULT:
568         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
569             if (!hci_stack.remote_device_db) break;
570             // first send inq result packet
571             hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
572             // then send cached remote names
573             for (i=0; i<packet[2];i++){
574                 bt_flip_addr(addr, &packet[3+i*6]);
575                 if (hci_stack.remote_device_db->get_name(&addr, &device_name)){
576                     hci_emit_remote_name_cached(&addr, &device_name);
577                 }
578             }
579             return;
580 #endif
581 
582         case HCI_EVENT_DISCONNECTION_COMPLETE:
583             if (!packet[2]){
584                 handle = READ_BT_16(packet, 3);
585                 hci_connection_t * conn = connection_for_handle(handle);
586                 if (conn) {
587                     hci_shutdown_connection(conn);
588                 }
589             }
590             break;
591 
592         case HCI_EVENT_HARDWARE_ERROR:
593             if(hci_stack.control->hw_error){
594                 (*hci_stack.control->hw_error)();
595             }
596             break;
597 
598 #ifdef HAVE_BLE
599         case HCI_EVENT_LE_META:
600             switch (packet[2]) {
601                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
602                     // Connection management
603                     bt_flip_addr(addr, &packet[8]);
604                     log_info("LE Connection_complete (status=%u) %s\n", packet[3], bd_addr_to_str(addr));
605                     // LE connections are auto-accepted, so just create a connection if there isn't one already
606                     conn = connection_for_address(addr);
607                     if (packet[3]){
608                         if (conn){
609                             // outgoing connection failed, remove entry
610                             linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
611                             btstack_memory_hci_connection_free( conn );
612 
613                         }
614                         // if authentication error, also delete link key
615                         if (packet[3] == 0x05) {
616                             hci_drop_link_key_for_bd_addr(&addr);
617                         }
618                         break;
619                     }
620                     if (!conn){
621                         conn = create_connection_for_addr(addr);
622                     }
623                     if (!conn){
624                         // no memory
625                         break;
626                     }
627 
628                     conn->state = OPEN;
629                     conn->con_handle = READ_BT_16(packet, 4);
630 
631                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
632 
633                     // restart timer
634                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
635                     // run_loop_add_timer(&conn->timeout);
636 
637                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
638 
639                     hci_emit_nr_connections_changed();
640                     break;
641 
642                 default:
643                     break;
644             }
645             break;
646 #endif
647 
648         default:
649             break;
650     }
651 
652     // handle BT initialization
653     if (hci_stack.state == HCI_STATE_INITIALIZING){
654         // handle H4 synchronization loss on restart
655         // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){
656         //    hci_stack.substate = 0;
657         // }
658         // handle normal init sequence
659         if (hci_stack.substate % 2){
660             // odd: waiting for event
661             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
662                 hci_stack.substate++;
663             }
664         }
665     }
666 
667     // help with BT sleep
668     if (hci_stack.state == HCI_STATE_FALLING_ASLEEP
669         && hci_stack.substate == 1
670         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
671         hci_stack.substate++;
672     }
673 
674     hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
675 
676 	// execute main loop
677 	hci_run();
678 }
679 
680 void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
681     switch (packet_type) {
682         case HCI_EVENT_PACKET:
683             event_handler(packet, size);
684             break;
685         case HCI_ACL_DATA_PACKET:
686             acl_handler(packet, size);
687             break;
688         default:
689             break;
690     }
691 }
692 
693 /** Register HCI packet handlers */
694 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
695     hci_stack.packet_handler = handler;
696 }
697 
698 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
699 
700     // reference to use transport layer implementation
701     hci_stack.hci_transport = transport;
702 
703     // references to used control implementation
704     hci_stack.control = control;
705 
706     // reference to used config
707     hci_stack.config = config;
708 
709     // no connections yet
710     hci_stack.connections = NULL;
711     hci_stack.discoverable = 0;
712     hci_stack.connectable = 0;
713 
714     // no pending cmds
715     hci_stack.decline_reason = 0;
716     hci_stack.new_scan_enable_value = 0xff;
717 
718     // higher level handler
719     hci_stack.packet_handler = dummy_handler;
720 
721     // store and open remote device db
722     hci_stack.remote_device_db = remote_device_db;
723     if (hci_stack.remote_device_db) {
724         hci_stack.remote_device_db->open();
725     }
726 
727     // max acl payload size defined in config.h
728     hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
729 
730     // register packet handlers with transport
731     transport->register_packet_handler(&packet_handler);
732 
733     hci_stack.state = HCI_STATE_OFF;
734 }
735 
736 void hci_close(){
737     // close remote device db
738     if (hci_stack.remote_device_db) {
739         hci_stack.remote_device_db->close();
740     }
741     while (hci_stack.connections) {
742         hci_shutdown_connection((hci_connection_t *) hci_stack.connections);
743 }
744     hci_power_control(HCI_POWER_OFF);
745 }
746 
747 // State-Module-Driver overview
748 // state                    module  low-level
749 // HCI_STATE_OFF             off      close
750 // HCI_STATE_INITIALIZING,   on       open
751 // HCI_STATE_WORKING,        on       open
752 // HCI_STATE_HALTING,        on       open
753 // HCI_STATE_SLEEPING,    off/sleep   close
754 // HCI_STATE_FALLING_ASLEEP  on       open
755 
756 static int hci_power_control_on(void){
757 
758     // power on
759     int err = 0;
760     if (hci_stack.control && hci_stack.control->on){
761         err = (*hci_stack.control->on)(hci_stack.config);
762     }
763     if (err){
764         log_error( "POWER_ON failed\n");
765         hci_emit_hci_open_failed();
766         return err;
767     }
768 
769     // open low-level device
770     err = hci_stack.hci_transport->open(hci_stack.config);
771     if (err){
772         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
773         if (hci_stack.control && hci_stack.control->off){
774             (*hci_stack.control->off)(hci_stack.config);
775         }
776         hci_emit_hci_open_failed();
777         return err;
778     }
779     return 0;
780 }
781 
782 static void hci_power_control_off(void){
783 
784     log_info("hci_power_control_off\n");
785 
786     // close low-level device
787     hci_stack.hci_transport->close(hci_stack.config);
788 
789     log_info("hci_power_control_off - hci_transport closed\n");
790 
791     // power off
792     if (hci_stack.control && hci_stack.control->off){
793         (*hci_stack.control->off)(hci_stack.config);
794     }
795 
796     log_info("hci_power_control_off - control closed\n");
797 
798     hci_stack.state = HCI_STATE_OFF;
799 }
800 
801 static void hci_power_control_sleep(void){
802 
803     log_info("hci_power_control_sleep\n");
804 
805 #if 0
806     // don't close serial port during sleep
807 
808     // close low-level device
809     hci_stack.hci_transport->close(hci_stack.config);
810 #endif
811 
812     // sleep mode
813     if (hci_stack.control && hci_stack.control->sleep){
814         (*hci_stack.control->sleep)(hci_stack.config);
815     }
816 
817     hci_stack.state = HCI_STATE_SLEEPING;
818 }
819 
820 static int hci_power_control_wake(void){
821 
822     log_info("hci_power_control_wake\n");
823 
824     // wake on
825     if (hci_stack.control && hci_stack.control->wake){
826         (*hci_stack.control->wake)(hci_stack.config);
827     }
828 
829 #if 0
830     // open low-level device
831     int err = hci_stack.hci_transport->open(hci_stack.config);
832     if (err){
833         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
834         if (hci_stack.control && hci_stack.control->off){
835             (*hci_stack.control->off)(hci_stack.config);
836         }
837         hci_emit_hci_open_failed();
838         return err;
839     }
840 #endif
841 
842     return 0;
843 }
844 
845 
846 int hci_power_control(HCI_POWER_MODE power_mode){
847 
848     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state);
849 
850     int err = 0;
851     switch (hci_stack.state){
852 
853         case HCI_STATE_OFF:
854             switch (power_mode){
855                 case HCI_POWER_ON:
856                     err = hci_power_control_on();
857                     if (err) return err;
858                     // set up state machine
859                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
860                     hci_stack.state = HCI_STATE_INITIALIZING;
861                     hci_stack.substate = 0;
862                     break;
863                 case HCI_POWER_OFF:
864                     // do nothing
865                     break;
866                 case HCI_POWER_SLEEP:
867                     // do nothing (with SLEEP == OFF)
868                     break;
869             }
870             break;
871 
872         case HCI_STATE_INITIALIZING:
873             switch (power_mode){
874                 case HCI_POWER_ON:
875                     // do nothing
876                     break;
877                 case HCI_POWER_OFF:
878                     // no connections yet, just turn it off
879                     hci_power_control_off();
880                     break;
881                 case HCI_POWER_SLEEP:
882                     // no connections yet, just turn it off
883                     hci_power_control_sleep();
884                     break;
885             }
886             break;
887 
888         case HCI_STATE_WORKING:
889             switch (power_mode){
890                 case HCI_POWER_ON:
891                     // do nothing
892                     break;
893                 case HCI_POWER_OFF:
894                     // see hci_run
895                     hci_stack.state = HCI_STATE_HALTING;
896                     break;
897                 case HCI_POWER_SLEEP:
898                     // see hci_run
899                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
900                     hci_stack.substate = 0;
901                     break;
902             }
903             break;
904 
905         case HCI_STATE_HALTING:
906             switch (power_mode){
907                 case HCI_POWER_ON:
908                     // set up state machine
909                     hci_stack.state = HCI_STATE_INITIALIZING;
910                     hci_stack.substate = 0;
911                     break;
912                 case HCI_POWER_OFF:
913                     // do nothing
914                     break;
915                 case HCI_POWER_SLEEP:
916                     // see hci_run
917                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
918                     hci_stack.substate = 0;
919                     break;
920             }
921             break;
922 
923         case HCI_STATE_FALLING_ASLEEP:
924             switch (power_mode){
925                 case HCI_POWER_ON:
926 
927 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
928                     // nothing to do, if H4 supports power management
929                     if (bt_control_iphone_power_management_enabled()){
930                         hci_stack.state = HCI_STATE_INITIALIZING;
931                         hci_stack.substate = 6;
932                         break;
933                     }
934 #endif
935                     // set up state machine
936                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
937                     hci_stack.state = HCI_STATE_INITIALIZING;
938                     hci_stack.substate = 0;
939                     break;
940                 case HCI_POWER_OFF:
941                     // see hci_run
942                     hci_stack.state = HCI_STATE_HALTING;
943                     break;
944                 case HCI_POWER_SLEEP:
945                     // do nothing
946                     break;
947             }
948             break;
949 
950         case HCI_STATE_SLEEPING:
951             switch (power_mode){
952                 case HCI_POWER_ON:
953 
954 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
955                     // nothing to do, if H4 supports power management
956                     if (bt_control_iphone_power_management_enabled()){
957                         hci_stack.state = HCI_STATE_INITIALIZING;
958                         hci_stack.substate = 6;
959                         hci_update_scan_enable();
960                         break;
961                     }
962 #endif
963                     err = hci_power_control_wake();
964                     if (err) return err;
965                     // set up state machine
966                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
967                     hci_stack.state = HCI_STATE_INITIALIZING;
968                     hci_stack.substate = 0;
969                     break;
970                 case HCI_POWER_OFF:
971                     hci_stack.state = HCI_STATE_HALTING;
972                     break;
973                 case HCI_POWER_SLEEP:
974                     // do nothing
975                     break;
976             }
977             break;
978     }
979 
980     // create internal event
981 	hci_emit_state();
982 
983 	// trigger next/first action
984 	hci_run();
985 
986     return 0;
987 }
988 
989 static void hci_update_scan_enable(void){
990     // 2 = page scan, 1 = inq scan
991     hci_stack.new_scan_enable_value  = hci_stack.connectable << 1 | hci_stack.discoverable;
992     hci_run();
993 }
994 
995 void hci_discoverable_control(uint8_t enable){
996     if (enable) enable = 1; // normalize argument
997 
998     if (hci_stack.discoverable == enable){
999         hci_emit_discoverable_enabled(hci_stack.discoverable);
1000         return;
1001     }
1002 
1003     hci_stack.discoverable = enable;
1004     hci_update_scan_enable();
1005 }
1006 
1007 void hci_connectable_control(uint8_t enable){
1008     if (enable) enable = 1; // normalize argument
1009 
1010     // don't emit event
1011     if (hci_stack.connectable == enable) return;
1012 
1013     hci_stack.connectable = enable;
1014     hci_update_scan_enable();
1015 }
1016 
1017 void hci_run(){
1018 
1019     hci_connection_t * connection;
1020     linked_item_t * it;
1021 
1022     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1023 
1024     // global/non-connection oriented commands
1025 
1026     // decline incoming connections
1027     if (hci_stack.decline_reason){
1028         uint8_t reason = hci_stack.decline_reason;
1029         hci_stack.decline_reason = 0;
1030         hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason);
1031     }
1032 
1033     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1034 
1035     // send scan enable
1036     if (hci_stack.new_scan_enable_value != 0xff){
1037         hci_send_cmd(&hci_write_scan_enable, hci_stack.new_scan_enable_value);
1038         hci_stack.new_scan_enable_value = 0xff;
1039     }
1040 
1041     // send pending HCI commands
1042     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
1043 
1044         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1045 
1046         connection = (hci_connection_t *) it;
1047 
1048         if (connection->state == RECEIVED_CONNECTION_REQUEST){
1049             log_info("sending hci_accept_connection_request\n");
1050             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1051             connection->state = ACCEPTED_CONNECTION_REQUEST;
1052         }
1053 
1054         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1055 
1056         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1057             link_key_t link_key;
1058             log_info("responding to link key request\n");
1059             if ( hci_stack.remote_device_db->get_link_key( &connection->address, &link_key)){
1060                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1061             } else {
1062                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1063             }
1064             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1065         }
1066     }
1067 
1068     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1069 
1070     switch (hci_stack.state){
1071         case HCI_STATE_INITIALIZING:
1072             // log_info("hci_init: substate %u\n", hci_stack.substate);
1073             if (hci_stack.substate % 2) {
1074                 // odd: waiting for command completion
1075                 return;
1076             }
1077             switch (hci_stack.substate >> 1){
1078                 case 0: // RESET
1079                     hci_send_cmd(&hci_reset);
1080                     if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){
1081                         // skip baud change
1082                         hci_stack.substate = 4; // >> 1 = 2
1083                     }
1084                     break;
1085                 case 1: // SEND BAUD CHANGE
1086                     hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_packet_buffer);
1087                     hci_send_cmd_packet(hci_stack.hci_packet_buffer, 3 + hci_stack.hci_packet_buffer[2]);
1088                     break;
1089                 case 2: // LOCAL BAUD CHANGE
1090                     hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main);
1091                     hci_stack.substate += 2;
1092                     // break missing here for fall through
1093 
1094                 case 3:
1095                     // custom initialization
1096                     if (hci_stack.control && hci_stack.control->next_cmd){
1097                         int valid_cmd = (*hci_stack.control->next_cmd)(hci_stack.config, hci_stack.hci_packet_buffer);
1098                         if (valid_cmd){
1099                             int size = 3 + hci_stack.hci_packet_buffer[2];
1100                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack.hci_packet_buffer, size);
1101                             hci_stack.substate = 4; // more init commands
1102                             break;
1103                         }
1104                         log_info("hci_run: init script done\n\r");
1105                     }
1106                     // otherwise continue
1107 					hci_send_cmd(&hci_read_bd_addr);
1108 					break;
1109 				case 4:
1110 					hci_send_cmd(&hci_read_buffer_size);
1111 					break;
1112                 case 5:
1113                     // ca. 15 sec
1114                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1115                     break;
1116 				case 6:
1117 					hci_send_cmd(&hci_write_scan_enable, (hci_stack.connectable << 1) | hci_stack.discoverable); // page scan
1118 					break;
1119                 case 7:
1120 #ifndef EMBEDDED
1121                 {
1122                     char hostname[30];
1123                     gethostname(hostname, 30);
1124                     hostname[29] = '\0';
1125                     hci_send_cmd(&hci_write_local_name, hostname);
1126                     break;
1127                 }
1128                 case 8:
1129 #ifdef USE_BLUETOOL
1130                     hci_send_cmd(&hci_write_class_of_device, 0x007a020c); // Smartphone
1131                     break;
1132 
1133                 case 9:
1134 #endif
1135 #endif
1136                     // done.
1137                     hci_stack.state = HCI_STATE_WORKING;
1138                     hci_emit_state();
1139                     break;
1140                 default:
1141                     break;
1142             }
1143             hci_stack.substate++;
1144             break;
1145 
1146         case HCI_STATE_HALTING:
1147 
1148             log_info("HCI_STATE_HALTING\n");
1149             // close all open connections
1150             connection =  (hci_connection_t *) hci_stack.connections;
1151             if (connection){
1152 
1153                 // send disconnect
1154                 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1155 
1156                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1157                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1158 
1159                 // send disconnected event right away - causes higher layer connections to get closed, too.
1160                 hci_shutdown_connection(connection);
1161                 return;
1162             }
1163             log_info("HCI_STATE_HALTING, calling off\n");
1164 
1165             // switch mode
1166             hci_power_control_off();
1167 
1168             log_info("HCI_STATE_HALTING, emitting state\n");
1169             hci_emit_state();
1170             log_info("HCI_STATE_HALTING, done\n");
1171             break;
1172 
1173         case HCI_STATE_FALLING_ASLEEP:
1174             switch(hci_stack.substate) {
1175                 case 0:
1176                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1177                     // close all open connections
1178                     connection =  (hci_connection_t *) hci_stack.connections;
1179 
1180 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1181                     // don't close connections, if H4 supports power management
1182                     if (bt_control_iphone_power_management_enabled()){
1183                         connection = NULL;
1184                     }
1185 #endif
1186                     if (connection){
1187 
1188                         // send disconnect
1189                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1190 
1191                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1192                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1193 
1194                         // send disconnected event right away - causes higher layer connections to get closed, too.
1195                         hci_shutdown_connection(connection);
1196                         return;
1197                     }
1198 
1199                     // disable page and inquiry scan
1200                     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1201 
1202                     log_info("HCI_STATE_HALTING, disabling inq cans\n");
1203                     hci_send_cmd(&hci_write_scan_enable, hci_stack.connectable << 1); // drop inquiry scan but keep page scan
1204 
1205                     // continue in next sub state
1206                     hci_stack.substate++;
1207                     break;
1208                 case 1:
1209                     // wait for command complete "hci_write_scan_enable" in event_handler();
1210                     break;
1211                 case 2:
1212                     log_info("HCI_STATE_HALTING, calling sleep\n");
1213 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1214                     // don't actually go to sleep, if H4 supports power management
1215                     if (bt_control_iphone_power_management_enabled()){
1216                         // SLEEP MODE reached
1217                         hci_stack.state = HCI_STATE_SLEEPING;
1218                         hci_emit_state();
1219                         break;
1220                     }
1221 #endif
1222                     // switch mode
1223                     hci_power_control_sleep();  // changes hci_stack.state to SLEEP
1224                     hci_emit_state();
1225                     break;
1226 
1227                 default:
1228                     break;
1229             }
1230             break;
1231 
1232         default:
1233             break;
1234     }
1235 }
1236 
1237 int hci_send_cmd_packet(uint8_t *packet, int size){
1238     bd_addr_t addr;
1239     hci_connection_t * conn;
1240     // house-keeping
1241 
1242     // create_connection?
1243     if (IS_COMMAND(packet, hci_create_connection)){
1244         bt_flip_addr(addr, &packet[3]);
1245         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1246         conn = connection_for_address(addr);
1247         if (conn) {
1248             // if connection exists
1249             if (conn->state == OPEN) {
1250                 // and OPEN, emit connection complete command
1251                 hci_emit_connection_complete(conn, 0);
1252             }
1253             //    otherwise, just ignore as it is already in the open process
1254             return 0; // don't sent packet to controller
1255 
1256         }
1257         // create connection struct and register, state = SENT_CREATE_CONNECTION
1258         conn = create_connection_for_addr(addr);
1259         if (!conn){
1260             // notify client that alloc failed
1261             hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1262             return 0; // don't sent packet to controller
1263         }
1264         conn->state = SENT_CREATE_CONNECTION;
1265     }
1266 
1267     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1268         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1269     }
1270     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1271         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1272     }
1273     if (IS_COMMAND(packet, hci_pin_code_request_reply)){
1274         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY);
1275     }
1276     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){
1277         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY);
1278     }
1279 
1280     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1281         if (hci_stack.remote_device_db){
1282             bt_flip_addr(addr, &packet[3]);
1283             hci_stack.remote_device_db->delete_link_key(&addr);
1284         }
1285     }
1286 
1287     hci_stack.num_cmd_packets--;
1288     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1289 }
1290 
1291 /**
1292  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1293  */
1294 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1295     va_list argptr;
1296     va_start(argptr, cmd);
1297     uint16_t size = hci_create_cmd_internal(hci_stack.hci_packet_buffer, cmd, argptr);
1298     va_end(argptr);
1299     return hci_send_cmd_packet(hci_stack.hci_packet_buffer, size);
1300 }
1301 
1302 // Create various non-HCI events.
1303 // TODO: generalize, use table similar to hci_create_command
1304 
1305 void hci_emit_state(){
1306     uint8_t event[3];
1307     event[0] = BTSTACK_EVENT_STATE;
1308     event[1] = sizeof(event) - 2;
1309     event[2] = hci_stack.state;
1310     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1311     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1312 }
1313 
1314 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1315     uint8_t event[13];
1316     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1317     event[1] = sizeof(event) - 2;
1318     event[2] = status;
1319     bt_store_16(event, 3, conn->con_handle);
1320     bt_flip_addr(&event[5], conn->address);
1321     event[11] = 1; // ACL connection
1322     event[12] = 0; // encryption disabled
1323     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1324     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1325 }
1326 
1327 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1328     uint8_t event[6];
1329     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1330     event[1] = sizeof(event) - 2;
1331     event[2] = 0; // status = OK
1332     bt_store_16(event, 3, handle);
1333     event[5] = reason;
1334     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1335     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1336 }
1337 
1338 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1339     uint8_t event[4];
1340     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1341     event[1] = sizeof(event) - 2;
1342     bt_store_16(event, 2, conn->con_handle);
1343     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1344     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1345 }
1346 
1347 void hci_emit_nr_connections_changed(){
1348     uint8_t event[3];
1349     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1350     event[1] = sizeof(event) - 2;
1351     event[2] = nr_hci_connections();
1352     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1353     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1354 }
1355 
1356 void hci_emit_hci_open_failed(){
1357     uint8_t event[2];
1358     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1359     event[1] = sizeof(event) - 2;
1360     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1361     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1362 }
1363 
1364 #ifndef EMBEDDED
1365 void hci_emit_btstack_version() {
1366     uint8_t event[6];
1367     event[0] = BTSTACK_EVENT_VERSION;
1368     event[1] = sizeof(event) - 2;
1369     event[2] = BTSTACK_MAJOR;
1370     event[3] = BTSTACK_MINOR;
1371     bt_store_16(event, 4, BTSTACK_REVISION);
1372     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1373     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1374 }
1375 #endif
1376 
1377 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1378     uint8_t event[3];
1379     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1380     event[1] = sizeof(event) - 2;
1381     event[2] = enabled;
1382     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1383     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1384 }
1385 
1386 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1387     uint8_t event[2+1+6+248];
1388     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1389     event[1] = sizeof(event) - 2;
1390     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1391     bt_flip_addr(&event[3], *addr);
1392     memcpy(&event[9], name, 248);
1393     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1394     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1395 }
1396 
1397 void hci_emit_discoverable_enabled(uint8_t enabled){
1398     uint8_t event[3];
1399     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1400     event[1] = sizeof(event) - 2;
1401     event[2] = enabled;
1402     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1403     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1404 }
1405