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