xref: /btstack/src/hci.c (revision c785ef68cf2f75708d1b63e77b925cf02aef517e)
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 /** Register HCI packet handlers */
579 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
580     hci_stack.packet_handler = handler;
581 }
582 
583 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t * remote_device_db){
584 
585     // reference to use transport layer implementation
586     hci_stack.hci_transport = transport;
587 
588     // references to used control implementation
589     hci_stack.control = control;
590 
591     // reference to used config
592     hci_stack.config = config;
593 
594     // no connections yet
595     hci_stack.connections = NULL;
596     hci_stack.discoverable = 0;
597 
598     // higher level handler
599     hci_stack.packet_handler = dummy_handler;
600 
601     // store and open remote device db
602     hci_stack.remote_device_db = remote_device_db;
603     if (hci_stack.remote_device_db) {
604         hci_stack.remote_device_db->open();
605     }
606 
607     // register packet handlers with transport
608     transport->register_packet_handler(&packet_handler);
609 }
610 
611 void hci_close(){
612     // close remote device db
613     if (hci_stack.remote_device_db) {
614         hci_stack.remote_device_db->close();
615     }
616 }
617 
618 // State-Module-Driver overview
619 // state                    module  low-level
620 // HCI_STATE_OFF             off      close
621 // HCI_STATE_INITIALIZING,   on       open
622 // HCI_STATE_WORKING,        on       open
623 // HCI_STATE_HALTING,        on       open
624 // HCI_STATE_SLEEPING,    off/sleep   close
625 // HCI_STATE_FALLING_ASLEEP  on       open
626 
627 static int hci_power_control_on(void){
628 
629     // power on
630     int err = 0;
631     if (hci_stack.control && hci_stack.control->on){
632         err = (*hci_stack.control->on)(hci_stack.config);
633     }
634     if (err){
635         log_error( "POWER_ON failed\n");
636         hci_emit_hci_open_failed();
637         return err;
638     }
639 
640     // open low-level device
641     err = hci_stack.hci_transport->open(hci_stack.config);
642     if (err){
643         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
644         if (hci_stack.control && hci_stack.control->off){
645             (*hci_stack.control->off)(hci_stack.config);
646         }
647         hci_emit_hci_open_failed();
648         return err;
649     }
650     return 0;
651 }
652 
653 static void hci_power_control_off(void){
654 
655     log_info("hci_power_control_off\n");
656 
657     // close low-level device
658     hci_stack.hci_transport->close(hci_stack.config);
659 
660     log_info("hci_power_control_off - hci_transport closed\n");
661 
662     // power off
663     if (hci_stack.control && hci_stack.control->off){
664         (*hci_stack.control->off)(hci_stack.config);
665     }
666 
667     log_info("hci_power_control_off - control closed\n");
668 
669     hci_stack.state = HCI_STATE_OFF;
670 }
671 
672 static void hci_power_control_sleep(void){
673 
674     log_info("hci_power_control_sleep\n");
675 
676 #if 0
677     // don't close serial port during sleep
678 
679     // close low-level device
680     hci_stack.hci_transport->close(hci_stack.config);
681 #endif
682 
683     // sleep mode
684     if (hci_stack.control && hci_stack.control->sleep){
685         (*hci_stack.control->sleep)(hci_stack.config);
686     }
687 
688     hci_stack.state = HCI_STATE_SLEEPING;
689 }
690 
691 static int hci_power_control_wake(void){
692 
693     log_info("hci_power_control_wake\n");
694 
695     // wake on
696     if (hci_stack.control && hci_stack.control->wake){
697         (*hci_stack.control->wake)(hci_stack.config);
698     }
699 
700 #if 0
701     // open low-level device
702     int err = hci_stack.hci_transport->open(hci_stack.config);
703     if (err){
704         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
705         if (hci_stack.control && hci_stack.control->off){
706             (*hci_stack.control->off)(hci_stack.config);
707         }
708         hci_emit_hci_open_failed();
709         return err;
710     }
711 #endif
712 
713     return 0;
714 }
715 
716 
717 int hci_power_control(HCI_POWER_MODE power_mode){
718 
719     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state);
720 
721     int err = 0;
722     switch (hci_stack.state){
723 
724         case HCI_STATE_OFF:
725             switch (power_mode){
726                 case HCI_POWER_ON:
727                     err = hci_power_control_on();
728                     if (err) return err;
729                     // set up state machine
730                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
731                     hci_stack.state = HCI_STATE_INITIALIZING;
732                     hci_stack.substate = 0;
733                     break;
734                 case HCI_POWER_OFF:
735                     // do nothing
736                     break;
737                 case HCI_POWER_SLEEP:
738                     // do nothing (with SLEEP == OFF)
739                     break;
740             }
741             break;
742 
743         case HCI_STATE_INITIALIZING:
744             switch (power_mode){
745                 case HCI_POWER_ON:
746                     // do nothing
747                     break;
748                 case HCI_POWER_OFF:
749                     // no connections yet, just turn it off
750                     hci_power_control_off();
751                     break;
752                 case HCI_POWER_SLEEP:
753                     // no connections yet, just turn it off
754                     hci_power_control_sleep();
755                     break;
756             }
757             break;
758 
759         case HCI_STATE_WORKING:
760             switch (power_mode){
761                 case HCI_POWER_ON:
762                     // do nothing
763                     break;
764                 case HCI_POWER_OFF:
765                     // see hci_run
766                     hci_stack.state = HCI_STATE_HALTING;
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_HALTING:
777             switch (power_mode){
778                 case HCI_POWER_ON:
779                     // set up state machine
780                     hci_stack.state = HCI_STATE_INITIALIZING;
781                     hci_stack.substate = 0;
782                     break;
783                 case HCI_POWER_OFF:
784                     // do nothing
785                     break;
786                 case HCI_POWER_SLEEP:
787                     // see hci_run
788                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
789                     hci_stack.substate = 0;
790                     break;
791             }
792             break;
793 
794         case HCI_STATE_FALLING_ASLEEP:
795             switch (power_mode){
796                 case HCI_POWER_ON:
797                     // set up state machine
798                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
799                     hci_stack.state = HCI_STATE_INITIALIZING;
800                     hci_stack.substate = 0;
801                     break;
802                 case HCI_POWER_OFF:
803                     // see hci_run
804                     hci_stack.state = HCI_STATE_HALTING;
805                     break;
806                 case HCI_POWER_SLEEP:
807                     // do nothing
808                     break;
809             }
810             break;
811 
812         case HCI_STATE_SLEEPING:
813             switch (power_mode){
814                 case HCI_POWER_ON:
815                     err = hci_power_control_wake();
816                     if (err) return err;
817                     // set up state machine
818                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
819                     hci_stack.state = HCI_STATE_INITIALIZING;
820                     hci_stack.substate = 0;
821                     break;
822                 case HCI_POWER_OFF:
823                     hci_stack.state = HCI_STATE_HALTING;
824                     break;
825                 case HCI_POWER_SLEEP:
826                     // do nothing
827                     break;
828             }
829             break;
830     }
831 
832     // create internal event
833 	hci_emit_state();
834 
835 	// trigger next/first action
836 	hci_run();
837 
838     return 0;
839 }
840 
841 void hci_discoverable_control(uint8_t enable){
842     if (enable) enable = 1; // normalize argument
843 
844     if (hci_stack.discoverable == enable){
845         hci_emit_discoverable_enabled(hci_stack.discoverable);
846         return;
847     }
848 
849     hci_send_cmd(&hci_write_scan_enable, 2 | enable); // 1 = inq scan, 2 = page scan
850     hci_stack.discoverable = enable;
851 }
852 
853 void hci_run(){
854 
855     hci_connection_t * connection;
856     linked_item_t * it;
857 
858     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
859 
860     // global/non-connection oriented commands - decline incoming connections
861     if (hci_stack.decline_reason){
862         uint8_t reason = hci_stack.decline_reason;
863         hci_stack.decline_reason = 0;
864         hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason);
865     }
866 
867     // send pending HCI commands
868     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
869 
870         connection = (hci_connection_t *) it;
871 
872         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) {
873             // log_info("hci_run: cannot send command packet\n");
874             return;
875         }
876 
877         if (connection->state == RECEIVED_CONNECTION_REQUEST){
878             log_info("sending hci_accept_connection_request\n");
879             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
880             connection->state = ACCEPTED_CONNECTION_REQUEST;
881         }
882 
883         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
884 
885         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
886             link_key_t link_key;
887             log_info("responding to link key request\n");
888             if ( hci_stack.remote_device_db->get_link_key( &connection->address, &link_key)){
889                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
890             } else {
891                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
892             }
893             connection->authentication_flags &= ~HANDLE_LINK_KEY_REQUEST;
894         }
895     }
896 
897     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
898 
899     switch (hci_stack.state){
900         case HCI_STATE_INITIALIZING:
901             // log_info("hci_init: substate %u\n", hci_stack.substate);
902             if (hci_stack.substate % 2) {
903                 // odd: waiting for command completion
904                 return;
905             }
906             switch (hci_stack.substate >> 1){
907                 case 0: // RESET
908                     hci_send_cmd(&hci_reset);
909                     if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){
910                         // skip baud change
911                         hci_stack.substate = 4; // >> 1 = 2
912                     }
913                     break;
914                 case 1: // SEND BAUD CHANGE
915                     hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_cmd_buffer);
916                     hci_send_cmd_packet(hci_stack.hci_cmd_buffer, 3 + hci_stack.hci_cmd_buffer[2]);
917                     break;
918                 case 2: // LOCAL BAUD CHANGE
919                     hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main);
920                     hci_stack.substate += 2;
921                     // break missing here for fall through
922 
923                 case 3:
924                     // custom initialization
925                     if (hci_stack.control && hci_stack.control->next_command){
926                         uint8_t * cmd = (*hci_stack.control->next_command)(hci_stack.config);
927                         if (cmd) {
928                             int size = 3 + cmd[2];
929                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, cmd, size);
930                             hci_stack.substate = 4; // more init commands
931                             break;
932                         }
933                         printf("hci_run: init script done\n\r");
934                     }
935                     // otherwise continue
936 					hci_send_cmd(&hci_read_bd_addr);
937 					break;
938 				case 4:
939 					hci_send_cmd(&hci_read_buffer_size);
940 					break;
941                 case 5:
942                     // ca. 15 sec
943                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
944                     break;
945 				case 6:
946 					hci_send_cmd(&hci_write_scan_enable, 2 | hci_stack.discoverable); // page scan
947 					break;
948                 case 7:
949 #ifndef EMBEDDED
950                 {
951                     char hostname[30];
952                     gethostname(hostname, 30);
953                     hostname[29] = '\0';
954                     hci_send_cmd(&hci_write_local_name, hostname);
955                     break;
956                 }
957                 case 8:
958 #ifdef USE_BLUETOOL
959                     hci_send_cmd(&hci_write_class_of_device, 0x007a020c); // Smartphone
960                     break;
961 
962                 case 9:
963 #endif
964 #endif
965                     // done.
966                     hci_stack.state = HCI_STATE_WORKING;
967                     hci_emit_state();
968                     break;
969                 default:
970                     break;
971             }
972             hci_stack.substate++;
973             break;
974 
975         case HCI_STATE_HALTING:
976 
977             log_info("HCI_STATE_HALTING\n");
978             // close all open connections
979             connection =  (hci_connection_t *) hci_stack.connections;
980             if (connection){
981 
982                 // send disconnect
983                 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
984 
985                 log_info("HCI_STATE_HALTING, connection %lu, handle %u\n", (uintptr_t) connection, (uint16_t)connection->con_handle);
986                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
987 
988                 // send disconnected event right away - causes higher layer connections to get closed, too.
989                 hci_shutdown_connection(connection);
990                 return;
991             }
992             log_info("HCI_STATE_HALTING, calling off\n");
993 
994             // switch mode
995             hci_power_control_off();
996 
997             log_info("HCI_STATE_HALTING, emitting state\n");
998             hci_emit_state();
999             log_info("HCI_STATE_HALTING, done\n");
1000             break;
1001 
1002         case HCI_STATE_FALLING_ASLEEP:
1003             switch(hci_stack.substate) {
1004                 case 0:
1005                     log_info("HCI_STATE_FALLING_ASLEEP\n");
1006                     // close all open connections
1007                     connection =  (hci_connection_t *) hci_stack.connections;
1008                     if (connection){
1009 
1010                         // send disconnect
1011                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1012 
1013                         log_info("HCI_STATE_FALLING_ASLEEP, connection %lu, handle %u\n", (uintptr_t) connection, (uint16_t)connection->con_handle);
1014                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1015 
1016                         // send disconnected event right away - causes higher layer connections to get closed, too.
1017                         hci_shutdown_connection(connection);
1018                         return;
1019                     }
1020 
1021                     // disable page and inquiry scan
1022                     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1023 
1024                     log_info("HCI_STATE_HALTING, disabling inq & page scans\n");
1025                     hci_send_cmd(&hci_write_scan_enable, 0); // none
1026 
1027                     // continue in next sub state
1028                     hci_stack.substate++;
1029                     break;
1030                 case 1:
1031                     // wait for command complete "hci_write_scan_enable" in event_handler();
1032                     break;
1033                 case 2:
1034                     log_info("HCI_STATE_HALTING, calling sleep\n");
1035                     // switch mode
1036                     hci_power_control_sleep();  // changes hci_stack.state to SLEEP
1037                     hci_emit_state();
1038                 default:
1039                     break;
1040             }
1041             break;
1042 
1043         default:
1044             break;
1045     }
1046 }
1047 
1048 int hci_send_cmd_packet(uint8_t *packet, int size){
1049     bd_addr_t addr;
1050     hci_connection_t * conn;
1051     // house-keeping
1052 
1053     // create_connection?
1054     if (IS_COMMAND(packet, hci_create_connection)){
1055         bt_flip_addr(addr, &packet[3]);
1056         log_info("Create_connection to "); print_bd_addr(addr); log_info("\n");
1057         conn = connection_for_address(addr);
1058         if (conn) {
1059             // if connection exists
1060             if (conn->state == OPEN) {
1061                 // and OPEN, emit connection complete command
1062                 hci_emit_connection_complete(conn, 0);
1063             }
1064             //    otherwise, just ignore as it is already in the open process
1065             return 0; // don't sent packet to controller
1066 
1067         }
1068         // create connection struct and register, state = SENT_CREATE_CONNECTION
1069         conn = create_connection_for_addr(addr);
1070         if (!conn){
1071             // notify client that alloc failed
1072             hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
1073             return 0; // don't sent packet to controller
1074         }
1075         conn->state = SENT_CREATE_CONNECTION;
1076     }
1077 
1078     if (IS_COMMAND(packet, hci_link_key_request_reply)){
1079         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
1080     }
1081     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
1082         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
1083     }
1084     if (IS_COMMAND(packet, hci_pin_code_request_reply)){
1085         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY);
1086     }
1087     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){
1088         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY);
1089     }
1090 
1091     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
1092         if (hci_stack.remote_device_db){
1093             bt_flip_addr(addr, &packet[3]);
1094             hci_stack.remote_device_db->delete_link_key(&addr);
1095         }
1096     }
1097 
1098     hci_stack.num_cmd_packets--;
1099     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
1100 }
1101 
1102 /**
1103  * pre: numcmds >= 0 - it's allowed to send a command to the controller
1104  */
1105 int hci_send_cmd(const hci_cmd_t *cmd, ...){
1106     va_list argptr;
1107     va_start(argptr, cmd);
1108     uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr);
1109     va_end(argptr);
1110     return hci_send_cmd_packet(hci_stack.hci_cmd_buffer, size);
1111 }
1112 
1113 // Create various non-HCI events.
1114 // TODO: generalize, use table similar to hci_create_command
1115 
1116 void hci_emit_state(){
1117     uint8_t event[3];
1118     event[0] = BTSTACK_EVENT_STATE;
1119     event[1] = sizeof(event) - 2;
1120     event[2] = hci_stack.state;
1121     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1122     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1123 }
1124 
1125 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1126     uint8_t event[13];
1127     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1128     event[1] = sizeof(event) - 2;
1129     event[2] = status;
1130     bt_store_16(event, 3, conn->con_handle);
1131     bt_flip_addr(&event[5], conn->address);
1132     event[11] = 1; // ACL connection
1133     event[12] = 0; // encryption disabled
1134     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1135     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1136 }
1137 
1138 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1139     uint8_t event[6];
1140     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1141     event[1] = sizeof(event) - 2;
1142     event[2] = 0; // status = OK
1143     bt_store_16(event, 3, handle);
1144     event[5] = reason;
1145     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1146     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1147 }
1148 
1149 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1150     uint8_t event[4];
1151     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1152     event[1] = sizeof(event) - 2;
1153     bt_store_16(event, 2, conn->con_handle);
1154     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1155     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1156 }
1157 
1158 void hci_emit_nr_connections_changed(){
1159     uint8_t event[3];
1160     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1161     event[1] = sizeof(event) - 2;
1162     event[2] = nr_hci_connections();
1163     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1164     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1165 }
1166 
1167 void hci_emit_hci_open_failed(){
1168     uint8_t event[2];
1169     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1170     event[1] = sizeof(event) - 2;
1171     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1172     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1173 }
1174 
1175 
1176 void hci_emit_btstack_version() {
1177     uint8_t event[6];
1178     event[0] = BTSTACK_EVENT_VERSION;
1179     event[1] = sizeof(event) - 2;
1180     event[2] = BTSTACK_MAJOR;
1181     event[3] = BTSTACK_MINOR;
1182     bt_store_16(event, 4, BTSTACK_REVISION);
1183     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1184     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1185 }
1186 
1187 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1188     uint8_t event[3];
1189     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1190     event[1] = sizeof(event) - 2;
1191     event[2] = enabled;
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 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1197     uint8_t event[2+1+6+248];
1198     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1199     event[1] = sizeof(event) - 2;
1200     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
1201     bt_flip_addr(&event[3], *addr);
1202     memcpy(&event[9], name, 248);
1203     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
1204     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1205 }
1206 
1207 void hci_emit_discoverable_enabled(uint8_t enabled){
1208     uint8_t event[3];
1209     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1210     event[1] = sizeof(event) - 2;
1211     event[2] = enabled;
1212     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1213     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1214 }
1215