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