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