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