xref: /btstack/src/hci.c (revision e2edc0c3988319f94f2d3706299f4e9ebe388b1d)
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 <unistd.h>
42 #include <stdarg.h>
43 #include <string.h>
44 #include <stdio.h>
45 
46 #include "debug.h"
47 #include "hci_dump.h"
48 
49 #include "../include/btstack/hci_cmds.h"
50 #include "../include/btstack/version.h"
51 
52 // temp
53 #include "l2cap.h"
54 
55 #define HCI_CONNECTION_TIMEOUT_MS 10000
56 
57 // the STACK is here
58 static hci_stack_t       hci_stack;
59 
60 /**
61  * get connection for a given handle
62  *
63  * @return connection OR NULL, if not found
64  */
65 hci_connection_t * connection_for_handle(hci_con_handle_t con_handle){
66     linked_item_t *it;
67     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
68         if ( ((hci_connection_t *) it)->con_handle == con_handle){
69             return (hci_connection_t *) it;
70         }
71     }
72     return NULL;
73 }
74 
75 static void hci_connection_timeout_handler(timer_source_t *timer){
76     hci_connection_t * connection = linked_item_get_user(&timer->item);
77     struct timeval tv;
78     gettimeofday(&tv, NULL);
79     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
80         // connections might be timed out
81         hci_emit_l2cap_check_timeout(connection);
82         run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
83     } else {
84         // next timeout check at
85         timer->timeout.tv_sec = connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000;
86     }
87     run_loop_add_timer(timer);
88 }
89 
90 static void hci_connection_timestamp(hci_connection_t *connection){
91     gettimeofday(&connection->timestamp, NULL);
92 }
93 
94 /**
95  * create connection for given address
96  *
97  * @return connection OR NULL, if not found
98  */
99 static hci_connection_t * create_connection_for_addr(bd_addr_t addr){
100     hci_connection_t * conn = malloc( sizeof(hci_connection_t) );
101     if (!conn) return NULL;
102     BD_ADDR_COPY(conn->address, addr);
103     conn->con_handle = 0xffff;
104     conn->flags = 0;
105     linked_item_set_user(&conn->timeout.item, conn);
106     conn->timeout.process = hci_connection_timeout_handler;
107     hci_connection_timestamp(conn);
108     conn->acl_recombination_length = 0;
109     conn->acl_recombination_pos = 0;
110     linked_list_add(&hci_stack.connections, (linked_item_t *) conn);
111     return conn;
112 }
113 
114 /**
115  * get connection for given address
116  *
117  * @return connection OR NULL, if not found
118  */
119 static hci_connection_t * connection_for_address(bd_addr_t address){
120     linked_item_t *it;
121     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
122         if ( ! BD_ADDR_CMP( ((hci_connection_t *) it)->address, address) ){
123             return (hci_connection_t *) it;
124         }
125     }
126     return NULL;
127 }
128 
129 /**
130  * count connections
131  */
132 static int nr_hci_connections(){
133     int count = 0;
134     linked_item_t *it;
135     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next, count++);
136     return count;
137 }
138 
139 /**
140  * Dummy handler called by HCI
141  */
142 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
143 }
144 
145 /**
146  * Dummy control handler
147  */
148 static int null_control_function(void *config){
149     return 0;
150 }
151 static const char * null_control_name(void *config){
152     return "Hardware unknown";
153 }
154 static bt_control_t null_control = {
155     null_control_function,
156     null_control_function,
157     null_control_function,
158     null_control_name
159 };
160 
161 
162 int hci_send_acl_packet(uint8_t *packet, int size){
163 
164     // update idle timestamp
165     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
166     hci_connection_t *connection = connection_for_handle( con_handle);
167     if (connection) hci_connection_timestamp(connection);
168 
169     // send packet
170     return hci_stack.hci_transport->send_acl_packet(packet, size);
171 }
172 
173 static void acl_handler(uint8_t *packet, int size){
174 
175     // get info
176     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
177     hci_connection_t *conn      = connection_for_handle(con_handle);
178     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
179     uint16_t acl_length         = READ_ACL_LENGTH(packet);
180 
181     // ignore non-registered handle
182     if (!conn){
183         log_err( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle);
184         return;
185     }
186 
187     // update idle timestamp
188     hci_connection_timestamp(conn);
189 
190     // handle different packet types
191     switch (acl_flags & 0x03) {
192 
193         case 0x01: // continuation fragment
194 
195             // sanity check
196             if (conn->acl_recombination_pos == 0) {
197                 log_err( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle);
198                 return;
199             }
200 
201             // append fragment payload (header already stored)
202             memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length );
203             conn->acl_recombination_pos += acl_length;
204 
205             // log_err( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n",
206             //        acl_length, connection->acl_recombination_pos, connection->acl_recombination_length);
207 
208             // forward complete L2CAP packet if complete.
209             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
210 
211                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos);
212                 // reset recombination buffer
213                 conn->acl_recombination_length = 0;
214                 conn->acl_recombination_pos = 0;
215             }
216             break;
217 
218         case 0x02: { // first fragment
219 
220             // sanity check
221             if (conn->acl_recombination_pos) {
222                 log_err( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle);
223                 return;
224             }
225 
226             // peek into L2CAP packet!
227             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
228 
229             // compare fragment size to L2CAP packet size
230             if (acl_length >= l2cap_length + 4){
231 
232                 // forward fragment as L2CAP packet
233                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
234 
235             } else {
236                 // store first fragment and tweak acl length for complete package
237                 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4);
238                 conn->acl_recombination_pos    = acl_length + 4;
239                 conn->acl_recombination_length = l2cap_length;
240                 bt_store_16(conn->acl_recombination_buffer, 2, acl_length +4);
241                 // log_err( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length);
242             }
243             break;
244 
245         }
246         default:
247             log_err( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03);
248             return;
249     }
250 
251     // execute main loop
252     hci_run();
253 }
254 
255 static void event_handler(uint8_t *packet, int size){
256     bd_addr_t addr;
257     hci_con_handle_t handle;
258     hci_connection_t * conn;
259 
260     // get num_cmd_packets
261     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){
262         // Get Num_HCI_Command_Packets
263         hci_stack.num_cmd_packets = packet[2];
264     }
265 
266     switch (packet[0]) {
267 
268         case HCI_EVENT_COMMAND_COMPLETE:
269             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
270                 // from offset 5
271                 // status
272                 hci_stack.acl_data_packet_length = READ_BT_16(packet, 6);
273                 // SCO data packet len (8)
274                 hci_stack.total_num_acl_packets  = packet[9];
275                 // total num SCO packets
276                 log_dbg("hci_read_buffer_size: size %u, count %u\n", hci_stack.acl_data_packet_length, hci_stack.total_num_acl_packets);
277             }
278             break;
279 
280         case HCI_EVENT_CONNECTION_REQUEST:
281             bt_flip_addr(addr, &packet[2]);
282             // TODO: eval COD 8-10
283             uint8_t link_type = packet[11];
284             log_dbg("Connection_incoming: "); print_bd_addr(addr); log_dbg(", type %u\n", link_type);
285             if (link_type == 1) { // ACL
286                 conn = connection_for_address(addr);
287                 if (!conn) {
288                     conn = create_connection_for_addr(addr);
289                 }
290                 // TODO: check for malloc failure
291                 conn->state = ACCEPTED_CONNECTION_REQUEST;
292                 hci_send_cmd(&hci_accept_connection_request, addr, 1);
293             } else {
294                 // TODO: decline request
295             }
296             break;
297 
298         case HCI_EVENT_CONNECTION_COMPLETE:
299             // Connection management
300             bt_flip_addr(addr, &packet[5]);
301             log_dbg("Connection_complete (status=%u)", packet[2]); print_bd_addr(addr); log_dbg("\n");
302             conn = connection_for_address(addr);
303             if (conn) {
304                 if (!packet[2]){
305                     conn->state = OPEN;
306                     conn->con_handle = READ_BT_16(packet, 3);
307                     conn->flags = 0;
308 
309                     gettimeofday(&conn->timestamp, NULL);
310                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
311                     run_loop_add_timer(&conn->timeout);
312 
313                     log_dbg("New connection: handle %u, ", conn->con_handle);
314                     print_bd_addr( conn->address );
315                     log_dbg("\n");
316 
317                     hci_emit_nr_connections_changed();
318                 } else {
319                     // connection failed, remove entry
320                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
321                     free( conn );
322                 }
323             }
324             break;
325 
326         case HCI_EVENT_DISCONNECTION_COMPLETE:
327             if (!packet[2]){
328                 handle = READ_BT_16(packet, 3);
329                 hci_connection_t * conn = connection_for_handle(handle);
330                 if (conn) {
331                     log_dbg("Connection closed: handle %u, ", conn->con_handle);
332                     print_bd_addr( conn->address );
333                     log_dbg("\n");
334                     run_loop_remove_timer(&conn->timeout);
335                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
336                     free( conn );
337                     hci_emit_nr_connections_changed();
338                 }
339             }
340             break;
341 
342         default:
343             break;
344     }
345 
346     // handle BT initialization
347     if (hci_stack.state == HCI_STATE_INITIALIZING){
348         // handle H4 synchronization loss on restart
349         // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){
350         //    hci_stack.substate = 0;
351         // }
352         // handle normal init sequence
353         if (hci_stack.substate % 2){
354             // odd: waiting for event
355             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
356                 hci_stack.substate++;
357             }
358         }
359     }
360 
361     hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
362 
363 	// execute main loop
364 	hci_run();
365 }
366 
367 void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
368     switch (packet_type) {
369         case HCI_EVENT_PACKET:
370             event_handler(packet, size);
371             break;
372         case HCI_ACL_DATA_PACKET:
373             acl_handler(packet, size);
374             break;
375         default:
376             break;
377     }
378 }
379 
380 /** Register HCI packet handlers */
381 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
382     hci_stack.packet_handler = handler;
383 }
384 
385 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control){
386 
387     // reference to use transport layer implementation
388     hci_stack.hci_transport = transport;
389 
390     // references to used control implementation
391     if (control) {
392         hci_stack.control = control;
393     } else {
394         hci_stack.control = &null_control;
395     }
396 
397     // reference to used config
398     hci_stack.config = config;
399 
400     // no connections yet
401     hci_stack.connections = NULL;
402 
403     // empty cmd buffer
404     hci_stack.hci_cmd_buffer = malloc(3+255);
405 
406     // higher level handler
407     hci_stack.packet_handler = dummy_handler;
408 
409     // register packet handlers with transport
410     transport->register_packet_handler(&packet_handler);
411 }
412 
413 int hci_power_control(HCI_POWER_MODE power_mode){
414     if (power_mode == HCI_POWER_ON && hci_stack.state == HCI_STATE_OFF) {
415 
416         // power on
417         int err = hci_stack.control->on(hci_stack.config);
418         if (err){
419             log_err( "POWER_ON failed\n");
420             hci_emit_hci_open_failed();
421             return err;
422         }
423 
424         // open low-level device
425         err = hci_stack.hci_transport->open(hci_stack.config);
426         if (err){
427             log_err( "HCI_INIT failed, turning Bluetooth off again\n");
428             hci_stack.control->off(hci_stack.config);
429             hci_emit_hci_open_failed();
430             return err;
431         }
432 
433         // set up state machine
434         hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
435         hci_stack.state = HCI_STATE_INITIALIZING;
436         hci_stack.substate = 0;
437 
438     } else if (power_mode == HCI_POWER_OFF && hci_stack.state == HCI_STATE_WORKING){
439 
440         // close low-level device
441         hci_stack.hci_transport->close(hci_stack.config);
442 
443         // power off
444         hci_stack.control->off(hci_stack.config);
445 
446         // we're off now
447         hci_stack.state = HCI_STATE_OFF;
448     }
449 
450     // create internal event
451 	hci_emit_state();
452 
453 	// trigger next/first action
454 	hci_run();
455 
456     return 0;
457 }
458 
459 void hci_run(){
460     switch (hci_stack.state){
461         case HCI_STATE_INITIALIZING:
462             if (hci_stack.substate % 2) {
463                 // odd: waiting for command completion
464                 return;
465             }
466             if (hci_stack.num_cmd_packets == 0) {
467                 // cannot send command yet
468                 return;
469             }
470             switch (hci_stack.substate/2){
471                 case 0:
472                     hci_send_cmd(&hci_reset);
473                     break;
474 				case 1:
475 					hci_send_cmd(&hci_read_bd_addr);
476 					break;
477 				case 2:
478 					hci_send_cmd(&hci_read_buffer_size);
479 					break;
480                 case 3:
481                     // ca. 15 sec
482                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
483                     break;
484 				case 4:
485 					hci_send_cmd(&hci_write_scan_enable, 3); // 3 inq scan + page scan
486 					break;
487                 case 5:
488                     // done.
489                     hci_stack.state = HCI_STATE_WORKING;
490                     hci_emit_state();
491                     break;
492                 default:
493                     break;
494             }
495             hci_stack.substate++;
496             break;
497         default:
498             break;
499     }
500 }
501 
502 int hci_send_cmd_packet(uint8_t *packet, int size){
503     bd_addr_t addr;
504     hci_connection_t * conn;
505     // house-keeping
506 
507     // create_connection?
508     if (IS_COMMAND(packet, hci_create_connection)){
509         bt_flip_addr(addr, &packet[3]);
510         log_dbg("Create_connection to "); print_bd_addr(addr); log_dbg("\n");
511         conn = connection_for_address(addr);
512         if (conn) {
513             // if connection exists
514             if (conn->state == OPEN) {
515                 // if OPEN, emit connection complete command
516                 hci_emit_connection_complete(conn);
517             }
518             //    otherwise, just ignore
519             return 0; // don't sent packet to controller
520 
521         } else{
522             conn = create_connection_for_addr(addr);
523             if (conn){
524                 //    create connection struct and register, state = SENT_CREATE_CONNECTION
525                 conn->state = SENT_CREATE_CONNECTION;
526             }
527         }
528     }
529 
530     // accept connection
531 
532     // reject connection
533 
534     // close_connection?
535       // set state = SENT_DISCONNECT
536 
537     hci_stack.num_cmd_packets--;
538     return hci_stack.hci_transport->send_cmd_packet(packet, size);
539 }
540 
541 /**
542  * pre: numcmds >= 0 - it's allowed to send a command to the controller
543  */
544 int hci_send_cmd(hci_cmd_t *cmd, ...){
545     va_list argptr;
546     va_start(argptr, cmd);
547     uint8_t * hci_cmd_buffer = hci_stack.hci_cmd_buffer;
548     uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr);
549     va_end(argptr);
550     return hci_send_cmd_packet(hci_cmd_buffer, size);
551 }
552 
553 // Create various non-HCI events.
554 // TODO: generalize, use table similar to hci_create_command
555 
556 void hci_emit_state(){
557     uint8_t len = 3;
558     uint8_t event[len];
559     event[0] = BTSTACK_EVENT_STATE;
560     event[1] = len - 3;
561     event[2] = hci_stack.state;
562     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
563     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
564 }
565 
566 void hci_emit_connection_complete(hci_connection_t *conn){
567     uint8_t len = 13;
568     uint8_t event[len];
569     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
570     event[1] = len - 3;
571     event[2] = 0; // status = OK
572     bt_store_16(event, 3, conn->con_handle);
573     bt_flip_addr(&event[5], conn->address);
574     event[11] = 1; // ACL connection
575     event[12] = 0; // encryption disabled
576     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
577     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
578 }
579 
580 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
581     uint8_t len = 4;
582     uint8_t event[len];
583     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
584     event[1] = len - 2;
585     bt_store_16(event, 2, conn->con_handle);
586     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
587     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
588 }
589 
590 void hci_emit_nr_connections_changed(){
591     uint8_t len = 3;
592     uint8_t event[len];
593     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
594     event[1] = len - 2;
595     event[2] = nr_hci_connections();
596     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
597     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
598 }
599 
600 void hci_emit_hci_open_failed(){
601     uint8_t len = 2;
602     uint8_t event[len];
603     event[0] = BTSTACK_EVENT_POWERON_FAILED;
604     event[1] = len - 2;
605     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
606     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
607 }
608 
609 
610 void hci_emit_btstack_version() {
611     uint8_t len = 6;
612     uint8_t event[len];
613     event[0] = BTSTACK_EVENT_VERSION;
614     event[1] = len - 2;
615     event[len++] = BTSTACK_MAJOR;
616     event[len++] = BTSTACK_MINOR;
617     bt_store_16(event, len, BTSTACK_REVISION);
618     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
619     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
620 }
621 
622 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
623     uint8_t len = 3;
624     uint8_t event[len];
625     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
626     event[1] = len - 2;
627     event[2] = enabled;
628     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
629     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
630 }
631