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