xref: /btstack/src/hci.c (revision ee091cf1fdd21fd33ab1793564ec007cd1d10ad1)
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 /**
99  * Dummy handler called by HCI
100  */
101 static void dummy_handler(uint8_t *packet, uint16_t size){
102 }
103 
104 /**
105  * Dummy control handler
106  */
107 static int null_control_function(void *config){
108     return 0;
109 }
110 static const char * null_control_name(void *config){
111     return "Hardware unknown";
112 }
113 static bt_control_t null_control = {
114     null_control_function,
115     null_control_function,
116     null_control_function,
117     null_control_name
118 };
119 
120 
121 int hci_send_acl_packet(uint8_t *packet, int size){
122     hci_connection_update_timestamp_for_acl(packet);
123     return hci_stack.hci_transport->send_acl_packet(packet, size);
124 }
125 
126 static void acl_handler(uint8_t *packet, int size){
127     hci_connection_update_timestamp_for_acl(packet);
128     hci_stack.acl_packet_handler(packet, size);
129 
130     // execute main loop
131     hci_run();
132 }
133 
134 static void event_handler(uint8_t *packet, int size){
135     bd_addr_t addr;
136     hci_con_handle_t handle;
137 
138     // Get Num_HCI_Command_Packets
139     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE ||
140         packet[0] == HCI_EVENT_COMMAND_STATUS){
141         hci_stack.num_cmd_packets = packet[2];
142     }
143 
144     // Connection management
145     if (packet[0] == HCI_EVENT_CONNECTION_COMPLETE) {
146         if (!packet[2]){
147             bt_flip_addr(addr, &packet[5]);
148             printf("Connection_complete "); print_bd_addr(addr); printf("\n");
149             hci_connection_t * conn = connection_for_address(addr);
150             if (conn) {
151                 conn->state = OPEN;
152                 conn->con_handle = READ_BT_16(packet, 3);
153                 conn->flags = 0;
154 
155                 gettimeofday(&conn->timestamp, NULL);
156                 run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT);
157                 run_loop_add_timer(&conn->timeout);
158 
159                 printf("New connection: handle %u, ", conn->con_handle);
160                 print_bd_addr( conn->address );
161                 printf("\n");
162             }
163         }
164     }
165 
166     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE) {
167         if (!packet[2]){
168             handle = READ_BT_16(packet, 3);
169             hci_connection_t * conn = connection_for_handle(handle);
170             if (conn) {
171                 printf("Connection closed: handle %u, ", conn->con_handle);
172                 print_bd_addr( conn->address );
173                 printf("\n");
174                 run_loop_remove_timer(&conn->timeout);
175                 linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
176                 free( conn );
177             }
178         }
179     }
180 
181     // handle BT initialization
182     if (hci_stack.state == HCI_STATE_INITIALIZING){
183         // handle H4 synchronization loss on restart
184         // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){
185         //    hci_stack.substate = 0;
186         // }
187         // handle normal init sequence
188         if (hci_stack.substate % 2){
189             // odd: waiting for event
190             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
191                 hci_stack.substate++;
192             }
193         }
194     }
195 
196     // link key request
197     if (packet[0] == HCI_EVENT_LINK_KEY_REQUEST){
198         bt_flip_addr(addr, &packet[2]);
199         hci_send_cmd(&hci_link_key_request_negative_reply, &addr);
200         return;
201     }
202 
203     // pin code request
204     if (packet[0] == HCI_EVENT_PIN_CODE_REQUEST){
205         bt_flip_addr(addr, &packet[2]);
206         hci_send_cmd(&hci_pin_code_request_reply, &addr, 4, "1234");
207     }
208 
209     hci_stack.event_packet_handler(packet, size);
210 
211 	// execute main loop
212 	hci_run();
213 }
214 
215 /** Register HCI packet handlers */
216 void hci_register_event_packet_handler(void (*handler)(uint8_t *packet, uint16_t size)){
217     hci_stack.event_packet_handler = handler;
218 }
219 void hci_register_acl_packet_handler  (void (*handler)(uint8_t *packet, uint16_t size)){
220     hci_stack.acl_packet_handler = handler;
221 }
222 
223 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control){
224 
225     // reference to use transport layer implementation
226     hci_stack.hci_transport = transport;
227 
228     // references to used control implementation
229     if (control) {
230         hci_stack.control = control;
231     } else {
232         hci_stack.control = &null_control;
233     }
234 
235     // reference to used config
236     hci_stack.config = config;
237 
238     // no connections yet
239     hci_stack.connections = NULL;
240 
241     // empty cmd buffer
242     hci_stack.hci_cmd_buffer = malloc(3+255);
243 
244     // higher level handler
245     hci_stack.event_packet_handler = dummy_handler;
246     hci_stack.acl_packet_handler = dummy_handler;
247 
248     // register packet handlers with transport
249     transport->register_event_packet_handler( event_handler);
250     transport->register_acl_packet_handler( acl_handler);
251 }
252 
253 int hci_power_control(HCI_POWER_MODE power_mode){
254     if (power_mode == HCI_POWER_ON && hci_stack.state == HCI_STATE_OFF) {
255 
256         // set up state machine
257         hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
258         hci_stack.state = HCI_STATE_INITIALIZING;
259         hci_stack.substate = 0;
260 
261         // power on
262         hci_stack.control->on(hci_stack.config);
263 
264         // open low-level device
265         hci_stack.hci_transport->open(hci_stack.config);
266 
267         // create internal event
268 
269     } else if (power_mode == HCI_POWER_OFF && hci_stack.state == HCI_STATE_WORKING){
270 
271         // close low-level device
272         hci_stack.hci_transport->close(hci_stack.config);
273 
274         // power off
275         hci_stack.control->off(hci_stack.config);
276     }
277 
278 	hci_emit_state();
279 
280 	// trigger next/first action
281 	hci_run();
282 
283     return 0;
284 }
285 
286 void hci_run(){
287     uint8_t micro_packet;
288     switch (hci_stack.state){
289         case HCI_STATE_INITIALIZING:
290             if (hci_stack.substate % 2) {
291                 // odd: waiting for command completion
292                 return;
293             }
294             if (hci_stack.num_cmd_packets == 0) {
295                 // cannot send command yet
296                 return;
297             }
298             switch (hci_stack.substate/2){
299                 case 0:
300                     hci_send_cmd(&hci_reset);
301                     break;
302 				case 1:
303 					hci_send_cmd(&hci_read_bd_addr);
304 					break;
305                 case 2:
306                     // ca. 15 sec
307                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
308                     break;
309 				case 3:
310 					hci_send_cmd(&hci_write_scan_enable, 3); // 3 inq scan + page scan
311 					break;
312                 case 4:
313                     // done.
314                     hci_stack.state = HCI_STATE_WORKING;
315                     micro_packet = HCI_EVENT_BTSTACK_WORKING;
316                     hci_stack.event_packet_handler(&micro_packet, 1);
317                     break;
318                 default:
319                     break;
320             }
321             hci_stack.substate++;
322             break;
323         default:
324             break;
325     }
326 }
327 
328 int hci_send_cmd_packet(uint8_t *packet, int size){
329     bd_addr_t addr;
330     hci_connection_t * conn;
331     // house-keeping
332 
333     // create_connection?
334     if (IS_COMMAND(packet, hci_create_connection)){
335         bt_flip_addr(addr, &packet[3]);
336         printf("Create_connection to "); print_bd_addr(addr); printf("\n");
337         conn = connection_for_address(addr);
338         if (conn) {
339             // if connection exists
340             if (conn->state == OPEN) {
341                 // if OPEN, emit connection complete command
342                 hci_emit_connection_complete(conn);
343             }
344             //    otherwise, just ignore
345             return 0; // don't sent packet to controller
346 
347         } else{
348             conn = create_connection_for_addr(addr);
349             if (conn){
350                 //    create connection struct and register, state = SENT_CREATE_CONNECTION
351                 conn->state = SENT_CREATE_CONNECTION;
352             }
353         }
354     }
355 
356     // accept connection
357 
358     // reject connection
359 
360     // close_connection?
361       // set state = SENT_DISCONNECT
362 
363     hci_stack.num_cmd_packets--;
364     return hci_stack.hci_transport->send_cmd_packet(packet, size);
365 }
366 
367 /**
368  * pre: numcmds >= 0 - it's allowed to send a command to the controller
369  */
370 int hci_send_cmd(hci_cmd_t *cmd, ...){
371     va_list argptr;
372     va_start(argptr, cmd);
373     uint8_t * hci_cmd_buffer = hci_stack.hci_cmd_buffer;
374     uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr);
375     va_end(argptr);
376     return hci_send_cmd_packet(hci_cmd_buffer, size);
377 }
378 
379 // Create various non-HCI events.
380 // TODO: generalize, use table similar to hci_create_command
381 
382 void hci_emit_state(){
383     uint8_t len = 3;
384     uint8_t event[len];
385     event[0] = HCI_EVENT_BTSTACK_STATE;
386     event[1] = 1;
387     event[2] = hci_stack.state;
388     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
389     hci_stack.event_packet_handler(event, len);
390 }
391 
392 void hci_emit_connection_complete(hci_connection_t *conn){
393     uint8_t len = 13;
394     uint8_t event[len];
395     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
396     event[2] = 0; // status = OK
397     bt_store_16(event, 3, conn->con_handle);
398     bt_flip_addr(&event[5], conn->address);
399     event[11] = 1; // ACL connection
400     event[12] = 0; // encryption disabled
401     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
402     hci_stack.event_packet_handler(event, len);
403 }
404 
405 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
406     uint8_t len = 4;
407     uint8_t event[len];
408     event[0] = HCI_EVENT_L2CAP_TIMEOUT_CHECK;
409     event[1] = 2;
410     bt_store_16(event, 2, conn->con_handle);
411     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
412     hci_stack.event_packet_handler(event, len);
413 }
414