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