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