xref: /btstack/src/hci.c (revision d9a327f9f151610e9be5a37b6f7ba6628250a553)
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             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
430                 hci_emit_discoverable_enabled(hci_stack.discoverable);
431             }
432             break;
433 
434         case HCI_EVENT_COMMAND_STATUS:
435             // get num cmd packets
436             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u\n", hci_stack.num_cmd_packets, packet[3]);
437             hci_stack.num_cmd_packets = packet[3];
438             break;
439 
440         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
441             for (i=0; i<packet[2];i++){
442                 handle = READ_BT_16(packet, 3 + 2*i);
443                 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i);
444                 conn = connection_for_handle(handle);
445                 if (!conn){
446                     log_error("hci_number_completed_packet lists unused con handle %u\n", handle);
447                     continue;
448                 }
449                 conn->num_acl_packets_sent -= num_packets;
450                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent);
451             }
452             break;
453 
454         case HCI_EVENT_CONNECTION_REQUEST:
455             bt_flip_addr(addr, &packet[2]);
456             // TODO: eval COD 8-10
457             link_type = packet[11];
458             log_info("Connection_incoming: %s, type %u\n", bd_addr_to_str(addr), link_type);
459             if (link_type == 1) { // ACL
460                 conn = connection_for_address(addr);
461                 if (!conn) {
462                     conn = create_connection_for_addr(addr);
463                 }
464                 if (!conn) {
465                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
466                     hci_stack.decline_reason = 0x0d;
467                     BD_ADDR_COPY(hci_stack.decline_addr, addr);
468                     break;
469                 }
470                 conn->state = RECEIVED_CONNECTION_REQUEST;
471                 hci_run();
472             } else {
473                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
474                 hci_stack.decline_reason = 0x0a;
475                 BD_ADDR_COPY(hci_stack.decline_addr, addr);
476             }
477             break;
478 
479         case HCI_EVENT_CONNECTION_COMPLETE:
480             // Connection management
481             bt_flip_addr(addr, &packet[5]);
482             log_info("Connection_complete (status=%u) %s\n", packet[2], bd_addr_to_str(addr));
483             conn = connection_for_address(addr);
484             if (conn) {
485                 if (!packet[2]){
486                     conn->state = OPEN;
487                     conn->con_handle = READ_BT_16(packet, 3);
488 
489                     // restart timer
490                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
491                     run_loop_add_timer(&conn->timeout);
492 
493                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
494 
495                     hci_emit_nr_connections_changed();
496                 } else {
497                     // connection failed, remove entry
498                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
499                     btstack_memory_hci_connection_free( conn );
500 
501                     // if authentication error, also delete link key
502                     if (packet[2] == 0x05) {
503                         hci_drop_link_key_for_bd_addr(&addr);
504                     }
505                 }
506             }
507             break;
508 
509         case HCI_EVENT_LINK_KEY_REQUEST:
510             log_info("HCI_EVENT_LINK_KEY_REQUEST\n");
511             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
512             if (!hci_stack.remote_device_db) break;
513             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
514             hci_run();
515             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
516             return;
517 
518         case HCI_EVENT_LINK_KEY_NOTIFICATION:
519             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_NOTIFICATION);
520             if (!hci_stack.remote_device_db) break;
521             bt_flip_addr(addr, &packet[2]);
522             hci_stack.remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8]);
523             // still forward event to allow dismiss of pairing dialog
524             break;
525 
526         case HCI_EVENT_PIN_CODE_REQUEST:
527             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_PIN_CODE_REQUEST);
528             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
529             if (!hci_stack.remote_device_db) break;
530             bt_flip_addr(addr, &packet[2]);
531             hci_stack.remote_device_db->delete_link_key(&addr);
532             break;
533 
534 #ifndef EMBEDDED
535         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
536             if (!hci_stack.remote_device_db) break;
537             if (packet[2]) break; // status not ok
538             bt_flip_addr(addr, &packet[3]);
539             // fix for invalid remote names - terminate on 0xff
540             for (i=0; i<248;i++){
541                 if (packet[9+i] == 0xff){
542                     packet[9+i] = 0;
543                     break;
544                 }
545             }
546             memset(&device_name, 0, sizeof(device_name_t));
547             strncpy((char*) device_name, (char*) &packet[9], 248);
548             hci_stack.remote_device_db->put_name(&addr, &device_name);
549             break;
550 
551         case HCI_EVENT_INQUIRY_RESULT:
552         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
553             if (!hci_stack.remote_device_db) break;
554             // first send inq result packet
555             hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
556             // then send cached remote names
557             for (i=0; i<packet[2];i++){
558                 bt_flip_addr(addr, &packet[3+i*6]);
559                 if (hci_stack.remote_device_db->get_name(&addr, &device_name)){
560                     hci_emit_remote_name_cached(&addr, &device_name);
561                 }
562             }
563             return;
564 #endif
565 
566         case HCI_EVENT_DISCONNECTION_COMPLETE:
567             if (!packet[2]){
568                 handle = READ_BT_16(packet, 3);
569                 hci_connection_t * conn = connection_for_handle(handle);
570                 if (conn) {
571                     hci_shutdown_connection(conn);
572                 }
573             }
574             break;
575 
576         case HCI_EVENT_HARDWARE_ERROR:
577             if(hci_stack.control->hw_error){
578                 (*hci_stack.control->hw_error)();
579             }
580             break;
581 
582 #ifdef HAVE_BLE
583         case HCI_EVENT_LE_META:
584             switch (packet[2]) {
585                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
586                     // Connection management
587                     bt_flip_addr(addr, &packet[8]);
588                     log_info("LE Connection_complete (status=%u) %s\n", packet[3], bd_addr_to_str(addr));
589                     // LE connections are auto-accepted, so just create a connection if there isn't one already
590                     conn = connection_for_address(addr);
591                     if (packet[3]){
592                         if (conn){
593                             // outgoing connection failed, remove entry
594                             linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
595                             btstack_memory_hci_connection_free( conn );
596 
597                         }
598                         // if authentication error, also delete link key
599                         if (packet[3] == 0x05) {
600                             hci_drop_link_key_for_bd_addr(&addr);
601                         }
602                         break;
603                     }
604                     if (!conn){
605                         conn = create_connection_for_addr(addr);
606                     }
607                     if (!conn){
608                         // no memory
609                         break;
610                     }
611 
612                     conn->state = OPEN;
613                     conn->con_handle = READ_BT_16(packet, 4);
614 
615                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
616 
617                     // restart timer
618                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
619                     // run_loop_add_timer(&conn->timeout);
620 
621                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
622 
623                     hci_emit_nr_connections_changed();
624                     break;
625 
626                 default:
627                     break;
628             }
629             break;
630 #endif
631 
632         default:
633             break;
634     }
635 
636     // handle BT initialization
637     if (hci_stack.state == HCI_STATE_INITIALIZING){
638         // handle H4 synchronization loss on restart
639         // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){
640         //    hci_stack.substate = 0;
641         // }
642         // handle normal init sequence
643         if (hci_stack.substate % 2){
644             // odd: waiting for event
645             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
646                 hci_stack.substate++;
647             }
648         }
649     }
650 
651     // help with BT sleep
652     if (hci_stack.state == HCI_STATE_FALLING_ASLEEP
653         && hci_stack.substate == 1
654         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
655         hci_stack.substate++;
656     }
657 
658     hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
659 
660 	// execute main loop
661 	hci_run();
662 }
663 
664 void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
665     switch (packet_type) {
666         case HCI_EVENT_PACKET:
667             event_handler(packet, size);
668             break;
669         case HCI_ACL_DATA_PACKET:
670             acl_handler(packet, size);
671             break;
672         default:
673             break;
674     }
675 }
676 
677 /** Register HCI packet handlers */
678 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
679     hci_stack.packet_handler = handler;
680 }
681 
682 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t * remote_device_db){
683 
684     // reference to use transport layer implementation
685     hci_stack.hci_transport = transport;
686 
687     // references to used control implementation
688     hci_stack.control = control;
689 
690     // reference to used config
691     hci_stack.config = config;
692 
693     // no connections yet
694     hci_stack.connections = NULL;
695     hci_stack.discoverable = 0;
696     hci_stack.connectable = 0;
697 
698     // no pending cmds
699     hci_stack.decline_reason = 0;
700     hci_stack.new_scan_enable_value = 0xff;
701 
702     // higher level handler
703     hci_stack.packet_handler = dummy_handler;
704 
705     // store and open remote device db
706     hci_stack.remote_device_db = remote_device_db;
707     if (hci_stack.remote_device_db) {
708         hci_stack.remote_device_db->open();
709     }
710 
711     // max acl payload size defined in config.h
712     hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
713 
714     // register packet handlers with transport
715     transport->register_packet_handler(&packet_handler);
716 
717     hci_stack.state = HCI_STATE_OFF;
718 }
719 
720 void hci_close(){
721     // close remote device db
722     if (hci_stack.remote_device_db) {
723         hci_stack.remote_device_db->close();
724     }
725     while (hci_stack.connections) {
726         hci_shutdown_connection((hci_connection_t *) hci_stack.connections);
727 }
728     hci_power_control(HCI_POWER_OFF);
729 }
730 
731 // State-Module-Driver overview
732 // state                    module  low-level
733 // HCI_STATE_OFF             off      close
734 // HCI_STATE_INITIALIZING,   on       open
735 // HCI_STATE_WORKING,        on       open
736 // HCI_STATE_HALTING,        on       open
737 // HCI_STATE_SLEEPING,    off/sleep   close
738 // HCI_STATE_FALLING_ASLEEP  on       open
739 
740 static int hci_power_control_on(void){
741 
742     // power on
743     int err = 0;
744     if (hci_stack.control && hci_stack.control->on){
745         err = (*hci_stack.control->on)(hci_stack.config);
746     }
747     if (err){
748         log_error( "POWER_ON failed\n");
749         hci_emit_hci_open_failed();
750         return err;
751     }
752 
753     // open low-level device
754     err = hci_stack.hci_transport->open(hci_stack.config);
755     if (err){
756         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
757         if (hci_stack.control && hci_stack.control->off){
758             (*hci_stack.control->off)(hci_stack.config);
759         }
760         hci_emit_hci_open_failed();
761         return err;
762     }
763     return 0;
764 }
765 
766 static void hci_power_control_off(void){
767 
768     log_info("hci_power_control_off\n");
769 
770     // close low-level device
771     hci_stack.hci_transport->close(hci_stack.config);
772 
773     log_info("hci_power_control_off - hci_transport closed\n");
774 
775     // power off
776     if (hci_stack.control && hci_stack.control->off){
777         (*hci_stack.control->off)(hci_stack.config);
778     }
779 
780     log_info("hci_power_control_off - control closed\n");
781 
782     hci_stack.state = HCI_STATE_OFF;
783 }
784 
785 static void hci_power_control_sleep(void){
786 
787     log_info("hci_power_control_sleep\n");
788 
789 #if 0
790     // don't close serial port during sleep
791 
792     // close low-level device
793     hci_stack.hci_transport->close(hci_stack.config);
794 #endif
795 
796     // sleep mode
797     if (hci_stack.control && hci_stack.control->sleep){
798         (*hci_stack.control->sleep)(hci_stack.config);
799     }
800 
801     hci_stack.state = HCI_STATE_SLEEPING;
802 }
803 
804 static int hci_power_control_wake(void){
805 
806     log_info("hci_power_control_wake\n");
807 
808     // wake on
809     if (hci_stack.control && hci_stack.control->wake){
810         (*hci_stack.control->wake)(hci_stack.config);
811     }
812 
813 #if 0
814     // open low-level device
815     int err = hci_stack.hci_transport->open(hci_stack.config);
816     if (err){
817         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
818         if (hci_stack.control && hci_stack.control->off){
819             (*hci_stack.control->off)(hci_stack.config);
820         }
821         hci_emit_hci_open_failed();
822         return err;
823     }
824 #endif
825 
826     return 0;
827 }
828 
829 
830 int hci_power_control(HCI_POWER_MODE power_mode){
831 
832     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state);
833 
834     int err = 0;
835     switch (hci_stack.state){
836 
837         case HCI_STATE_OFF:
838             switch (power_mode){
839                 case HCI_POWER_ON:
840                     err = hci_power_control_on();
841                     if (err) return err;
842                     // set up state machine
843                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
844                     hci_stack.state = HCI_STATE_INITIALIZING;
845                     hci_stack.substate = 0;
846                     break;
847                 case HCI_POWER_OFF:
848                     // do nothing
849                     break;
850                 case HCI_POWER_SLEEP:
851                     // do nothing (with SLEEP == OFF)
852                     break;
853             }
854             break;
855 
856         case HCI_STATE_INITIALIZING:
857             switch (power_mode){
858                 case HCI_POWER_ON:
859                     // do nothing
860                     break;
861                 case HCI_POWER_OFF:
862                     // no connections yet, just turn it off
863                     hci_power_control_off();
864                     break;
865                 case HCI_POWER_SLEEP:
866                     // no connections yet, just turn it off
867                     hci_power_control_sleep();
868                     break;
869             }
870             break;
871 
872         case HCI_STATE_WORKING:
873             switch (power_mode){
874                 case HCI_POWER_ON:
875                     // do nothing
876                     break;
877                 case HCI_POWER_OFF:
878                     // see hci_run
879                     hci_stack.state = HCI_STATE_HALTING;
880                     break;
881                 case HCI_POWER_SLEEP:
882                     // see hci_run
883                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
884                     hci_stack.substate = 0;
885                     break;
886             }
887             break;
888 
889         case HCI_STATE_HALTING:
890             switch (power_mode){
891                 case HCI_POWER_ON:
892                     // set up state machine
893                     hci_stack.state = HCI_STATE_INITIALIZING;
894                     hci_stack.substate = 0;
895                     break;
896                 case HCI_POWER_OFF:
897                     // do nothing
898                     break;
899                 case HCI_POWER_SLEEP:
900                     // see hci_run
901                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
902                     hci_stack.substate = 0;
903                     break;
904             }
905             break;
906 
907         case HCI_STATE_FALLING_ASLEEP:
908             switch (power_mode){
909                 case HCI_POWER_ON:
910 
911 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
912                     // nothing to do, if H4 supports power management
913                     if (bt_control_iphone_power_management_enabled()){
914                         hci_stack.state = HCI_STATE_INITIALIZING;
915                         hci_stack.substate = 6;
916                         break;
917                     }
918 #endif
919                     // set up state machine
920                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
921                     hci_stack.state = HCI_STATE_INITIALIZING;
922                     hci_stack.substate = 0;
923                     break;
924                 case HCI_POWER_OFF:
925                     // see hci_run
926                     hci_stack.state = HCI_STATE_HALTING;
927                     break;
928                 case HCI_POWER_SLEEP:
929                     // do nothing
930                     break;
931             }
932             break;
933 
934         case HCI_STATE_SLEEPING:
935             switch (power_mode){
936                 case HCI_POWER_ON:
937 
938 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
939                     // nothing to do, if H4 supports power management
940                     if (bt_control_iphone_power_management_enabled()){
941                         hci_stack.state = HCI_STATE_INITIALIZING;
942                         hci_stack.substate = 6;
943                         hci_update_scan_enable();
944                         break;
945                     }
946 #endif
947                     err = hci_power_control_wake();
948                     if (err) return err;
949                     // set up state machine
950                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
951                     hci_stack.state = HCI_STATE_INITIALIZING;
952                     hci_stack.substate = 0;
953                     break;
954                 case HCI_POWER_OFF:
955                     hci_stack.state = HCI_STATE_HALTING;
956                     break;
957                 case HCI_POWER_SLEEP:
958                     // do nothing
959                     break;
960             }
961             break;
962     }
963 
964     // create internal event
965 	hci_emit_state();
966 
967 	// trigger next/first action
968 	hci_run();
969 
970     return 0;
971 }
972 
973 static void hci_update_scan_enable(void){
974     // 2 = page scan, 1 = inq scan
975     hci_stack.new_scan_enable_value  = hci_stack.connectable << 1 | hci_stack.discoverable;
976     hci_run();
977 }
978 
979 void hci_discoverable_control(uint8_t enable){
980     if (enable) enable = 1; // normalize argument
981 
982     if (hci_stack.discoverable == enable){
983         hci_emit_discoverable_enabled(hci_stack.discoverable);
984         return;
985     }
986 
987     hci_stack.discoverable = enable;
988     hci_update_scan_enable();
989 }
990 
991 void hci_connectable_control(uint8_t enable){
992     if (enable) enable = 1; // normalize argument
993 
994     // don't emit event
995     if (hci_stack.connectable == enable) return;
996 
997     hci_stack.connectable = enable;
998     hci_update_scan_enable();
999 }
1000 
1001 void hci_run(){
1002 
1003     hci_connection_t * connection;
1004     linked_item_t * it;
1005 
1006     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1007 
1008     // global/non-connection oriented commands
1009 
1010     // decline incoming connections
1011     if (hci_stack.decline_reason){
1012         uint8_t reason = hci_stack.decline_reason;
1013         hci_stack.decline_reason = 0;
1014         hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason);
1015     }
1016 
1017     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1018 
1019     // send scan enable
1020     if (hci_stack.new_scan_enable_value != 0xff){
1021         hci_send_cmd(&hci_write_scan_enable, hci_stack.new_scan_enable_value);
1022         hci_stack.new_scan_enable_value = 0xff;
1023     }
1024 
1025     // send pending HCI commands
1026     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
1027 
1028         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1029 
1030         connection = (hci_connection_t *) it;
1031 
1032         if (connection->state == RECEIVED_CONNECTION_REQUEST){
1033             log_info("sending hci_accept_connection_request\n");
1034             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1035             connection->state = ACCEPTED_CONNECTION_REQUEST;
1036         }
1037 
1038         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1039 
1040         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1041             link_key_t link_key;
1042             log_info("responding to link key request\n");
1043             if ( hci_stack.remote_device_db->get_link_key( &connection->address, &link_key)){
1044                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1045             } else {
1046                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1047             }
1048             connection->authentication_flags &= ~HANDLE_LINK_KEY_REQUEST;
1049         }
1050     }
1051 
1052     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1053 
1054     switch (hci_stack.state){
1055         case HCI_STATE_INITIALIZING:
1056             // log_info("hci_init: substate %u\n", hci_stack.substate);
1057             if (hci_stack.substate % 2) {
1058                 // odd: waiting for command completion
1059                 return;
1060             }
1061             switch (hci_stack.substate >> 1){
1062                 case 0: // RESET
1063                     hci_send_cmd(&hci_reset);
1064                     if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){
1065                         // skip baud change
1066                         hci_stack.substate = 4; // >> 1 = 2
1067                     }
1068                     break;
1069                 case 1: // SEND BAUD CHANGE
1070                     hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_packet_buffer);
1071                     hci_send_cmd_packet(hci_stack.hci_packet_buffer, 3 + hci_stack.hci_packet_buffer[2]);
1072                     break;
1073                 case 2: // LOCAL BAUD CHANGE
1074                     hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main);
1075                     hci_stack.substate += 2;
1076                     // break missing here for fall through
1077 
1078                 case 3:
1079                     // custom initialization
1080                     if (hci_stack.control && hci_stack.control->next_cmd){
1081                         int valid_cmd = (*hci_stack.control->next_cmd)(hci_stack.config, hci_stack.hci_packet_buffer);
1082                         if (valid_cmd){
1083                             int size = 3 + hci_stack.hci_packet_buffer[2];
1084                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack.hci_packet_buffer, size);
1085                             hci_stack.substate = 4; // more init commands
1086                             break;
1087                         }
1088                         log_info("hci_run: init script done\n\r");
1089                     }
1090                     // otherwise continue
1091 					hci_send_cmd(&hci_read_bd_addr);
1092 					break;
1093 				case 4:
1094 					hci_send_cmd(&hci_read_buffer_size);
1095 					break;
1096                 case 5:
1097                     // ca. 15 sec
1098                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1099                     break;
1100 				case 6:
1101 					hci_send_cmd(&hci_write_scan_enable, (hci_stack.connectable << 1) | hci_stack.discoverable); // page scan
1102 					break;
1103                 case 7:
1104 #ifndef EMBEDDED
1105                 {
1106                     char hostname[30];
1107                     gethostname(hostname, 30);
1108                     hostname[29] = '\0';
1109                     hci_send_cmd(&hci_write_local_name, hostname);
1110                     break;
1111                 }
1112                 case 8:
1113 #ifdef USE_BLUETOOL
1114                     hci_send_cmd(&hci_write_class_of_device, 0x007a020c); // Smartphone
1115                     break;
1116 
1117                 case 9:
1118 #endif
1119 #endif
1120                     // done.
1121                     hci_stack.state = HCI_STATE_WORKING;
1122                     hci_emit_state();
1123                     break;
1124                 default:
1125                     break;
1126             }
1127             hci_stack.substate++;
1128             break;
1129 
1130         case HCI_STATE_HALTING:
1131 
1132             log_info("HCI_STATE_HALTING\n");
1133             // close all open connections
1134             connection =  (hci_connection_t *) hci_stack.connections;
1135             if (connection){
1136 
1137                 // send disconnect
1138                 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1139 
1140                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1141                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1142 
1143                 // send disconnected event right away - causes higher layer connections to get closed, too.
1144                 hci_shutdown_connection(connection);
1145                 return;
1146             }
1147             log_info("HCI_STATE_HALTING, calling off\n");
1148 
1149             // switch mode
1150             hci_power_control_off();
1151 
1152             log_info("HCI_STATE_HALTING, emitting state\n");
1153             hci_emit_state();
1154             log_info("HCI_STATE_HALTING, done\n");
1155             break;
1156 
1157         case HCI_STATE_FALLING_ASLEEP:
1158             switch(hci_stack.substate) {
1159                 case 0:
1160                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1161                     // close all open connections
1162                     connection =  (hci_connection_t *) hci_stack.connections;
1163 
1164 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1165                     // don't close connections, if H4 supports power management
1166                     if (bt_control_iphone_power_management_enabled()){
1167                         connection = NULL;
1168                     }
1169 #endif
1170                     if (connection){
1171 
1172                         // send disconnect
1173                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1174 
1175                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1176                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1177 
1178                         // send disconnected event right away - causes higher layer connections to get closed, too.
1179                         hci_shutdown_connection(connection);
1180                         return;
1181                     }
1182 
1183                     // disable page and inquiry scan
1184                     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1185 
1186                     log_info("HCI_STATE_HALTING, disabling inq cans\n");
1187                     hci_send_cmd(&hci_write_scan_enable, hci_stack.connectable << 1); // drop inquiry scan but keep page scan
1188 
1189                     // continue in next sub state
1190                     hci_stack.substate++;
1191                     break;
1192                 case 1:
1193                     // wait for command complete "hci_write_scan_enable" in event_handler();
1194                     break;
1195                 case 2:
1196                     log_info("HCI_STATE_HALTING, calling sleep\n");
1197 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1198                     // don't actually go to sleep, if H4 supports power management
1199                     if (bt_control_iphone_power_management_enabled()){
1200                         // SLEEP MODE reached
1201                         hci_stack.state = HCI_STATE_SLEEPING;
1202                         hci_emit_state();
1203                         break;
1204                     }
1205 #endif
1206                     // switch mode
1207                     hci_power_control_sleep();  // changes hci_stack.state to SLEEP
1208                     hci_emit_state();
1209                     break;
1210 
1211                 default:
1212                     break;
1213             }
1214             break;
1215 
1216         default:
1217             break;
1218     }
1219 }
1220 
1221 int hci_send_cmd_packet(uint8_t *packet, int size){
1222     bd_addr_t addr;
1223     hci_connection_t * conn;
1224     // house-keeping
1225 
1226     // create_connection?
1227     if (IS_COMMAND(packet, hci_create_connection)){
1228         bt_flip_addr(addr, &packet[3]);
1229         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1230         conn = connection_for_address(addr);
1231         if (conn) {
1232             // if connection exists
1233             if (conn->state == OPEN) {
1234                 // and OPEN, emit connection complete command
1235                 hci_emit_connection_complete(conn, 0);
1236             }
1237             //    otherwise, just ignore as it is already in the open process
1238             return 0; // don't sent packet to controller
1239 
1240         }
1241         // create connection struct and register, state = SENT_CREATE_CONNECTION
1242         conn = create_connection_for_addr(addr);
1243         if (!conn){
1244             // notify client that alloc failed
1245             hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1246             return 0; // don't sent packet to controller
1247         }
1248         conn->state = SENT_CREATE_CONNECTION;
1249     }
1250 
1251     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1252         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1253     }
1254     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1255         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1256     }
1257     if (IS_COMMAND(packet, hci_pin_code_request_reply)){
1258         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY);
1259     }
1260     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){
1261         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY);
1262     }
1263 
1264     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1265         if (hci_stack.remote_device_db){
1266             bt_flip_addr(addr, &packet[3]);
1267             hci_stack.remote_device_db->delete_link_key(&addr);
1268         }
1269     }
1270 
1271     hci_stack.num_cmd_packets--;
1272     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1273 }
1274 
1275 /**
1276  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1277  */
1278 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1279     va_list argptr;
1280     va_start(argptr, cmd);
1281     uint16_t size = hci_create_cmd_internal(hci_stack.hci_packet_buffer, cmd, argptr);
1282     va_end(argptr);
1283     return hci_send_cmd_packet(hci_stack.hci_packet_buffer, size);
1284 }
1285 
1286 // Create various non-HCI events.
1287 // TODO: generalize, use table similar to hci_create_command
1288 
1289 void hci_emit_state(){
1290     uint8_t event[3];
1291     event[0] = BTSTACK_EVENT_STATE;
1292     event[1] = sizeof(event) - 2;
1293     event[2] = hci_stack.state;
1294     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1295     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1296 }
1297 
1298 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1299     uint8_t event[13];
1300     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1301     event[1] = sizeof(event) - 2;
1302     event[2] = status;
1303     bt_store_16(event, 3, conn->con_handle);
1304     bt_flip_addr(&event[5], conn->address);
1305     event[11] = 1; // ACL connection
1306     event[12] = 0; // encryption disabled
1307     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1308     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1309 }
1310 
1311 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1312     uint8_t event[6];
1313     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1314     event[1] = sizeof(event) - 2;
1315     event[2] = 0; // status = OK
1316     bt_store_16(event, 3, handle);
1317     event[5] = reason;
1318     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1319     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1320 }
1321 
1322 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1323     uint8_t event[4];
1324     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1325     event[1] = sizeof(event) - 2;
1326     bt_store_16(event, 2, conn->con_handle);
1327     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1328     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1329 }
1330 
1331 void hci_emit_nr_connections_changed(){
1332     uint8_t event[3];
1333     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1334     event[1] = sizeof(event) - 2;
1335     event[2] = nr_hci_connections();
1336     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1337     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1338 }
1339 
1340 void hci_emit_hci_open_failed(){
1341     uint8_t event[2];
1342     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1343     event[1] = sizeof(event) - 2;
1344     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1345     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1346 }
1347 
1348 #ifndef EMBEDDED
1349 void hci_emit_btstack_version() {
1350     uint8_t event[6];
1351     event[0] = BTSTACK_EVENT_VERSION;
1352     event[1] = sizeof(event) - 2;
1353     event[2] = BTSTACK_MAJOR;
1354     event[3] = BTSTACK_MINOR;
1355     bt_store_16(event, 4, BTSTACK_REVISION);
1356     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1357     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1358 }
1359 #endif
1360 
1361 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1362     uint8_t event[3];
1363     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1364     event[1] = sizeof(event) - 2;
1365     event[2] = enabled;
1366     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1367     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1368 }
1369 
1370 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1371     uint8_t event[2+1+6+248];
1372     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1373     event[1] = sizeof(event) - 2;
1374     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1375     bt_flip_addr(&event[3], *addr);
1376     memcpy(&event[9], name, 248);
1377     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1378     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1379 }
1380 
1381 void hci_emit_discoverable_enabled(uint8_t enabled){
1382     uint8_t event[3];
1383     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1384     event[1] = sizeof(event) - 2;
1385     event[2] = enabled;
1386     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1387     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1388 }
1389