xref: /btstack/src/hci.c (revision 6ad890d3190eac63ed71b199c2792a0ecd9839f2)
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     // get num_cmd_packets
328     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){
329         // Get Num_HCI_Command_Packets
330         hci_stack.num_cmd_packets = packet[2];
331     }
332 
333     switch (packet[0]) {
334 
335         case HCI_EVENT_COMMAND_COMPLETE:
336             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
337                 // from offset 5
338                 // status
339                 hci_stack.acl_data_packet_length = READ_BT_16(packet, 6);
340                 // ignore: SCO data packet len (8)
341                 hci_stack.total_num_acl_packets  = packet[9];
342                 // ignore: total num SCO packets
343                 if (hci_stack.state == HCI_STATE_INITIALIZING){
344                     log_dbg("hci_read_buffer_size: size %u, count %u\n", hci_stack.acl_data_packet_length, hci_stack.total_num_acl_packets);
345                 }
346             }
347             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
348                 hci_emit_discoverable_enabled(hci_stack.discoverable);
349             }
350             break;
351 
352         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
353             for (i=0; i<packet[2];i++){
354                 handle = READ_BT_16(packet, 3 + 2*i);
355                 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i);
356                 conn = connection_for_handle(handle);
357                 if (!conn){
358                     log_err("hci_number_completed_packet lists unused con handle %u\n", handle);
359                     continue;
360                 }
361                 conn->num_acl_packets_sent -= num_packets;
362                 // log_dbg("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent);
363             }
364             break;
365 
366         case HCI_EVENT_CONNECTION_REQUEST:
367             bt_flip_addr(addr, &packet[2]);
368             // TODO: eval COD 8-10
369             uint8_t link_type = packet[11];
370             log_dbg("Connection_incoming: "); print_bd_addr(addr); log_dbg(", type %u\n", link_type);
371             if (link_type == 1) { // ACL
372                 conn = connection_for_address(addr);
373                 if (!conn) {
374                     conn = create_connection_for_addr(addr);
375                 }
376                 // TODO: check for malloc failure
377                 conn->state = ACCEPTED_CONNECTION_REQUEST;
378                 hci_send_cmd(&hci_accept_connection_request, addr, 1);
379             } else {
380                 // TODO: decline request
381             }
382             break;
383 
384         case HCI_EVENT_CONNECTION_COMPLETE:
385             // Connection management
386             bt_flip_addr(addr, &packet[5]);
387             log_dbg("Connection_complete (status=%u)", packet[2]); print_bd_addr(addr); log_dbg("\n");
388             conn = connection_for_address(addr);
389             if (conn) {
390                 if (!packet[2]){
391                     conn->state = OPEN;
392                     conn->con_handle = READ_BT_16(packet, 3);
393 
394                     gettimeofday(&conn->timestamp, NULL);
395                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
396                     run_loop_add_timer(&conn->timeout);
397 
398                     log_dbg("New connection: handle %u, ", conn->con_handle);
399                     print_bd_addr( conn->address );
400                     log_dbg("\n");
401 
402                     hci_emit_nr_connections_changed();
403                 } else {
404                     // connection failed, remove entry
405                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
406                     free( conn );
407 
408                     // if authentication error, also delete link key
409                     if (packet[2] == 0x05) {
410                         hci_drop_link_key_for_bd_addr(&addr);
411                     }
412                 }
413             }
414             break;
415 
416         case HCI_EVENT_LINK_KEY_REQUEST:
417             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
418             if (!hci_stack.remote_device_db) break;
419             bt_flip_addr(addr, &packet[2]);
420             if ( hci_stack.remote_device_db->get_link_key( &addr, &link_key)){
421                 hci_send_cmd(&hci_link_key_request_reply, &addr, &link_key);
422             } else {
423                 hci_send_cmd(&hci_link_key_request_negative_reply, &addr);
424             }
425             // request already answered
426             return;
427 
428         case HCI_EVENT_LINK_KEY_NOTIFICATION:
429             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_NOTIFICATION);
430             if (!hci_stack.remote_device_db) break;
431             bt_flip_addr(addr, &packet[2]);
432             hci_stack.remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8]);
433             // still forward event to allow dismiss of pairing dialog
434             break;
435 
436         case HCI_EVENT_PIN_CODE_REQUEST:
437             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_PIN_CODE_REQUEST);
438             break;
439 
440         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
441             if (!hci_stack.remote_device_db) break;
442             if (packet[2]) break; // status not ok
443             bt_flip_addr(addr, &packet[3]);
444             bzero(&device_name, sizeof(device_name_t));
445             strncpy((char*) device_name, (char*) &packet[9], 248);
446             hci_stack.remote_device_db->put_name(&addr, &device_name);
447             break;
448 
449         case HCI_EVENT_INQUIRY_RESULT:
450         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
451             if (!hci_stack.remote_device_db) break;
452             // first send inq result packet
453             hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
454             // then send cached remote names
455             for (i=0; i<packet[2];i++){
456                 bt_flip_addr(addr, &packet[3+i*6]);
457                 if (hci_stack.remote_device_db->get_name(&addr, &device_name)){
458                     hci_emit_remote_name_cached(&addr, &device_name);
459                 }
460             }
461             return;
462 
463         case HCI_EVENT_DISCONNECTION_COMPLETE:
464             if (!packet[2]){
465                 handle = READ_BT_16(packet, 3);
466                 hci_connection_t * conn = connection_for_handle(handle);
467                 if (conn) {
468                     hci_shutdown_connection(conn);
469                 }
470             }
471             break;
472 
473         default:
474             break;
475     }
476 
477     // handle BT initialization
478     if (hci_stack.state == HCI_STATE_INITIALIZING){
479         // handle H4 synchronization loss on restart
480         // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){
481         //    hci_stack.substate = 0;
482         // }
483         // handle normal init sequence
484         if (hci_stack.substate % 2){
485             // odd: waiting for event
486             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
487                 hci_stack.substate++;
488             }
489         }
490     }
491 
492     hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
493 
494 	// execute main loop
495 	hci_run();
496 }
497 
498 void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
499     switch (packet_type) {
500         case HCI_EVENT_PACKET:
501             event_handler(packet, size);
502             break;
503         case HCI_ACL_DATA_PACKET:
504             acl_handler(packet, size);
505             break;
506         default:
507             break;
508     }
509 }
510 
511 /** Register HCI packet handlers */
512 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
513     hci_stack.packet_handler = handler;
514 }
515 
516 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t * remote_device_db){
517 
518     // reference to use transport layer implementation
519     hci_stack.hci_transport = transport;
520 
521     // references to used control implementation
522     hci_stack.control = control;
523 
524     // reference to used config
525     hci_stack.config = config;
526 
527     // no connections yet
528     hci_stack.connections = NULL;
529 
530     // empty cmd buffer
531     hci_stack.hci_cmd_buffer = malloc(3+255);
532 
533     // higher level handler
534     hci_stack.packet_handler = dummy_handler;
535 
536     // store and open remote device db
537     hci_stack.remote_device_db = remote_device_db;
538     if (hci_stack.remote_device_db) {
539         hci_stack.remote_device_db->open();
540     }
541 
542     // register packet handlers with transport
543     transport->register_packet_handler(&packet_handler);
544 }
545 
546 void hci_close(){
547     // close remote device db
548     if (hci_stack.remote_device_db) {
549         hci_stack.remote_device_db->close();
550     }
551 }
552 
553 // State-Module-Driver overview
554 // state                    module  low-level
555 // HCI_STATE_OFF             off      close
556 // HCI_STATE_INITIALIZING,   on       open
557 // HCI_STATE_WORKING,        on       open
558 // HCI_STATE_HALTING,        on       open
559 // HCI_STATE_SLEEPING,    off/sleep   close
560 // HCI_STATE_FALLING_ASLEEP  on       open
561 
562 static int hci_power_control_on(){
563 
564     // power on
565     int err = 0;
566     if (hci_stack.control && hci_stack.control->on){
567         err = (*hci_stack.control->on)(hci_stack.config);
568     }
569     if (err){
570         log_err( "POWER_ON failed\n");
571         hci_emit_hci_open_failed();
572         return err;
573     }
574 
575     // open low-level device
576     err = hci_stack.hci_transport->open(hci_stack.config);
577     if (err){
578         log_err( "HCI_INIT failed, turning Bluetooth off again\n");
579         if (hci_stack.control && hci_stack.control->off){
580             (*hci_stack.control->off)(hci_stack.config);
581         }
582         hci_emit_hci_open_failed();
583         return err;
584     }
585     return 0;
586 }
587 
588 static void hci_power_control_off(){
589 
590     // close low-level device
591     hci_stack.hci_transport->close(hci_stack.config);
592 
593     // power off
594     if (hci_stack.control && hci_stack.control->off){
595         (*hci_stack.control->off)(hci_stack.config);
596     }
597     hci_stack.state = HCI_STATE_OFF;
598 }
599 
600 static void hci_power_control_sleep(){
601 
602     log_dbg("hci_power_control_sleep");
603 
604 #if 0
605     // don't close serial port during sleep
606 
607     // close low-level device
608     hci_stack.hci_transport->close(hci_stack.config);
609 #endif
610 
611     // sleep mode
612     if (hci_stack.control && hci_stack.control->sleep){
613         (*hci_stack.control->sleep)(hci_stack.config);
614     }
615 
616     hci_stack.state = HCI_STATE_SLEEPING;
617 }
618 
619 static int hci_power_control_wake(){
620 
621     log_dbg("hci_power_control_wake");
622 
623     // wake on
624     if (hci_stack.control && hci_stack.control->wake){
625         (*hci_stack.control->wake)(hci_stack.config);
626     }
627 
628 #if 0
629     // open low-level device
630     int err = hci_stack.hci_transport->open(hci_stack.config);
631     if (err){
632         log_err( "HCI_INIT failed, turning Bluetooth off again\n");
633         if (hci_stack.control && hci_stack.control->off){
634             (*hci_stack.control->off)(hci_stack.config);
635         }
636         hci_emit_hci_open_failed();
637         return err;
638     }
639 #endif
640 
641     return 0;
642 }
643 
644 
645 int hci_power_control(HCI_POWER_MODE power_mode){
646 
647     log_dbg("hci_power_control: %u\n", power_mode);
648 
649     int err = 0;
650     switch (hci_stack.state){
651 
652         case HCI_STATE_OFF:
653             switch (power_mode){
654                 case HCI_POWER_ON:
655                     err = hci_power_control_on();
656                     if (err) return err;
657                     // set up state machine
658                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
659                     hci_stack.state = HCI_STATE_INITIALIZING;
660                     hci_stack.substate = 0;
661                     break;
662                 case HCI_POWER_OFF:
663                     // do nothing
664                     break;
665                 case HCI_POWER_SLEEP:
666                     // do nothing (with SLEEP == OFF)
667                     break;
668             }
669             break;
670 
671         case HCI_STATE_INITIALIZING:
672             switch (power_mode){
673                 case HCI_POWER_ON:
674                     // do nothing
675                     break;
676                 case HCI_POWER_OFF:
677                     // no connections yet, just turn it off
678                     hci_power_control_off();
679                     break;
680                 case HCI_POWER_SLEEP:
681                     // no connections yet, just turn it off
682                     hci_power_control_sleep();
683                     break;
684             }
685             break;
686 
687         case HCI_STATE_WORKING:
688             switch (power_mode){
689                 case HCI_POWER_ON:
690                     // do nothing
691                     break;
692                 case HCI_POWER_OFF:
693                     // see hci_run
694                     hci_stack.state = HCI_STATE_HALTING;
695                     break;
696                 case HCI_POWER_SLEEP:
697                     // see hci_run
698                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
699                     break;
700             }
701             break;
702 
703         case HCI_STATE_HALTING:
704             switch (power_mode){
705                 case HCI_POWER_ON:
706                     // set up state machine
707                     hci_stack.state = HCI_STATE_INITIALIZING;
708                     hci_stack.substate = 0;
709                     break;
710                 case HCI_POWER_OFF:
711                     // do nothing
712                     break;
713                 case HCI_POWER_SLEEP:
714                     // see hci_run
715                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
716                     break;
717             }
718             break;
719 
720         case HCI_STATE_FALLING_ASLEEP:
721             switch (power_mode){
722                 case HCI_POWER_ON:
723                     // set up state machine
724                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
725                     hci_stack.state = HCI_STATE_INITIALIZING;
726                     hci_stack.substate = 0;
727                     break;
728                 case HCI_POWER_OFF:
729                     // see hci_run
730                     hci_stack.state = HCI_STATE_HALTING;
731                     break;
732                 case HCI_POWER_SLEEP:
733                     // do nothing
734                     break;
735             }
736             break;
737 
738         case HCI_STATE_SLEEPING:
739             switch (power_mode){
740                 case HCI_POWER_ON:
741                     err = hci_power_control_wake();
742                     if (err) return err;
743                     // set up state machine
744                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
745                     hci_stack.state = HCI_STATE_INITIALIZING;
746                     hci_stack.substate = 0;
747                     break;
748                 case HCI_POWER_OFF:
749                     hci_stack.state = HCI_STATE_OFF;
750                     break;
751                 case HCI_POWER_SLEEP:
752                     // do nothing
753                     break;
754             }
755             break;
756     }
757 
758     // create internal event
759 	hci_emit_state();
760 
761 	// trigger next/first action
762 	hci_run();
763 
764     return 0;
765 }
766 
767 void hci_discoverable_control(uint8_t enable){
768     if (enable) enable = 1; // normalize argument
769 
770     if (hci_stack.discoverable == enable){
771         hci_emit_discoverable_enabled(hci_stack.discoverable);
772         return;
773     }
774 
775     hci_send_cmd(&hci_write_scan_enable, 2 | enable); // 1 = inq scan, 2 = page scan
776     hci_stack.discoverable = enable;
777 }
778 
779 void hci_run(){
780 
781     if (hci_stack.num_cmd_packets == 0) {
782         // cannot send command yet
783         return;
784     }
785 
786     hci_connection_t * connection;
787 
788     switch (hci_stack.state){
789         case HCI_STATE_INITIALIZING:
790             if (hci_stack.substate % 2) {
791                 // odd: waiting for command completion
792                 return;
793             }
794             switch (hci_stack.substate >> 1){
795                 case 0:
796                     hci_send_cmd(&hci_reset);
797                     break;
798                 case 1:
799                     // custom initialization
800                     if (hci_stack.control && hci_stack.control->next_command){
801                         uint8_t * cmd = (*hci_stack.control->next_command)(hci_stack.config);
802                         if (cmd) {
803                             int size = 3 + cmd[2];
804                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, cmd, size);
805                             hci_stack.substate = 0; // more init commands
806                             break;
807                         }
808                     }
809                     // otherwise continue
810 					hci_send_cmd(&hci_read_bd_addr);
811 					break;
812 				case 2:
813 					hci_send_cmd(&hci_read_buffer_size);
814 					break;
815                 case 3:
816                     // ca. 15 sec
817                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
818                     break;
819 				case 4:
820 					hci_send_cmd(&hci_write_scan_enable, 3); // 3 inq scan + page scan
821 					break;
822                 case 5:
823 #ifndef EMBEDDED
824                 {
825                     char hostname[30];
826                     gethostname(hostname, 30);
827                     hostname[29] = '\0';
828                     hci_send_cmd(&hci_write_local_name, hostname);
829                     break;
830                 }
831                 case 6:
832 #endif
833                     // done.
834                     hci_stack.state = HCI_STATE_WORKING;
835                     hci_emit_state();
836                     break;
837                 default:
838                     break;
839             }
840             hci_stack.substate++;
841             break;
842 
843         case HCI_STATE_HALTING:
844 
845             log_dbg("HCI_STATE_HALTING\n");
846             // close all open connections
847             connection =  (hci_connection_t *) hci_stack.connections;
848             if (connection){
849                 log_dbg("HCI_STATE_HALTING, connection %u, handle %u\n", (int) connection, connection->con_handle);
850                 // send disconnect
851                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
852 
853                 // send disconnected event right away - causes higher layer connections to get closed, too.
854                 hci_shutdown_connection(connection);
855 
856                 // remove from table
857                 hci_stack.connections = connection->item.next;
858                 return;
859             }
860             log_dbg("HCI_STATE_HALTING, calling off\n");
861 
862             // switch mode
863             hci_power_control_off();
864             hci_emit_state();
865             log_dbg("HCI_STATE_HALTING, done\n");
866             break;
867 
868         case HCI_STATE_FALLING_ASLEEP:
869             // close all open connections
870             connection =  (hci_connection_t *) hci_stack.connections;
871             if (connection){
872                 // send disconnect
873                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
874 
875                 // send disconnected event right away - causes higher layer connections to get closed, too.
876                 hci_shutdown_connection(connection);
877 
878                 // remove from table
879                 hci_stack.connections = connection->item.next;
880                 return;
881             }
882 
883             // switch mode
884             hci_power_control_sleep();
885             hci_emit_state();
886             break;
887 
888         default:
889             break;
890     }
891 }
892 
893 int hci_send_cmd_packet(uint8_t *packet, int size){
894     bd_addr_t addr;
895     hci_connection_t * conn;
896     // house-keeping
897 
898     // create_connection?
899     if (IS_COMMAND(packet, hci_create_connection)){
900         bt_flip_addr(addr, &packet[3]);
901         log_dbg("Create_connection to "); print_bd_addr(addr); log_dbg("\n");
902         conn = connection_for_address(addr);
903         if (conn) {
904             // if connection exists
905             if (conn->state == OPEN) {
906                 // if OPEN, emit connection complete command
907                 hci_emit_connection_complete(conn);
908             }
909             //    otherwise, just ignore
910             return 0; // don't sent packet to controller
911 
912         } else{
913             conn = create_connection_for_addr(addr);
914             if (conn){
915                 //    create connection struct and register, state = SENT_CREATE_CONNECTION
916                 conn->state = SENT_CREATE_CONNECTION;
917             }
918         }
919     }
920 
921     if (IS_COMMAND(packet, hci_link_key_request_reply)){
922         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
923     }
924     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
925         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
926     }
927     if (IS_COMMAND(packet, hci_pin_code_request_reply)){
928         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY);
929     }
930     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){
931         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY);
932     }
933 
934     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
935         if (hci_stack.remote_device_db){
936             bt_flip_addr(addr, &packet[3]);
937             hci_stack.remote_device_db->delete_link_key(&addr);
938         }
939     }
940 
941     hci_stack.num_cmd_packets--;
942     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
943 }
944 
945 /**
946  * pre: numcmds >= 0 - it's allowed to send a command to the controller
947  */
948 int hci_send_cmd(const hci_cmd_t *cmd, ...){
949     va_list argptr;
950     va_start(argptr, cmd);
951     uint8_t * hci_cmd_buffer = hci_stack.hci_cmd_buffer;
952     uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr);
953     va_end(argptr);
954     return hci_send_cmd_packet(hci_cmd_buffer, size);
955 }
956 
957 // Create various non-HCI events.
958 // TODO: generalize, use table similar to hci_create_command
959 
960 void hci_emit_state(){
961     uint8_t len = 3;
962     uint8_t event[len];
963     event[0] = BTSTACK_EVENT_STATE;
964     event[1] = len - 3;
965     event[2] = hci_stack.state;
966     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
967     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
968 }
969 
970 void hci_emit_connection_complete(hci_connection_t *conn){
971     uint8_t len = 13;
972     uint8_t event[len];
973     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
974     event[1] = len - 3;
975     event[2] = 0; // status = OK
976     bt_store_16(event, 3, conn->con_handle);
977     bt_flip_addr(&event[5], conn->address);
978     event[11] = 1; // ACL connection
979     event[12] = 0; // encryption disabled
980     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
981     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
982 }
983 
984 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
985     uint8_t len = 4;
986     uint8_t event[len];
987     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
988     event[1] = len - 2;
989     bt_store_16(event, 2, conn->con_handle);
990     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
991     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
992 }
993 
994 void hci_emit_nr_connections_changed(){
995     uint8_t len = 3;
996     uint8_t event[len];
997     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
998     event[1] = len - 2;
999     event[2] = nr_hci_connections();
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_hci_open_failed(){
1005     uint8_t len = 2;
1006     uint8_t event[len];
1007     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1008     event[1] = len - 2;
1009     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
1010     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
1011 }
1012 
1013 
1014 void hci_emit_btstack_version() {
1015     uint8_t len = 6;
1016     uint8_t event[len];
1017     event[0] = BTSTACK_EVENT_VERSION;
1018     event[1] = len - 2;
1019     event[len++] = BTSTACK_MAJOR;
1020     event[len++] = BTSTACK_MINOR;
1021     bt_store_16(event, len, BTSTACK_REVISION);
1022     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
1023     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
1024 }
1025 
1026 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1027     uint8_t len = 3;
1028     uint8_t event[len];
1029     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1030     event[1] = len - 2;
1031     event[2] = enabled;
1032     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
1033     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
1034 }
1035 
1036 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1037     uint16_t len = 2+1+6+248;
1038     uint8_t event[len];
1039     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1040     event[1] = len - 2;
1041     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1042     bt_flip_addr(&event[3], *addr);
1043     memcpy(&event[9], name, 248);
1044     hci_dump_packet(HCI_EVENT_PACKET, 0, event, len);
1045     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
1046 }
1047 
1048 void hci_emit_discoverable_enabled(uint8_t enabled){
1049     uint8_t len = 3;
1050     uint8_t event[len];
1051     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1052     event[1] = len - 2;
1053     event[2] = enabled;
1054     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
1055     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
1056 }
1057