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