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