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