xref: /btstack/src/hci.c (revision 1713bcea3a49b492b9437ccc3270646a8b9d602e)
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 10000
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_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) {
74         // connections might be timed out
75         hci_emit_l2cap_check_timeout(connection);
76         run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT);
77     } else {
78         // next timeout check at
79         timer->timeout.tv_sec = connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT;
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     // Get Num_HCI_Command_Packets
179     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE ||
180         packet[0] == HCI_EVENT_COMMAND_STATUS){
181         hci_stack.num_cmd_packets = packet[2];
182     }
183 
184     // Connection management
185     if (packet[0] == HCI_EVENT_CONNECTION_COMPLETE) {
186         if (!packet[2]){
187             bt_flip_addr(addr, &packet[5]);
188             printf("Connection_complete "); print_bd_addr(addr); printf("\n");
189             hci_connection_t * conn = connection_for_address(addr);
190             if (conn) {
191                 conn->state = OPEN;
192                 conn->con_handle = READ_BT_16(packet, 3);
193                 conn->flags = 0;
194 
195                 gettimeofday(&conn->timestamp, NULL);
196                 run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT);
197                 run_loop_add_timer(&conn->timeout);
198 
199                 printf("New connection: handle %u, ", conn->con_handle);
200                 print_bd_addr( conn->address );
201                 printf("\n");
202 
203                 hci_emit_nr_connections_changed();
204             }
205         }
206     }
207 
208     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE) {
209         if (!packet[2]){
210             handle = READ_BT_16(packet, 3);
211             hci_connection_t * conn = connection_for_handle(handle);
212             if (conn) {
213                 printf("Connection closed: handle %u, ", conn->con_handle);
214                 print_bd_addr( conn->address );
215                 printf("\n");
216                 run_loop_remove_timer(&conn->timeout);
217                 linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
218                 free( conn );
219                 hci_emit_nr_connections_changed();
220             }
221         }
222     }
223 
224     // handle BT initialization
225     if (hci_stack.state == HCI_STATE_INITIALIZING){
226         // handle H4 synchronization loss on restart
227         // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){
228         //    hci_stack.substate = 0;
229         // }
230         // handle normal init sequence
231         if (hci_stack.substate % 2){
232             // odd: waiting for event
233             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
234                 hci_stack.substate++;
235             }
236         }
237     }
238 
239     // link key request
240     if (packet[0] == HCI_EVENT_LINK_KEY_REQUEST){
241         bt_flip_addr(addr, &packet[2]);
242         hci_send_cmd(&hci_link_key_request_negative_reply, &addr);
243         return;
244     }
245 
246     hci_stack.event_packet_handler(packet, size);
247 
248 	// execute main loop
249 	hci_run();
250 }
251 
252 /** Register HCI packet handlers */
253 void hci_register_event_packet_handler(void (*handler)(uint8_t *packet, uint16_t size)){
254     hci_stack.event_packet_handler = handler;
255 }
256 void hci_register_acl_packet_handler  (void (*handler)(uint8_t *packet, uint16_t size)){
257     hci_stack.acl_packet_handler = handler;
258 }
259 
260 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control){
261 
262     // reference to use transport layer implementation
263     hci_stack.hci_transport = transport;
264 
265     // references to used control implementation
266     if (control) {
267         hci_stack.control = control;
268     } else {
269         hci_stack.control = &null_control;
270     }
271 
272     // reference to used config
273     hci_stack.config = config;
274 
275     // no connections yet
276     hci_stack.connections = NULL;
277 
278     // empty cmd buffer
279     hci_stack.hci_cmd_buffer = malloc(3+255);
280 
281     // higher level handler
282     hci_stack.event_packet_handler = dummy_handler;
283     hci_stack.acl_packet_handler = dummy_handler;
284 
285     // register packet handlers with transport
286     transport->register_event_packet_handler( event_handler);
287     transport->register_acl_packet_handler( acl_handler);
288 }
289 
290 int hci_power_control(HCI_POWER_MODE power_mode){
291     if (power_mode == HCI_POWER_ON && hci_stack.state == HCI_STATE_OFF) {
292 
293         // power on
294         int err = hci_stack.control->on(hci_stack.config);
295         if (err){
296             fprintf(stderr, "POWER_ON failed\n");
297             hci_emit_hci_open_failed();
298             return err;
299         }
300 
301         // open low-level device
302         err = hci_stack.hci_transport->open(hci_stack.config);
303         if (err){
304             fprintf(stderr, "HCI_INIT failed, turning Bluetooth off again\n");
305             hci_stack.control->off(hci_stack.config);
306             hci_emit_hci_open_failed();
307             return err;
308         }
309 
310         // set up state machine
311         hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
312         hci_stack.state = HCI_STATE_INITIALIZING;
313         hci_stack.substate = 0;
314 
315     } else if (power_mode == HCI_POWER_OFF && hci_stack.state == HCI_STATE_WORKING){
316 
317         // close low-level device
318         hci_stack.hci_transport->close(hci_stack.config);
319 
320         // power off
321         hci_stack.control->off(hci_stack.config);
322 
323         // we're off now
324         hci_stack.state = HCI_STATE_OFF;
325     }
326 
327     // create internal event
328 	hci_emit_state();
329 
330 	// trigger next/first action
331 	hci_run();
332 
333     return 0;
334 }
335 
336 void hci_run(){
337     switch (hci_stack.state){
338         case HCI_STATE_INITIALIZING:
339             if (hci_stack.substate % 2) {
340                 // odd: waiting for command completion
341                 return;
342             }
343             if (hci_stack.num_cmd_packets == 0) {
344                 // cannot send command yet
345                 return;
346             }
347             switch (hci_stack.substate/2){
348                 case 0:
349                     hci_send_cmd(&hci_reset);
350                     break;
351 				case 1:
352 					hci_send_cmd(&hci_read_bd_addr);
353 					break;
354                 case 2:
355                     // ca. 15 sec
356                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
357                     break;
358 				case 3:
359 					hci_send_cmd(&hci_write_scan_enable, 3); // 3 inq scan + page scan
360 					break;
361                 case 4:
362                     // done.
363                     hci_stack.state = HCI_STATE_WORKING;
364                     hci_emit_state();
365                     break;
366                 default:
367                     break;
368             }
369             hci_stack.substate++;
370             break;
371         default:
372             break;
373     }
374 }
375 
376 int hci_send_cmd_packet(uint8_t *packet, int size){
377     bd_addr_t addr;
378     hci_connection_t * conn;
379     // house-keeping
380 
381     // create_connection?
382     if (IS_COMMAND(packet, hci_create_connection)){
383         bt_flip_addr(addr, &packet[3]);
384         printf("Create_connection to "); print_bd_addr(addr); printf("\n");
385         conn = connection_for_address(addr);
386         if (conn) {
387             // if connection exists
388             if (conn->state == OPEN) {
389                 // if OPEN, emit connection complete command
390                 hci_emit_connection_complete(conn);
391             }
392             //    otherwise, just ignore
393             return 0; // don't sent packet to controller
394 
395         } else{
396             conn = create_connection_for_addr(addr);
397             if (conn){
398                 //    create connection struct and register, state = SENT_CREATE_CONNECTION
399                 conn->state = SENT_CREATE_CONNECTION;
400             }
401         }
402     }
403 
404     // accept connection
405 
406     // reject connection
407 
408     // close_connection?
409       // set state = SENT_DISCONNECT
410 
411     hci_stack.num_cmd_packets--;
412     return hci_stack.hci_transport->send_cmd_packet(packet, size);
413 }
414 
415 /**
416  * pre: numcmds >= 0 - it's allowed to send a command to the controller
417  */
418 int hci_send_cmd(hci_cmd_t *cmd, ...){
419     va_list argptr;
420     va_start(argptr, cmd);
421     uint8_t * hci_cmd_buffer = hci_stack.hci_cmd_buffer;
422     uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr);
423     va_end(argptr);
424     return hci_send_cmd_packet(hci_cmd_buffer, size);
425 }
426 
427 // Create various non-HCI events.
428 // TODO: generalize, use table similar to hci_create_command
429 
430 void hci_emit_state(){
431     uint8_t len = 3;
432     uint8_t event[len];
433     event[0] = BTSTACK_EVENT_STATE;
434     event[1] = 1;
435     event[2] = hci_stack.state;
436     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
437     hci_stack.event_packet_handler(event, len);
438 }
439 
440 void hci_emit_connection_complete(hci_connection_t *conn){
441     uint8_t len = 13;
442     uint8_t event[len];
443     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
444     event[2] = 0; // status = OK
445     bt_store_16(event, 3, conn->con_handle);
446     bt_flip_addr(&event[5], conn->address);
447     event[11] = 1; // ACL connection
448     event[12] = 0; // encryption disabled
449     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
450     hci_stack.event_packet_handler(event, len);
451 }
452 
453 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
454     uint8_t len = 4;
455     uint8_t event[len];
456     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
457     event[1] = 2;
458     bt_store_16(event, 2, conn->con_handle);
459     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
460     hci_stack.event_packet_handler(event, len);
461 }
462 
463 void hci_emit_nr_connections_changed(){
464     uint8_t len = 3;
465     uint8_t event[len];
466     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
467     event[1] = 1;
468     event[2] = nr_hci_connections();
469     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
470     hci_stack.event_packet_handler(event, len);
471 }
472 
473 void hci_emit_hci_open_failed(){
474     uint8_t len = 1;
475     uint8_t event[len];
476     event[0] = BTSTACK_EVENT_POWERON_FAILED;
477     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
478     hci_stack.event_packet_handler(event, len);
479 }
480