xref: /btstack/src/hci.c (revision 79bbfa0b87edbff70f5406a6c52f2cbc768cff68)
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 
711 void hci_close(){
712     // close remote device db
713     if (hci_stack.remote_device_db) {
714         hci_stack.remote_device_db->close();
715     }
716 }
717 
718 // State-Module-Driver overview
719 // state                    module  low-level
720 // HCI_STATE_OFF             off      close
721 // HCI_STATE_INITIALIZING,   on       open
722 // HCI_STATE_WORKING,        on       open
723 // HCI_STATE_HALTING,        on       open
724 // HCI_STATE_SLEEPING,    off/sleep   close
725 // HCI_STATE_FALLING_ASLEEP  on       open
726 
727 static int hci_power_control_on(void){
728 
729     // power on
730     int err = 0;
731     if (hci_stack.control && hci_stack.control->on){
732         err = (*hci_stack.control->on)(hci_stack.config);
733     }
734     if (err){
735         log_error( "POWER_ON failed\n");
736         hci_emit_hci_open_failed();
737         return err;
738     }
739 
740     // open low-level device
741     err = hci_stack.hci_transport->open(hci_stack.config);
742     if (err){
743         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
744         if (hci_stack.control && hci_stack.control->off){
745             (*hci_stack.control->off)(hci_stack.config);
746         }
747         hci_emit_hci_open_failed();
748         return err;
749     }
750     return 0;
751 }
752 
753 static void hci_power_control_off(void){
754 
755     log_info("hci_power_control_off\n");
756 
757     // close low-level device
758     hci_stack.hci_transport->close(hci_stack.config);
759 
760     log_info("hci_power_control_off - hci_transport closed\n");
761 
762     // power off
763     if (hci_stack.control && hci_stack.control->off){
764         (*hci_stack.control->off)(hci_stack.config);
765     }
766 
767     log_info("hci_power_control_off - control closed\n");
768 
769     hci_stack.state = HCI_STATE_OFF;
770 }
771 
772 static void hci_power_control_sleep(void){
773 
774     log_info("hci_power_control_sleep\n");
775 
776 #if 0
777     // don't close serial port during sleep
778 
779     // close low-level device
780     hci_stack.hci_transport->close(hci_stack.config);
781 #endif
782 
783     // sleep mode
784     if (hci_stack.control && hci_stack.control->sleep){
785         (*hci_stack.control->sleep)(hci_stack.config);
786     }
787 
788     hci_stack.state = HCI_STATE_SLEEPING;
789 }
790 
791 static int hci_power_control_wake(void){
792 
793     log_info("hci_power_control_wake\n");
794 
795     // wake on
796     if (hci_stack.control && hci_stack.control->wake){
797         (*hci_stack.control->wake)(hci_stack.config);
798     }
799 
800 #if 0
801     // open low-level device
802     int err = hci_stack.hci_transport->open(hci_stack.config);
803     if (err){
804         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
805         if (hci_stack.control && hci_stack.control->off){
806             (*hci_stack.control->off)(hci_stack.config);
807         }
808         hci_emit_hci_open_failed();
809         return err;
810     }
811 #endif
812 
813     return 0;
814 }
815 
816 
817 int hci_power_control(HCI_POWER_MODE power_mode){
818 
819     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state);
820 
821     int err = 0;
822     switch (hci_stack.state){
823 
824         case HCI_STATE_OFF:
825             switch (power_mode){
826                 case HCI_POWER_ON:
827                     err = hci_power_control_on();
828                     if (err) return err;
829                     // set up state machine
830                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
831                     hci_stack.state = HCI_STATE_INITIALIZING;
832                     hci_stack.substate = 0;
833                     break;
834                 case HCI_POWER_OFF:
835                     // do nothing
836                     break;
837                 case HCI_POWER_SLEEP:
838                     // do nothing (with SLEEP == OFF)
839                     break;
840             }
841             break;
842 
843         case HCI_STATE_INITIALIZING:
844             switch (power_mode){
845                 case HCI_POWER_ON:
846                     // do nothing
847                     break;
848                 case HCI_POWER_OFF:
849                     // no connections yet, just turn it off
850                     hci_power_control_off();
851                     break;
852                 case HCI_POWER_SLEEP:
853                     // no connections yet, just turn it off
854                     hci_power_control_sleep();
855                     break;
856             }
857             break;
858 
859         case HCI_STATE_WORKING:
860             switch (power_mode){
861                 case HCI_POWER_ON:
862                     // do nothing
863                     break;
864                 case HCI_POWER_OFF:
865                     // see hci_run
866                     hci_stack.state = HCI_STATE_HALTING;
867                     break;
868                 case HCI_POWER_SLEEP:
869                     // see hci_run
870                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
871                     hci_stack.substate = 0;
872                     break;
873             }
874             break;
875 
876         case HCI_STATE_HALTING:
877             switch (power_mode){
878                 case HCI_POWER_ON:
879                     // set up state machine
880                     hci_stack.state = HCI_STATE_INITIALIZING;
881                     hci_stack.substate = 0;
882                     break;
883                 case HCI_POWER_OFF:
884                     // do nothing
885                     break;
886                 case HCI_POWER_SLEEP:
887                     // see hci_run
888                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
889                     hci_stack.substate = 0;
890                     break;
891             }
892             break;
893 
894         case HCI_STATE_FALLING_ASLEEP:
895             switch (power_mode){
896                 case HCI_POWER_ON:
897 
898 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
899                     // nothing to do, if H4 supports power management
900                     if (bt_control_iphone_power_management_enabled()){
901                         hci_stack.state = HCI_STATE_INITIALIZING;
902                         hci_stack.substate = 6;
903                         break;
904                     }
905 #endif
906                     // set up state machine
907                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
908                     hci_stack.state = HCI_STATE_INITIALIZING;
909                     hci_stack.substate = 0;
910                     break;
911                 case HCI_POWER_OFF:
912                     // see hci_run
913                     hci_stack.state = HCI_STATE_HALTING;
914                     break;
915                 case HCI_POWER_SLEEP:
916                     // do nothing
917                     break;
918             }
919             break;
920 
921         case HCI_STATE_SLEEPING:
922             switch (power_mode){
923                 case HCI_POWER_ON:
924 
925 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
926                     // nothing to do, if H4 supports power management
927                     if (bt_control_iphone_power_management_enabled()){
928                         hci_stack.state = HCI_STATE_INITIALIZING;
929                         hci_stack.substate = 6;
930                         break;
931                     }
932 #endif
933                     err = hci_power_control_wake();
934                     if (err) return err;
935                     // set up state machine
936                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
937                     hci_stack.state = HCI_STATE_INITIALIZING;
938                     hci_stack.substate = 0;
939                     break;
940                 case HCI_POWER_OFF:
941                     hci_stack.state = HCI_STATE_HALTING;
942                     break;
943                 case HCI_POWER_SLEEP:
944                     // do nothing
945                     break;
946             }
947             break;
948     }
949 
950     // create internal event
951 	hci_emit_state();
952 
953 	// trigger next/first action
954 	hci_run();
955 
956     return 0;
957 }
958 
959 void hci_discoverable_control(uint8_t enable){
960     if (enable) enable = 1; // normalize argument
961 
962     if (hci_stack.discoverable == enable){
963         hci_emit_discoverable_enabled(hci_stack.discoverable);
964         return;
965     }
966 
967     // store request to send command but accept in higher layer view
968     hci_stack.new_scan_enable_value = 2 | enable; // 1 = inq scan, 2 = page scan
969     hci_stack.discoverable = enable;
970 
971     hci_run();
972 }
973 
974 void hci_run(){
975 
976     hci_connection_t * connection;
977     linked_item_t * it;
978 
979     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
980 
981     // global/non-connection oriented commands
982 
983     // decline incoming connections
984     if (hci_stack.decline_reason){
985         uint8_t reason = hci_stack.decline_reason;
986         hci_stack.decline_reason = 0;
987         hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason);
988     }
989 
990     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
991 
992     // send scan enable
993     if (hci_stack.new_scan_enable_value != 0xff){
994         hci_send_cmd(&hci_write_scan_enable, hci_stack.new_scan_enable_value);
995         hci_stack.new_scan_enable_value = 0xff;
996     }
997 
998     // send pending HCI commands
999     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
1000 
1001         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1002 
1003         connection = (hci_connection_t *) it;
1004 
1005         if (connection->state == RECEIVED_CONNECTION_REQUEST){
1006             log_info("sending hci_accept_connection_request\n");
1007             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1008             connection->state = ACCEPTED_CONNECTION_REQUEST;
1009         }
1010 
1011         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1012 
1013         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1014             link_key_t link_key;
1015             log_info("responding to link key request\n");
1016             if ( hci_stack.remote_device_db->get_link_key( &connection->address, &link_key)){
1017                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
1018             } else {
1019                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
1020             }
1021             connection->authentication_flags &= ~HANDLE_LINK_KEY_REQUEST;
1022         }
1023     }
1024 
1025     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1026 
1027     switch (hci_stack.state){
1028         case HCI_STATE_INITIALIZING:
1029             // log_info("hci_init: substate %u\n", hci_stack.substate);
1030             if (hci_stack.substate % 2) {
1031                 // odd: waiting for command completion
1032                 return;
1033             }
1034             switch (hci_stack.substate >> 1){
1035                 case 0: // RESET
1036                     hci_send_cmd(&hci_reset);
1037                     if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){
1038                         // skip baud change
1039                         hci_stack.substate = 4; // >> 1 = 2
1040                     }
1041                     break;
1042                 case 1: // SEND BAUD CHANGE
1043                     hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_packet_buffer);
1044                     hci_send_cmd_packet(hci_stack.hci_packet_buffer, 3 + hci_stack.hci_packet_buffer[2]);
1045                     break;
1046                 case 2: // LOCAL BAUD CHANGE
1047                     hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main);
1048                     hci_stack.substate += 2;
1049                     // break missing here for fall through
1050 
1051                 case 3:
1052                     // custom initialization
1053                     if (hci_stack.control && hci_stack.control->next_cmd){
1054                         int valid_cmd = (*hci_stack.control->next_cmd)(hci_stack.config, hci_stack.hci_packet_buffer);
1055                         if (valid_cmd){
1056                             int size = 3 + hci_stack.hci_packet_buffer[2];
1057                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack.hci_packet_buffer, size);
1058                             hci_stack.substate = 4; // more init commands
1059                             break;
1060                         }
1061                         log_info("hci_run: init script done\n\r");
1062                     }
1063                     // otherwise continue
1064 					hci_send_cmd(&hci_read_bd_addr);
1065 					break;
1066 				case 4:
1067 					hci_send_cmd(&hci_read_buffer_size);
1068 					break;
1069                 case 5:
1070                     // ca. 15 sec
1071                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1072                     break;
1073 				case 6:
1074 					hci_send_cmd(&hci_write_scan_enable, 2 | hci_stack.discoverable); // page scan
1075 					break;
1076                 case 7:
1077 #ifndef EMBEDDED
1078                 {
1079                     char hostname[30];
1080                     gethostname(hostname, 30);
1081                     hostname[29] = '\0';
1082                     hci_send_cmd(&hci_write_local_name, hostname);
1083                     break;
1084                 }
1085                 case 8:
1086 #ifdef USE_BLUETOOL
1087                     hci_send_cmd(&hci_write_class_of_device, 0x007a020c); // Smartphone
1088                     break;
1089 
1090                 case 9:
1091 #endif
1092 #endif
1093                     // done.
1094                     hci_stack.state = HCI_STATE_WORKING;
1095                     hci_emit_state();
1096                     break;
1097                 default:
1098                     break;
1099             }
1100             hci_stack.substate++;
1101             break;
1102 
1103         case HCI_STATE_HALTING:
1104 
1105             log_info("HCI_STATE_HALTING\n");
1106             // close all open connections
1107             connection =  (hci_connection_t *) hci_stack.connections;
1108             if (connection){
1109 
1110                 // send disconnect
1111                 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1112 
1113                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1114                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1115 
1116                 // send disconnected event right away - causes higher layer connections to get closed, too.
1117                 hci_shutdown_connection(connection);
1118                 return;
1119             }
1120             log_info("HCI_STATE_HALTING, calling off\n");
1121 
1122             // switch mode
1123             hci_power_control_off();
1124 
1125             log_info("HCI_STATE_HALTING, emitting state\n");
1126             hci_emit_state();
1127             log_info("HCI_STATE_HALTING, done\n");
1128             break;
1129 
1130         case HCI_STATE_FALLING_ASLEEP:
1131             switch(hci_stack.substate) {
1132                 case 0:
1133                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1134                     // close all open connections
1135                     connection =  (hci_connection_t *) hci_stack.connections;
1136 
1137 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1138                     // don't close connections, if H4 supports power management
1139                     if (bt_control_iphone_power_management_enabled()){
1140                         connection = NULL;
1141                     }
1142 #endif
1143                     if (connection){
1144 
1145                         // send disconnect
1146                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1147 
1148                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
1149                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1150 
1151                         // send disconnected event right away - causes higher layer connections to get closed, too.
1152                         hci_shutdown_connection(connection);
1153                         return;
1154                     }
1155 
1156                     // disable page and inquiry scan
1157                     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1158 
1159                     log_info("HCI_STATE_HALTING, disabling inq & page scans\n");
1160                     hci_send_cmd(&hci_write_scan_enable, 0); // none
1161 
1162                     // continue in next sub state
1163                     hci_stack.substate++;
1164                     break;
1165                 case 1:
1166                     // wait for command complete "hci_write_scan_enable" in event_handler();
1167                     break;
1168                 case 2:
1169                     log_info("HCI_STATE_HALTING, calling sleep\n");
1170 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1171                     // don't actually go to sleep, if H4 supports power management
1172                     if (bt_control_iphone_power_management_enabled()){
1173                         // SLEEP MODE reached
1174                         hci_stack.state = HCI_STATE_SLEEPING;
1175                         hci_emit_state();
1176                         break;
1177                     }
1178 #endif
1179                     // switch mode
1180                     hci_power_control_sleep();  // changes hci_stack.state to SLEEP
1181                     hci_emit_state();
1182                     break;
1183 
1184                 default:
1185                     break;
1186             }
1187             break;
1188 
1189         default:
1190             break;
1191     }
1192 }
1193 
1194 int hci_send_cmd_packet(uint8_t *packet, int size){
1195     bd_addr_t addr;
1196     hci_connection_t * conn;
1197     // house-keeping
1198 
1199     // create_connection?
1200     if (IS_COMMAND(packet, hci_create_connection)){
1201         bt_flip_addr(addr, &packet[3]);
1202         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1203         conn = connection_for_address(addr);
1204         if (conn) {
1205             // if connection exists
1206             if (conn->state == OPEN) {
1207                 // and OPEN, emit connection complete command
1208                 hci_emit_connection_complete(conn, 0);
1209             }
1210             //    otherwise, just ignore as it is already in the open process
1211             return 0; // don't sent packet to controller
1212 
1213         }
1214         // create connection struct and register, state = SENT_CREATE_CONNECTION
1215         conn = create_connection_for_addr(addr);
1216         if (!conn){
1217             // notify client that alloc failed
1218             hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1219             return 0; // don't sent packet to controller
1220         }
1221         conn->state = SENT_CREATE_CONNECTION;
1222     }
1223 
1224     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1225         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1226     }
1227     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1228         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1229     }
1230     if (IS_COMMAND(packet, hci_pin_code_request_reply)){
1231         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY);
1232     }
1233     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){
1234         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY);
1235     }
1236 
1237     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1238         if (hci_stack.remote_device_db){
1239             bt_flip_addr(addr, &packet[3]);
1240             hci_stack.remote_device_db->delete_link_key(&addr);
1241         }
1242     }
1243 
1244     hci_stack.num_cmd_packets--;
1245     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1246 }
1247 
1248 /**
1249  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1250  */
1251 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1252     va_list argptr;
1253     va_start(argptr, cmd);
1254     uint16_t size = hci_create_cmd_internal(hci_stack.hci_packet_buffer, cmd, argptr);
1255     va_end(argptr);
1256     return hci_send_cmd_packet(hci_stack.hci_packet_buffer, size);
1257 }
1258 
1259 // Create various non-HCI events.
1260 // TODO: generalize, use table similar to hci_create_command
1261 
1262 void hci_emit_state(){
1263     uint8_t event[3];
1264     event[0] = BTSTACK_EVENT_STATE;
1265     event[1] = sizeof(event) - 2;
1266     event[2] = hci_stack.state;
1267     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1268     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1269 }
1270 
1271 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1272     uint8_t event[13];
1273     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1274     event[1] = sizeof(event) - 2;
1275     event[2] = status;
1276     bt_store_16(event, 3, conn->con_handle);
1277     bt_flip_addr(&event[5], conn->address);
1278     event[11] = 1; // ACL connection
1279     event[12] = 0; // encryption disabled
1280     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1281     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1282 }
1283 
1284 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1285     uint8_t event[6];
1286     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1287     event[1] = sizeof(event) - 2;
1288     event[2] = 0; // status = OK
1289     bt_store_16(event, 3, handle);
1290     event[5] = reason;
1291     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1292     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1293 }
1294 
1295 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1296     uint8_t event[4];
1297     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1298     event[1] = sizeof(event) - 2;
1299     bt_store_16(event, 2, conn->con_handle);
1300     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1301     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1302 }
1303 
1304 void hci_emit_nr_connections_changed(){
1305     uint8_t event[3];
1306     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1307     event[1] = sizeof(event) - 2;
1308     event[2] = nr_hci_connections();
1309     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1310     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1311 }
1312 
1313 void hci_emit_hci_open_failed(){
1314     uint8_t event[2];
1315     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1316     event[1] = sizeof(event) - 2;
1317     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1318     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1319 }
1320 
1321 #ifndef EMBEDDED
1322 void hci_emit_btstack_version() {
1323     uint8_t event[6];
1324     event[0] = BTSTACK_EVENT_VERSION;
1325     event[1] = sizeof(event) - 2;
1326     event[2] = BTSTACK_MAJOR;
1327     event[3] = BTSTACK_MINOR;
1328     bt_store_16(event, 4, BTSTACK_REVISION);
1329     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1330     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1331 }
1332 #endif
1333 
1334 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1335     uint8_t event[3];
1336     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1337     event[1] = sizeof(event) - 2;
1338     event[2] = enabled;
1339     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1340     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1341 }
1342 
1343 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1344     uint8_t event[2+1+6+248];
1345     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1346     event[1] = sizeof(event) - 2;
1347     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1348     bt_flip_addr(&event[3], *addr);
1349     memcpy(&event[9], name, 248);
1350     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1351     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1352 }
1353 
1354 void hci_emit_discoverable_enabled(uint8_t enabled){
1355     uint8_t event[3];
1356     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1357     event[1] = sizeof(event) - 2;
1358     event[2] = enabled;
1359     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1360     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1361 }
1362