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