xref: /btstack/src/hci.c (revision 8747d67f7db2bf8c425c0cecaf92928cc07ef4db)
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                         hci_stack.state = HCI_STATE_INITIALIZING;
853                         hci_stack.substate = 6;
854                         break;
855                     }
856 #endif
857                     // set up state machine
858                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
859                     hci_stack.state = HCI_STATE_INITIALIZING;
860                     hci_stack.substate = 0;
861                     break;
862                 case HCI_POWER_OFF:
863                     // see hci_run
864                     hci_stack.state = HCI_STATE_HALTING;
865                     break;
866                 case HCI_POWER_SLEEP:
867                     // do nothing
868                     break;
869             }
870             break;
871 
872         case HCI_STATE_SLEEPING:
873             switch (power_mode){
874                 case HCI_POWER_ON:
875 
876 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
877                     // nothing to do, if H4 supports power management
878                     if (bt_control_iphone_power_management_enabled()){
879                         hci_stack.state = HCI_STATE_INITIALIZING;
880                         hci_stack.substate = 6;
881                         break;
882                     }
883 #endif
884                     err = hci_power_control_wake();
885                     if (err) return err;
886                     // set up state machine
887                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
888                     hci_stack.state = HCI_STATE_INITIALIZING;
889                     hci_stack.substate = 0;
890                     break;
891                 case HCI_POWER_OFF:
892                     hci_stack.state = HCI_STATE_HALTING;
893                     break;
894                 case HCI_POWER_SLEEP:
895                     // do nothing
896                     break;
897             }
898             break;
899     }
900 
901     // create internal event
902 	hci_emit_state();
903 
904 	// trigger next/first action
905 	hci_run();
906 
907     return 0;
908 }
909 
910 void hci_discoverable_control(uint8_t enable){
911     if (enable) enable = 1; // normalize argument
912 
913     if (hci_stack.discoverable == enable){
914         hci_emit_discoverable_enabled(hci_stack.discoverable);
915         return;
916     }
917 
918     // store request to send command but accept in higher layer view
919     hci_stack.new_scan_enable_value = 2 | enable; // 1 = inq scan, 2 = page scan
920     hci_stack.discoverable = enable;
921 
922     hci_run();
923 }
924 
925 void hci_run(){
926 
927     hci_connection_t * connection;
928     linked_item_t * it;
929 
930     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
931 
932     // global/non-connection oriented commands
933 
934     // decline incoming connections
935     if (hci_stack.decline_reason){
936         uint8_t reason = hci_stack.decline_reason;
937         hci_stack.decline_reason = 0;
938         hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason);
939     }
940 
941     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
942 
943     // send scan enable
944     if (hci_stack.new_scan_enable_value != 0xff){
945         hci_send_cmd(&hci_write_scan_enable, hci_stack.new_scan_enable_value);
946         hci_stack.new_scan_enable_value = 0xff;
947     }
948 
949     // send pending HCI commands
950     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
951 
952         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
953 
954         connection = (hci_connection_t *) it;
955 
956         if (connection->state == RECEIVED_CONNECTION_REQUEST){
957             log_info("sending hci_accept_connection_request\n");
958             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
959             connection->state = ACCEPTED_CONNECTION_REQUEST;
960         }
961 
962         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
963 
964         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
965             link_key_t link_key;
966             log_info("responding to link key request\n");
967             if ( hci_stack.remote_device_db->get_link_key( &connection->address, &link_key)){
968                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
969             } else {
970                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
971             }
972             connection->authentication_flags &= ~HANDLE_LINK_KEY_REQUEST;
973         }
974     }
975 
976     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
977 
978     switch (hci_stack.state){
979         case HCI_STATE_INITIALIZING:
980             // log_info("hci_init: substate %u\n", hci_stack.substate);
981             if (hci_stack.substate % 2) {
982                 // odd: waiting for command completion
983                 return;
984             }
985             switch (hci_stack.substate >> 1){
986                 case 0: // RESET
987                     hci_send_cmd(&hci_reset);
988                     if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){
989                         // skip baud change
990                         hci_stack.substate = 4; // >> 1 = 2
991                     }
992                     break;
993                 case 1: // SEND BAUD CHANGE
994                     hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_packet_buffer);
995                     hci_send_cmd_packet(hci_stack.hci_packet_buffer, 3 + hci_stack.hci_packet_buffer[2]);
996                     break;
997                 case 2: // LOCAL BAUD CHANGE
998                     hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main);
999                     hci_stack.substate += 2;
1000                     // break missing here for fall through
1001 
1002                 case 3:
1003                     // custom initialization
1004                     if (hci_stack.control && hci_stack.control->next_cmd){
1005                         int valid_cmd = (*hci_stack.control->next_cmd)(hci_stack.config, hci_stack.hci_packet_buffer);
1006                         if (valid_cmd){
1007                             int size = 3 + hci_stack.hci_packet_buffer[2];
1008                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack.hci_packet_buffer, size);
1009                             hci_stack.substate = 4; // more init commands
1010                             break;
1011                         }
1012                         log_info("hci_run: init script done\n\r");
1013                     }
1014                     // otherwise continue
1015 					hci_send_cmd(&hci_read_bd_addr);
1016 					break;
1017 				case 4:
1018 					hci_send_cmd(&hci_read_buffer_size);
1019 					break;
1020                 case 5:
1021                     // ca. 15 sec
1022                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1023                     break;
1024 				case 6:
1025 					hci_send_cmd(&hci_write_scan_enable, 2 | hci_stack.discoverable); // page scan
1026 					break;
1027                 case 7:
1028 #ifndef EMBEDDED
1029                 {
1030                     char hostname[30];
1031                     gethostname(hostname, 30);
1032                     hostname[29] = '\0';
1033                     hci_send_cmd(&hci_write_local_name, hostname);
1034                     break;
1035                 }
1036                 case 8:
1037 #ifdef USE_BLUETOOL
1038                     hci_send_cmd(&hci_write_class_of_device, 0x007a020c); // Smartphone
1039                     break;
1040 
1041                 case 9:
1042 #endif
1043 #endif
1044                     // done.
1045                     hci_stack.state = HCI_STATE_WORKING;
1046                     hci_emit_state();
1047                     break;
1048                 default:
1049                     break;
1050             }
1051             hci_stack.substate++;
1052             break;
1053 
1054         case HCI_STATE_HALTING:
1055 
1056             log_info("HCI_STATE_HALTING\n");
1057             // close all open connections
1058             connection =  (hci_connection_t *) hci_stack.connections;
1059             if (connection){
1060 
1061                 // send disconnect
1062                 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1063 
1064                 log_info("HCI_STATE_HALTING, connection %lu, handle %u\n", (uintptr_t) connection, (uint16_t)connection->con_handle);
1065                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1066 
1067                 // send disconnected event right away - causes higher layer connections to get closed, too.
1068                 hci_shutdown_connection(connection);
1069                 return;
1070             }
1071             log_info("HCI_STATE_HALTING, calling off\n");
1072 
1073             // switch mode
1074             hci_power_control_off();
1075 
1076             log_info("HCI_STATE_HALTING, emitting state\n");
1077             hci_emit_state();
1078             log_info("HCI_STATE_HALTING, done\n");
1079             break;
1080 
1081         case HCI_STATE_FALLING_ASLEEP:
1082             switch(hci_stack.substate) {
1083                 case 0:
1084                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1085                     // close all open connections
1086                     connection =  (hci_connection_t *) hci_stack.connections;
1087 
1088 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1089                     // don't close connections, if H4 supports power management
1090                     if (bt_control_iphone_power_management_enabled()){
1091                         connection = NULL;
1092                     }
1093 #endif
1094                     if (connection){
1095 
1096                         // send disconnect
1097                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1098 
1099                         log_info("HCI_STATE_FALLING_ASLEEP, connection %lu, handle %u\n", (uintptr_t) connection, (uint16_t)connection->con_handle);
1100                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1101 
1102                         // send disconnected event right away - causes higher layer connections to get closed, too.
1103                         hci_shutdown_connection(connection);
1104                         return;
1105                     }
1106 
1107                     // disable page and inquiry scan
1108                     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1109 
1110                     log_info("HCI_STATE_HALTING, disabling inq & page scans\n");
1111                     hci_send_cmd(&hci_write_scan_enable, 0); // none
1112 
1113                     // continue in next sub state
1114                     hci_stack.substate++;
1115                     break;
1116                 case 1:
1117                     // wait for command complete "hci_write_scan_enable" in event_handler();
1118                     break;
1119                 case 2:
1120                     log_info("HCI_STATE_HALTING, calling sleep\n");
1121 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1122                     // don't actually go to sleep, if H4 supports power management
1123                     if (bt_control_iphone_power_management_enabled()){
1124                         // SLEEP MODE reached
1125                         hci_stack.state = HCI_STATE_SLEEPING;
1126                         hci_emit_state();
1127                         break;
1128                     }
1129 #endif
1130                     // switch mode
1131                     hci_power_control_sleep();  // changes hci_stack.state to SLEEP
1132                     hci_emit_state();
1133                     break;
1134 
1135                 default:
1136                     break;
1137             }
1138             break;
1139 
1140         default:
1141             break;
1142     }
1143 }
1144 
1145 int hci_send_cmd_packet(uint8_t *packet, int size){
1146     bd_addr_t addr;
1147     hci_connection_t * conn;
1148     // house-keeping
1149 
1150     // create_connection?
1151     if (IS_COMMAND(packet, hci_create_connection)){
1152         bt_flip_addr(addr, &packet[3]);
1153         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1154         conn = connection_for_address(addr);
1155         if (conn) {
1156             // if connection exists
1157             if (conn->state == OPEN) {
1158                 // and OPEN, emit connection complete command
1159                 hci_emit_connection_complete(conn, 0);
1160             }
1161             //    otherwise, just ignore as it is already in the open process
1162             return 0; // don't sent packet to controller
1163 
1164         }
1165         // create connection struct and register, state = SENT_CREATE_CONNECTION
1166         conn = create_connection_for_addr(addr);
1167         if (!conn){
1168             // notify client that alloc failed
1169             hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1170             return 0; // don't sent packet to controller
1171         }
1172         conn->state = SENT_CREATE_CONNECTION;
1173     }
1174 
1175     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1176         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1177     }
1178     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1179         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1180     }
1181     if (IS_COMMAND(packet, hci_pin_code_request_reply)){
1182         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY);
1183     }
1184     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){
1185         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY);
1186     }
1187 
1188     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1189         if (hci_stack.remote_device_db){
1190             bt_flip_addr(addr, &packet[3]);
1191             hci_stack.remote_device_db->delete_link_key(&addr);
1192         }
1193     }
1194 
1195     hci_stack.num_cmd_packets--;
1196     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1197 }
1198 
1199 /**
1200  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1201  */
1202 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1203     va_list argptr;
1204     va_start(argptr, cmd);
1205     uint16_t size = hci_create_cmd_internal(hci_stack.hci_packet_buffer, cmd, argptr);
1206     va_end(argptr);
1207     return hci_send_cmd_packet(hci_stack.hci_packet_buffer, size);
1208 }
1209 
1210 // Create various non-HCI events.
1211 // TODO: generalize, use table similar to hci_create_command
1212 
1213 void hci_emit_state(){
1214     uint8_t event[3];
1215     event[0] = BTSTACK_EVENT_STATE;
1216     event[1] = sizeof(event) - 2;
1217     event[2] = hci_stack.state;
1218     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1219     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1220 }
1221 
1222 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1223     uint8_t event[13];
1224     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1225     event[1] = sizeof(event) - 2;
1226     event[2] = status;
1227     bt_store_16(event, 3, conn->con_handle);
1228     bt_flip_addr(&event[5], conn->address);
1229     event[11] = 1; // ACL connection
1230     event[12] = 0; // encryption disabled
1231     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1232     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1233 }
1234 
1235 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1236     uint8_t event[6];
1237     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1238     event[1] = sizeof(event) - 2;
1239     event[2] = 0; // status = OK
1240     bt_store_16(event, 3, handle);
1241     event[5] = reason;
1242     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1243     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1244 }
1245 
1246 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1247     uint8_t event[4];
1248     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1249     event[1] = sizeof(event) - 2;
1250     bt_store_16(event, 2, conn->con_handle);
1251     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1252     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1253 }
1254 
1255 void hci_emit_nr_connections_changed(){
1256     uint8_t event[3];
1257     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1258     event[1] = sizeof(event) - 2;
1259     event[2] = nr_hci_connections();
1260     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1261     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1262 }
1263 
1264 void hci_emit_hci_open_failed(){
1265     uint8_t event[2];
1266     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1267     event[1] = sizeof(event) - 2;
1268     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1269     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1270 }
1271 
1272 
1273 void hci_emit_btstack_version() {
1274     uint8_t event[6];
1275     event[0] = BTSTACK_EVENT_VERSION;
1276     event[1] = sizeof(event) - 2;
1277     event[2] = BTSTACK_MAJOR;
1278     event[3] = BTSTACK_MINOR;
1279     bt_store_16(event, 4, BTSTACK_REVISION);
1280     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1281     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1282 }
1283 
1284 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1285     uint8_t event[3];
1286     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1287     event[1] = sizeof(event) - 2;
1288     event[2] = enabled;
1289     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1290     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1291 }
1292 
1293 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1294     uint8_t event[2+1+6+248];
1295     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1296     event[1] = sizeof(event) - 2;
1297     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1298     bt_flip_addr(&event[3], *addr);
1299     memcpy(&event[9], name, 248);
1300     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1301     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1302 }
1303 
1304 void hci_emit_discoverable_enabled(uint8_t enabled){
1305     uint8_t event[3];
1306     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1307     event[1] = sizeof(event) - 2;
1308     event[2] = enabled;
1309     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1310     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1311 }
1312