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