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