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