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