xref: /btstack/src/hci.c (revision c12e46e766afa6ed133f629380d6622db1508db3)
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 "hci.h"
40 
41 #include <unistd.h>
42 #include <stdarg.h>
43 #include <string.h>
44 #include <stdio.h>
45 
46 #include "debug.h"
47 #include "hci_dump.h"
48 
49 #include "../include/btstack/hci_cmds.h"
50 #include "../include/btstack/version.h"
51 
52 // temp
53 #include "l2cap.h"
54 
55 #define HCI_CONNECTION_TIMEOUT_MS 10000
56 
57 // the STACK is here
58 static hci_stack_t       hci_stack;
59 
60 /**
61  * get connection for a given handle
62  *
63  * @return connection OR NULL, if not found
64  */
65 hci_connection_t * connection_for_handle(hci_con_handle_t con_handle){
66     linked_item_t *it;
67     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
68         if ( ((hci_connection_t *) it)->con_handle == con_handle){
69             return (hci_connection_t *) it;
70         }
71     }
72     return NULL;
73 }
74 
75 static void hci_connection_timeout_handler(timer_source_t *timer){
76     hci_connection_t * connection = linked_item_get_user(&timer->item);
77     struct timeval tv;
78     gettimeofday(&tv, NULL);
79     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
80         // connections might be timed out
81         hci_emit_l2cap_check_timeout(connection);
82         run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
83     } else {
84         // next timeout check at
85         timer->timeout.tv_sec = connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000;
86     }
87     run_loop_add_timer(timer);
88 }
89 
90 static void hci_connection_timestamp(hci_connection_t *connection){
91     gettimeofday(&connection->timestamp, NULL);
92 }
93 
94 /**
95  * create connection for given address
96  *
97  * @return connection OR NULL, if not found
98  */
99 static hci_connection_t * create_connection_for_addr(bd_addr_t addr){
100     hci_connection_t * conn = malloc( sizeof(hci_connection_t) );
101     if (!conn) return NULL;
102     BD_ADDR_COPY(conn->address, addr);
103     conn->con_handle = 0xffff;
104     conn->authentication_flags = 0;
105     linked_item_set_user(&conn->timeout.item, conn);
106     conn->timeout.process = hci_connection_timeout_handler;
107     hci_connection_timestamp(conn);
108     conn->acl_recombination_length = 0;
109     conn->acl_recombination_pos = 0;
110     conn->num_acl_packets_sent = 0;
111     linked_list_add(&hci_stack.connections, (linked_item_t *) conn);
112     return conn;
113 }
114 
115 /**
116  * get connection for given address
117  *
118  * @return connection OR NULL, if not found
119  */
120 static hci_connection_t * connection_for_address(bd_addr_t address){
121     linked_item_t *it;
122     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
123         if ( ! BD_ADDR_CMP( ((hci_connection_t *) it)->address, address) ){
124             return (hci_connection_t *) it;
125         }
126     }
127     return NULL;
128 }
129 
130 /**
131  * add authentication flags and reset timer
132  */
133 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
134     bd_addr_t addr;
135     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
136     hci_connection_t * conn = connection_for_address(addr);
137     if (conn) {
138         conn->authentication_flags |= flags;
139         hci_connection_timestamp(conn);
140     }
141 }
142 
143 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
144     hci_connection_t * conn = connection_for_handle(handle);
145     if (!conn) return 0;
146     if (!conn->authentication_flags) return 0;
147     if (conn->authentication_flags & SENT_LINK_KEY_REPLY) return 0;
148     if (conn->authentication_flags & RECV_LINK_KEY_NOTIFICATION) return 0;
149     return 1;
150 }
151 
152 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
153     if (hci_stack.remote_device_db) {
154         hci_stack.remote_device_db->delete_link_key(addr);
155     }
156 }
157 
158 
159 /**
160  * count connections
161  */
162 static int nr_hci_connections(){
163     int count = 0;
164     linked_item_t *it;
165     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next, count++);
166     return count;
167 }
168 
169 /**
170  * Dummy handler called by HCI
171  */
172 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
173 }
174 
175 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
176     hci_connection_t * connection = connection_for_handle(handle);
177     if (!connection) {
178         log_err("hci_number_outgoing_packets connectino for handle %u does not exist!\n", handle);
179         return 0;
180     }
181     return connection->num_acl_packets_sent;
182 }
183 
184 uint8_t hci_number_free_acl_slots(){
185     uint8_t free_slots = hci_stack.total_num_acl_packets;
186     linked_item_t *it;
187     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
188         hci_connection_t * connection = (hci_connection_t *) it;
189         if (free_slots < connection->num_acl_packets_sent) {
190             log_err("hci_number_free_acl_slots: sum of outgoing packets > total acl packets!\n");
191             return 0;
192         }
193         free_slots -= connection->num_acl_packets_sent;
194     }
195     return free_slots;
196 }
197 
198 int hci_ready_to_send(hci_con_handle_t handle){
199     return hci_number_free_acl_slots() && hci_number_outgoing_packets(handle) < 2;
200 }
201 
202 int hci_send_acl_packet(uint8_t *packet, int size){
203 
204     // check for free places on BT module
205     if (!hci_number_free_acl_slots()) return -1;
206 
207     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
208     hci_connection_t *connection = connection_for_handle( con_handle);
209     if (!connection) return 0;
210     hci_connection_timestamp(connection);
211 
212     // count packet
213     connection->num_acl_packets_sent++;
214     // log_dbg("hci_send_acl_packet - handle %u, sent %u\n", connection->con_handle, connection->num_acl_packets_sent);
215 
216     // send packet - ignore errors
217     hci_stack.hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
218 
219     return 0;
220 }
221 
222 static void acl_handler(uint8_t *packet, int size){
223 
224     // get info
225     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
226     hci_connection_t *conn      = connection_for_handle(con_handle);
227     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
228     uint16_t acl_length         = READ_ACL_LENGTH(packet);
229 
230     // ignore non-registered handle
231     if (!conn){
232         log_err( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle);
233         return;
234     }
235 
236     // update idle timestamp
237     hci_connection_timestamp(conn);
238 
239     // handle different packet types
240     switch (acl_flags & 0x03) {
241 
242         case 0x01: // continuation fragment
243 
244             // sanity check
245             if (conn->acl_recombination_pos == 0) {
246                 log_err( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle);
247                 return;
248             }
249 
250             // append fragment payload (header already stored)
251             memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length );
252             conn->acl_recombination_pos += acl_length;
253 
254             // log_err( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n",
255             //        acl_length, connection->acl_recombination_pos, connection->acl_recombination_length);
256 
257             // forward complete L2CAP packet if complete.
258             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
259 
260                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos);
261                 // reset recombination buffer
262                 conn->acl_recombination_length = 0;
263                 conn->acl_recombination_pos = 0;
264             }
265             break;
266 
267         case 0x02: { // first fragment
268 
269             // sanity check
270             if (conn->acl_recombination_pos) {
271                 log_err( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle);
272                 return;
273             }
274 
275             // peek into L2CAP packet!
276             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
277 
278             // compare fragment size to L2CAP packet size
279             if (acl_length >= l2cap_length + 4){
280 
281                 // forward fragment as L2CAP packet
282                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
283 
284             } else {
285                 // store first fragment and tweak acl length for complete package
286                 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4);
287                 conn->acl_recombination_pos    = acl_length + 4;
288                 conn->acl_recombination_length = l2cap_length;
289                 bt_store_16(conn->acl_recombination_buffer, 2, acl_length +4);
290                 // log_err( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length);
291             }
292             break;
293 
294         }
295         default:
296             log_err( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03);
297             return;
298     }
299 
300     // execute main loop
301     hci_run();
302 }
303 
304 static void event_handler(uint8_t *packet, int size){
305     bd_addr_t addr;
306     hci_con_handle_t handle;
307     hci_connection_t * conn;
308     int i;
309     link_key_t link_key;
310 
311     // get num_cmd_packets
312     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){
313         // Get Num_HCI_Command_Packets
314         hci_stack.num_cmd_packets = packet[2];
315     }
316 
317     switch (packet[0]) {
318 
319         case HCI_EVENT_COMMAND_COMPLETE:
320             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
321                 // from offset 5
322                 // status
323                 hci_stack.acl_data_packet_length = READ_BT_16(packet, 6);
324                 // ignore: SCO data packet len (8)
325                 hci_stack.total_num_acl_packets  = packet[9];
326                 // ignore: total num SCO packets
327                 if (hci_stack.state == HCI_STATE_INITIALIZING){
328                     log_dbg("hci_read_buffer_size: size %u, count %u\n", hci_stack.acl_data_packet_length, hci_stack.total_num_acl_packets);
329                 }
330             }
331             break;
332 
333         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
334             for (i=0; i<packet[2];i++){
335                 handle = READ_BT_16(packet, 3 + 2*i);
336                 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i);
337                 conn = connection_for_handle(handle);
338                 if (!conn){
339                     log_err("hci_number_completed_packet lists unused con handle %u\n", handle);
340                     continue;
341                 }
342                 conn->num_acl_packets_sent -= num_packets;
343                 // log_dbg("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent);
344             }
345             break;
346 
347         case HCI_EVENT_CONNECTION_REQUEST:
348             bt_flip_addr(addr, &packet[2]);
349             // TODO: eval COD 8-10
350             uint8_t link_type = packet[11];
351             log_dbg("Connection_incoming: "); print_bd_addr(addr); log_dbg(", type %u\n", link_type);
352             if (link_type == 1) { // ACL
353                 conn = connection_for_address(addr);
354                 if (!conn) {
355                     conn = create_connection_for_addr(addr);
356                 }
357                 // TODO: check for malloc failure
358                 conn->state = ACCEPTED_CONNECTION_REQUEST;
359                 hci_send_cmd(&hci_accept_connection_request, addr, 1);
360             } else {
361                 // TODO: decline request
362             }
363             break;
364 
365         case HCI_EVENT_CONNECTION_COMPLETE:
366             // Connection management
367             bt_flip_addr(addr, &packet[5]);
368             log_dbg("Connection_complete (status=%u)", packet[2]); print_bd_addr(addr); log_dbg("\n");
369             conn = connection_for_address(addr);
370             if (conn) {
371                 if (!packet[2]){
372                     conn->state = OPEN;
373                     conn->con_handle = READ_BT_16(packet, 3);
374 
375                     gettimeofday(&conn->timestamp, NULL);
376                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
377                     run_loop_add_timer(&conn->timeout);
378 
379                     log_dbg("New connection: handle %u, ", conn->con_handle);
380                     print_bd_addr( conn->address );
381                     log_dbg("\n");
382 
383                     hci_emit_nr_connections_changed();
384                 } else {
385 
386                     // connection failed, remove entry
387                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
388                     free( conn );
389 
390                     // if authentication error, also delete link key
391                     if (packet[2] == 0x05) {
392                         hci_drop_link_key_for_bd_addr(&addr);
393                     }
394                 }
395             }
396             break;
397 
398         case HCI_EVENT_LINK_KEY_REQUEST:
399             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
400             if (hci_stack.remote_device_db) {
401                 bt_flip_addr(addr, &packet[2]);
402                 if ( hci_stack.remote_device_db->get_link_key( &addr, &link_key)){
403                     hci_send_cmd(&hci_link_key_request_reply, &addr, &link_key);
404                 } else {
405                     hci_send_cmd(&hci_link_key_request_negative_reply, &addr);
406                 }
407                 // request already answered
408                 return;
409             }
410             break;
411 
412         case HCI_EVENT_LINK_KEY_NOTIFICATION:
413             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_NOTIFICATION);
414             if (hci_stack.remote_device_db) {
415                 bt_flip_addr(addr, &packet[2]);
416                 hci_stack.remote_device_db->put_link_key(&addr, &link_key);
417             }
418             // still forward event to allow dismiss of pairing dialog
419             break;
420 
421         case HCI_EVENT_PIN_CODE_REQUEST:
422             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_PIN_CODE_REQUEST);
423             break;
424 
425         case HCI_EVENT_DISCONNECTION_COMPLETE:
426             if (!packet[2]){
427                 handle = READ_BT_16(packet, 3);
428                 hci_connection_t * conn = connection_for_handle(handle);
429                 if (conn) {
430                     log_dbg("Connection closed: handle %u, ", conn->con_handle);
431                     print_bd_addr( conn->address );
432                     log_dbg("\n");
433                     run_loop_remove_timer(&conn->timeout);
434                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
435                     free( conn );
436                     hci_emit_nr_connections_changed();
437                 }
438             }
439             break;
440 
441         default:
442             break;
443     }
444 
445     // handle BT initialization
446     if (hci_stack.state == HCI_STATE_INITIALIZING){
447         // handle H4 synchronization loss on restart
448         // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){
449         //    hci_stack.substate = 0;
450         // }
451         // handle normal init sequence
452         if (hci_stack.substate % 2){
453             // odd: waiting for event
454             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
455                 hci_stack.substate++;
456             }
457         }
458     }
459 
460     hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
461 
462 	// execute main loop
463 	hci_run();
464 }
465 
466 void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
467     switch (packet_type) {
468         case HCI_EVENT_PACKET:
469             event_handler(packet, size);
470             break;
471         case HCI_ACL_DATA_PACKET:
472             acl_handler(packet, size);
473             break;
474         default:
475             break;
476     }
477 }
478 
479 /** Register HCI packet handlers */
480 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
481     hci_stack.packet_handler = handler;
482 }
483 
484 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control){
485 
486     // reference to use transport layer implementation
487     hci_stack.hci_transport = transport;
488 
489     // references to used control implementation
490     hci_stack.control = control;
491 
492     // reference to used config
493     hci_stack.config = config;
494 
495     // no connections yet
496     hci_stack.connections = NULL;
497 
498     // empty cmd buffer
499     hci_stack.hci_cmd_buffer = malloc(3+255);
500 
501     // higher level handler
502     hci_stack.packet_handler = dummy_handler;
503 
504     // no link key db yet
505     hci_stack.remote_device_db = NULL;
506 
507     // register packet handlers with transport
508     transport->register_packet_handler(&packet_handler);
509 }
510 
511 int hci_power_control(HCI_POWER_MODE power_mode){
512     if (power_mode == HCI_POWER_ON && hci_stack.state == HCI_STATE_OFF) {
513 
514         // power on
515         int err = 0;
516         if (hci_stack.control && hci_stack.control->on){
517             err = (*hci_stack.control->on)(hci_stack.config);
518         }
519         if (err){
520             log_err( "POWER_ON failed\n");
521             hci_emit_hci_open_failed();
522             return err;
523         }
524 
525         // open low-level device
526         err = hci_stack.hci_transport->open(hci_stack.config);
527         if (err){
528             log_err( "HCI_INIT failed, turning Bluetooth off again\n");
529             if (hci_stack.control && hci_stack.control->off){
530                 (*hci_stack.control->off)(hci_stack.config);
531             }
532             hci_emit_hci_open_failed();
533             return err;
534         }
535 
536         // set up state machine
537         hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
538         hci_stack.state = HCI_STATE_INITIALIZING;
539         hci_stack.substate = 0;
540 
541     } else if (power_mode == HCI_POWER_OFF && hci_stack.state == HCI_STATE_WORKING){
542 
543         // close low-level device
544         hci_stack.hci_transport->close(hci_stack.config);
545 
546         // power off
547         if (hci_stack.control && hci_stack.control->off){
548             (*hci_stack.control->off)(hci_stack.config);
549         }
550 
551         // we're off now
552         hci_stack.state = HCI_STATE_OFF;
553     }
554 
555     // create internal event
556 	hci_emit_state();
557 
558 	// trigger next/first action
559 	hci_run();
560 
561     return 0;
562 }
563 
564 void hci_run(){
565 
566     switch (hci_stack.state){
567         case HCI_STATE_INITIALIZING:
568             if (hci_stack.substate % 2) {
569                 // odd: waiting for command completion
570                 return;
571             }
572             if (hci_stack.num_cmd_packets == 0) {
573                 // cannot send command yet
574                 return;
575             }
576             switch (hci_stack.substate >> 1){
577                 case 0:
578                     hci_send_cmd(&hci_reset);
579                     break;
580                 case 1:
581                     // custom initialization
582                     if (hci_stack.control && hci_stack.control->next_command){
583                         uint8_t * cmd = (*hci_stack.control->next_command)(hci_stack.config);
584                         if (cmd) {
585                             int size = 3 + cmd[2];
586                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, cmd, size);
587                             hci_stack.substate = 0; // more init commands
588                             break;
589                         }
590                     }
591                     // otherwise continue
592 					hci_send_cmd(&hci_read_bd_addr);
593 					break;
594 				case 2:
595 					hci_send_cmd(&hci_read_buffer_size);
596 					break;
597                 case 3:
598                     // ca. 15 sec
599                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
600                     break;
601 				case 4:
602 					hci_send_cmd(&hci_write_scan_enable, 3); // 3 inq scan + page scan
603 					break;
604                 case 5:
605 #ifndef EMBEDDED
606                 {
607                     char hostname[30];
608                     gethostname(hostname, 30);
609                     hostname[29] = '\0';
610                     hci_send_cmd(&hci_write_local_name, hostname);
611                     break;
612                 }
613                 case 6:
614 #endif
615                     // done.
616                     hci_stack.state = HCI_STATE_WORKING;
617                     hci_emit_state();
618                     break;
619                 default:
620                     break;
621             }
622             hci_stack.substate++;
623             break;
624         default:
625             break;
626     }
627 }
628 
629 int hci_send_cmd_packet(uint8_t *packet, int size){
630     bd_addr_t addr;
631     hci_connection_t * conn;
632     // house-keeping
633 
634     // create_connection?
635     if (IS_COMMAND(packet, hci_create_connection)){
636         bt_flip_addr(addr, &packet[3]);
637         log_dbg("Create_connection to "); print_bd_addr(addr); log_dbg("\n");
638         conn = connection_for_address(addr);
639         if (conn) {
640             // if connection exists
641             if (conn->state == OPEN) {
642                 // if OPEN, emit connection complete command
643                 hci_emit_connection_complete(conn);
644             }
645             //    otherwise, just ignore
646             return 0; // don't sent packet to controller
647 
648         } else{
649             conn = create_connection_for_addr(addr);
650             if (conn){
651                 //    create connection struct and register, state = SENT_CREATE_CONNECTION
652                 conn->state = SENT_CREATE_CONNECTION;
653             }
654         }
655     }
656 
657     if (IS_COMMAND(packet, hci_link_key_request_reply)){
658         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
659     }
660     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
661         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
662     }
663     if (IS_COMMAND(packet, hci_pin_code_request_reply)){
664         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY);
665     }
666     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){
667         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY);
668     }
669 
670     // accept connection
671 
672     // reject connection
673 
674     // close_connection?
675       // set state = SENT_DISCONNECT
676 
677     hci_stack.num_cmd_packets--;
678     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
679 }
680 
681 /**
682  * pre: numcmds >= 0 - it's allowed to send a command to the controller
683  */
684 int hci_send_cmd(const hci_cmd_t *cmd, ...){
685     va_list argptr;
686     va_start(argptr, cmd);
687     uint8_t * hci_cmd_buffer = hci_stack.hci_cmd_buffer;
688     uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr);
689     va_end(argptr);
690     return hci_send_cmd_packet(hci_cmd_buffer, size);
691 }
692 
693 // Create various non-HCI events.
694 // TODO: generalize, use table similar to hci_create_command
695 
696 void hci_emit_state(){
697     uint8_t len = 3;
698     uint8_t event[len];
699     event[0] = BTSTACK_EVENT_STATE;
700     event[1] = len - 3;
701     event[2] = hci_stack.state;
702     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
703     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
704 }
705 
706 void hci_emit_connection_complete(hci_connection_t *conn){
707     uint8_t len = 13;
708     uint8_t event[len];
709     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
710     event[1] = len - 3;
711     event[2] = 0; // status = OK
712     bt_store_16(event, 3, conn->con_handle);
713     bt_flip_addr(&event[5], conn->address);
714     event[11] = 1; // ACL connection
715     event[12] = 0; // encryption disabled
716     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
717     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
718 }
719 
720 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
721     uint8_t len = 4;
722     uint8_t event[len];
723     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
724     event[1] = len - 2;
725     bt_store_16(event, 2, conn->con_handle);
726     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
727     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
728 }
729 
730 void hci_emit_nr_connections_changed(){
731     uint8_t len = 3;
732     uint8_t event[len];
733     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
734     event[1] = len - 2;
735     event[2] = nr_hci_connections();
736     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
737     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
738 }
739 
740 void hci_emit_hci_open_failed(){
741     uint8_t len = 2;
742     uint8_t event[len];
743     event[0] = BTSTACK_EVENT_POWERON_FAILED;
744     event[1] = len - 2;
745     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
746     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
747 }
748 
749 
750 void hci_emit_btstack_version() {
751     uint8_t len = 6;
752     uint8_t event[len];
753     event[0] = BTSTACK_EVENT_VERSION;
754     event[1] = len - 2;
755     event[len++] = BTSTACK_MAJOR;
756     event[len++] = BTSTACK_MINOR;
757     bt_store_16(event, len, BTSTACK_REVISION);
758     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
759     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
760 }
761 
762 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
763     uint8_t len = 3;
764     uint8_t event[len];
765     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
766     event[1] = len - 2;
767     event[2] = enabled;
768     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
769     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
770 }
771