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