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