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