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