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