xref: /btstack/src/hci.c (revision ac2e07f8dd09e7f1b309f34acfaf76b249bb0a2e)
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;
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     // pin code request
216     if (packet[0] == HCI_EVENT_PIN_CODE_REQUEST){
217         bt_flip_addr(addr, &packet[2]);
218         hci_send_cmd(&hci_pin_code_request_reply, &addr, 4, "1234");
219     }
220 
221     hci_stack.event_packet_handler(packet, size);
222 
223 	// execute main loop
224 	hci_run();
225 }
226 
227 /** Register HCI packet handlers */
228 void hci_register_event_packet_handler(void (*handler)(uint8_t *packet, uint16_t size)){
229     hci_stack.event_packet_handler = handler;
230 }
231 void hci_register_acl_packet_handler  (void (*handler)(uint8_t *packet, uint16_t size)){
232     hci_stack.acl_packet_handler = handler;
233 }
234 
235 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control){
236 
237     // reference to use transport layer implementation
238     hci_stack.hci_transport = transport;
239 
240     // references to used control implementation
241     if (control) {
242         hci_stack.control = control;
243     } else {
244         hci_stack.control = &null_control;
245     }
246 
247     // reference to used config
248     hci_stack.config = config;
249 
250     // no connections yet
251     hci_stack.connections = NULL;
252 
253     // empty cmd buffer
254     hci_stack.hci_cmd_buffer = malloc(3+255);
255 
256     // higher level handler
257     hci_stack.event_packet_handler = dummy_handler;
258     hci_stack.acl_packet_handler = dummy_handler;
259 
260     // register packet handlers with transport
261     transport->register_event_packet_handler( event_handler);
262     transport->register_acl_packet_handler( acl_handler);
263 }
264 
265 int hci_power_control(HCI_POWER_MODE power_mode){
266     if (power_mode == HCI_POWER_ON && hci_stack.state == HCI_STATE_OFF) {
267 
268         // power on
269         int err = hci_stack.control->on(hci_stack.config);
270         if (err){
271             fprintf(stderr, "POWER_ON failed\n");
272             hci_emit_hci_open_failed();
273             return err;
274         }
275 
276         // open low-level device
277         err = hci_stack.hci_transport->open(hci_stack.config);
278         if (err){
279             fprintf(stderr, "HCI_INIT failed, turning Bluetooth off again\n");
280             hci_stack.control->off(hci_stack.config);
281             hci_emit_hci_open_failed();
282             return err;
283         }
284 
285         // set up state machine
286         hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
287         hci_stack.state = HCI_STATE_INITIALIZING;
288         hci_stack.substate = 0;
289 
290     } else if (power_mode == HCI_POWER_OFF && hci_stack.state == HCI_STATE_WORKING){
291 
292         // close low-level device
293         hci_stack.hci_transport->close(hci_stack.config);
294 
295         // power off
296         hci_stack.control->off(hci_stack.config);
297 
298         // we're off now
299         hci_stack.state = HCI_STATE_OFF;
300     }
301 
302     // create internal event
303 	hci_emit_state();
304 
305 	// trigger next/first action
306 	hci_run();
307 
308     return 0;
309 }
310 
311 void hci_run(){
312     uint8_t micro_packet;
313     switch (hci_stack.state){
314         case HCI_STATE_INITIALIZING:
315             if (hci_stack.substate % 2) {
316                 // odd: waiting for command completion
317                 return;
318             }
319             if (hci_stack.num_cmd_packets == 0) {
320                 // cannot send command yet
321                 return;
322             }
323             switch (hci_stack.substate/2){
324                 case 0:
325                     hci_send_cmd(&hci_reset);
326                     break;
327 				case 1:
328 					hci_send_cmd(&hci_read_bd_addr);
329 					break;
330                 case 2:
331                     // ca. 15 sec
332                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
333                     break;
334 				case 3:
335 					hci_send_cmd(&hci_write_scan_enable, 3); // 3 inq scan + page scan
336 					break;
337                 case 4:
338                     // done.
339                     hci_stack.state = HCI_STATE_WORKING;
340                     micro_packet = HCI_EVENT_BTSTACK_WORKING;
341                     hci_stack.event_packet_handler(&micro_packet, 1);
342                     break;
343                 default:
344                     break;
345             }
346             hci_stack.substate++;
347             break;
348         default:
349             break;
350     }
351 }
352 
353 int hci_send_cmd_packet(uint8_t *packet, int size){
354     bd_addr_t addr;
355     hci_connection_t * conn;
356     // house-keeping
357 
358     // create_connection?
359     if (IS_COMMAND(packet, hci_create_connection)){
360         bt_flip_addr(addr, &packet[3]);
361         printf("Create_connection to "); print_bd_addr(addr); printf("\n");
362         conn = connection_for_address(addr);
363         if (conn) {
364             // if connection exists
365             if (conn->state == OPEN) {
366                 // if OPEN, emit connection complete command
367                 hci_emit_connection_complete(conn);
368             }
369             //    otherwise, just ignore
370             return 0; // don't sent packet to controller
371 
372         } else{
373             conn = create_connection_for_addr(addr);
374             if (conn){
375                 //    create connection struct and register, state = SENT_CREATE_CONNECTION
376                 conn->state = SENT_CREATE_CONNECTION;
377             }
378         }
379     }
380 
381     // accept connection
382 
383     // reject connection
384 
385     // close_connection?
386       // set state = SENT_DISCONNECT
387 
388     hci_stack.num_cmd_packets--;
389     return hci_stack.hci_transport->send_cmd_packet(packet, size);
390 }
391 
392 /**
393  * pre: numcmds >= 0 - it's allowed to send a command to the controller
394  */
395 int hci_send_cmd(hci_cmd_t *cmd, ...){
396     va_list argptr;
397     va_start(argptr, cmd);
398     uint8_t * hci_cmd_buffer = hci_stack.hci_cmd_buffer;
399     uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr);
400     va_end(argptr);
401     return hci_send_cmd_packet(hci_cmd_buffer, size);
402 }
403 
404 // Create various non-HCI events.
405 // TODO: generalize, use table similar to hci_create_command
406 
407 void hci_emit_state(){
408     uint8_t len = 3;
409     uint8_t event[len];
410     event[0] = HCI_EVENT_BTSTACK_STATE;
411     event[1] = 1;
412     event[2] = hci_stack.state;
413     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
414     hci_stack.event_packet_handler(event, len);
415 }
416 
417 void hci_emit_connection_complete(hci_connection_t *conn){
418     uint8_t len = 13;
419     uint8_t event[len];
420     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
421     event[2] = 0; // status = OK
422     bt_store_16(event, 3, conn->con_handle);
423     bt_flip_addr(&event[5], conn->address);
424     event[11] = 1; // ACL connection
425     event[12] = 0; // encryption disabled
426     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
427     hci_stack.event_packet_handler(event, len);
428 }
429 
430 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
431     uint8_t len = 4;
432     uint8_t event[len];
433     event[0] = HCI_EVENT_L2CAP_TIMEOUT_CHECK;
434     event[1] = 2;
435     bt_store_16(event, 2, conn->con_handle);
436     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
437     hci_stack.event_packet_handler(event, len);
438 }
439 
440 void hci_emit_nr_connections_changed(){
441     uint8_t len = 3;
442     uint8_t event[len];
443     event[0] = HCI_EVENT_NR_CONNECTIONS_CHANGED;
444     event[1] = 1;
445     event[2] = nr_hci_connections();
446     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
447     hci_stack.event_packet_handler(event, len);
448 }
449 
450 void hci_emit_hci_open_failed(){
451     uint8_t len = 1;
452     uint8_t event[len];
453     event[0] = HCI_EVENT_POWERON_FAILED;
454     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
455     hci_stack.event_packet_handler(event, len);
456 }
457