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