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