xref: /btstack/src/hci.c (revision 43bfb1bd9ce527929f7260490b797482f1a04ec4)
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         // set up state machine
269         hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
270         hci_stack.state = HCI_STATE_INITIALIZING;
271         hci_stack.substate = 0;
272 
273         // power on
274         hci_stack.control->on(hci_stack.config);
275 
276         // open low-level device
277         hci_stack.hci_transport->open(hci_stack.config);
278 
279         // create internal event
280 
281     } else if (power_mode == HCI_POWER_OFF && hci_stack.state == HCI_STATE_WORKING){
282 
283         // close low-level device
284         hci_stack.hci_transport->close(hci_stack.config);
285 
286         // power off
287         hci_stack.control->off(hci_stack.config);
288 
289         // we're off now
290         hci_stack.state = HCI_STATE_OFF;
291     }
292 
293 	hci_emit_state();
294 
295 	// trigger next/first action
296 	hci_run();
297 
298     return 0;
299 }
300 
301 void hci_run(){
302     uint8_t micro_packet;
303     switch (hci_stack.state){
304         case HCI_STATE_INITIALIZING:
305             if (hci_stack.substate % 2) {
306                 // odd: waiting for command completion
307                 return;
308             }
309             if (hci_stack.num_cmd_packets == 0) {
310                 // cannot send command yet
311                 return;
312             }
313             switch (hci_stack.substate/2){
314                 case 0:
315                     hci_send_cmd(&hci_reset);
316                     break;
317 				case 1:
318 					hci_send_cmd(&hci_read_bd_addr);
319 					break;
320                 case 2:
321                     // ca. 15 sec
322                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
323                     break;
324 				case 3:
325 					hci_send_cmd(&hci_write_scan_enable, 3); // 3 inq scan + page scan
326 					break;
327                 case 4:
328                     // done.
329                     hci_stack.state = HCI_STATE_WORKING;
330                     micro_packet = HCI_EVENT_BTSTACK_WORKING;
331                     hci_stack.event_packet_handler(&micro_packet, 1);
332                     break;
333                 default:
334                     break;
335             }
336             hci_stack.substate++;
337             break;
338         default:
339             break;
340     }
341 }
342 
343 int hci_send_cmd_packet(uint8_t *packet, int size){
344     bd_addr_t addr;
345     hci_connection_t * conn;
346     // house-keeping
347 
348     // create_connection?
349     if (IS_COMMAND(packet, hci_create_connection)){
350         bt_flip_addr(addr, &packet[3]);
351         printf("Create_connection to "); print_bd_addr(addr); printf("\n");
352         conn = connection_for_address(addr);
353         if (conn) {
354             // if connection exists
355             if (conn->state == OPEN) {
356                 // if OPEN, emit connection complete command
357                 hci_emit_connection_complete(conn);
358             }
359             //    otherwise, just ignore
360             return 0; // don't sent packet to controller
361 
362         } else{
363             conn = create_connection_for_addr(addr);
364             if (conn){
365                 //    create connection struct and register, state = SENT_CREATE_CONNECTION
366                 conn->state = SENT_CREATE_CONNECTION;
367             }
368         }
369     }
370 
371     // accept connection
372 
373     // reject connection
374 
375     // close_connection?
376       // set state = SENT_DISCONNECT
377 
378     hci_stack.num_cmd_packets--;
379     return hci_stack.hci_transport->send_cmd_packet(packet, size);
380 }
381 
382 /**
383  * pre: numcmds >= 0 - it's allowed to send a command to the controller
384  */
385 int hci_send_cmd(hci_cmd_t *cmd, ...){
386     va_list argptr;
387     va_start(argptr, cmd);
388     uint8_t * hci_cmd_buffer = hci_stack.hci_cmd_buffer;
389     uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr);
390     va_end(argptr);
391     return hci_send_cmd_packet(hci_cmd_buffer, size);
392 }
393 
394 // Create various non-HCI events.
395 // TODO: generalize, use table similar to hci_create_command
396 
397 void hci_emit_state(){
398     uint8_t len = 3;
399     uint8_t event[len];
400     event[0] = HCI_EVENT_BTSTACK_STATE;
401     event[1] = 1;
402     event[2] = hci_stack.state;
403     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
404     hci_stack.event_packet_handler(event, len);
405 }
406 
407 void hci_emit_connection_complete(hci_connection_t *conn){
408     uint8_t len = 13;
409     uint8_t event[len];
410     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
411     event[2] = 0; // status = OK
412     bt_store_16(event, 3, conn->con_handle);
413     bt_flip_addr(&event[5], conn->address);
414     event[11] = 1; // ACL connection
415     event[12] = 0; // encryption disabled
416     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
417     hci_stack.event_packet_handler(event, len);
418 }
419 
420 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
421     uint8_t len = 4;
422     uint8_t event[len];
423     event[0] = HCI_EVENT_L2CAP_TIMEOUT_CHECK;
424     event[1] = 2;
425     bt_store_16(event, 2, conn->con_handle);
426     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
427     hci_stack.event_packet_handler(event, len);
428 }
429 
430 void hci_emit_nr_connections_changed(){
431     uint8_t len = 3;
432     uint8_t event[len];
433     event[0] = HCI_EVENT_NR_CONNECTIONS_CHANGED;
434     event[1] = 1;
435     event[2] = nr_hci_connections();
436     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
437     hci_stack.event_packet_handler(event, len);
438 }
439