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