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