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