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