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