xref: /btstack/src/hci.c (revision 7851196edd176ca0d2c15ea0ca8bde3181fdd7c3)
11f504dbdSmatthias.ringwald /*
26b64433eSmatthias.ringwald  * Copyright (C) 2009-2012 by Matthias Ringwald
31713bceaSmatthias.ringwald  *
41713bceaSmatthias.ringwald  * Redistribution and use in source and binary forms, with or without
51713bceaSmatthias.ringwald  * modification, are permitted provided that the following conditions
61713bceaSmatthias.ringwald  * are met:
71713bceaSmatthias.ringwald  *
81713bceaSmatthias.ringwald  * 1. Redistributions of source code must retain the above copyright
91713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer.
101713bceaSmatthias.ringwald  * 2. Redistributions in binary form must reproduce the above copyright
111713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer in the
121713bceaSmatthias.ringwald  *    documentation and/or other materials provided with the distribution.
131713bceaSmatthias.ringwald  * 3. Neither the name of the copyright holders nor the names of
141713bceaSmatthias.ringwald  *    contributors may be used to endorse or promote products derived
151713bceaSmatthias.ringwald  *    from this software without specific prior written permission.
166b64433eSmatthias.ringwald  * 4. Any redistribution, use, or modification is done solely for
176b64433eSmatthias.ringwald  *    personal benefit and not for any commercial purpose or for
186b64433eSmatthias.ringwald  *    monetary gain.
191713bceaSmatthias.ringwald  *
201713bceaSmatthias.ringwald  * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS
211713bceaSmatthias.ringwald  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
221713bceaSmatthias.ringwald  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
231713bceaSmatthias.ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
241713bceaSmatthias.ringwald  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
251713bceaSmatthias.ringwald  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
261713bceaSmatthias.ringwald  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
271713bceaSmatthias.ringwald  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
281713bceaSmatthias.ringwald  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
291713bceaSmatthias.ringwald  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
301713bceaSmatthias.ringwald  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311713bceaSmatthias.ringwald  * SUCH DAMAGE.
321713bceaSmatthias.ringwald  *
336b64433eSmatthias.ringwald  * Please inquire about commercial licensing options at [email protected]
346b64433eSmatthias.ringwald  *
351713bceaSmatthias.ringwald  */
361713bceaSmatthias.ringwald 
371713bceaSmatthias.ringwald /*
381f504dbdSmatthias.ringwald  *  hci.c
391f504dbdSmatthias.ringwald  *
401f504dbdSmatthias.ringwald  *  Created by Matthias Ringwald on 4/29/09.
411f504dbdSmatthias.ringwald  *
421f504dbdSmatthias.ringwald  */
431f504dbdSmatthias.ringwald 
44bde315ceS[email protected] #include "btstack-config.h"
4528171530Smatthias.ringwald 
467f2435e6Smatthias.ringwald #include "hci.h"
474c57c146S[email protected] #include "gap.h"
487f2435e6Smatthias.ringwald 
4993b8dc03Smatthias.ringwald #include <stdarg.h>
5093b8dc03Smatthias.ringwald #include <string.h>
5156fe0872Smatthias.ringwald #include <stdio.h>
527f2435e6Smatthias.ringwald 
53549e6ebeSmatthias.ringwald #ifndef EMBEDDED
54549e6ebeSmatthias.ringwald #include <unistd.h> // gethostbyname
5509ba8edeSmatthias.ringwald #include <btstack/version.h>
56549e6ebeSmatthias.ringwald #endif
57549e6ebeSmatthias.ringwald 
58a3b02b71Smatthias.ringwald #include "btstack_memory.h"
597f2435e6Smatthias.ringwald #include "debug.h"
60d8905019Smatthias.ringwald #include "hci_dump.h"
6193b8dc03Smatthias.ringwald 
62ae1fd9f3Smatthias.ringwald #include <btstack/hci_cmds.h>
631b0e3922Smatthias.ringwald 
64169f8b28Smatthias.ringwald #define HCI_CONNECTION_TIMEOUT_MS 10000
65ee091cf1Smatthias.ringwald 
66a45d6b9fS[email protected] #define HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP 11
67da5275c5S[email protected] 
6828171530Smatthias.ringwald #ifdef USE_BLUETOOL
6928171530Smatthias.ringwald #include "bt_control_iphone.h"
7028171530Smatthias.ringwald #endif
7128171530Smatthias.ringwald 
72758b46ceSmatthias.ringwald static void hci_update_scan_enable(void);
73a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
7496a45072S[email protected] static void hci_connection_timeout_handler(timer_source_t *timer);
7596a45072S[email protected] static void hci_connection_timestamp(hci_connection_t *connection);
76758b46ceSmatthias.ringwald 
7706b35ec0Smatthias.ringwald // the STACK is here
783a9fb326S[email protected] #ifndef HAVE_MALLOC
793a9fb326S[email protected] static hci_stack_t   hci_stack_static;
803a9fb326S[email protected] #endif
813a9fb326S[email protected] static hci_stack_t * hci_stack = NULL;
8216833f0aSmatthias.ringwald 
8366fb9560S[email protected] // test helper
8466fb9560S[email protected] static uint8_t disable_l2cap_timeouts = 0;
8566fb9560S[email protected] 
8696a45072S[email protected] /**
8796a45072S[email protected]  * create connection for given address
8896a45072S[email protected]  *
8996a45072S[email protected]  * @return connection OR NULL, if no memory left
9096a45072S[email protected]  */
9196a45072S[email protected] static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
9296a45072S[email protected] 
9396a45072S[email protected]     printf("create_connection_for_addr %s\n", bd_addr_to_str(addr));
9496a45072S[email protected]     hci_connection_t * conn = (hci_connection_t *) btstack_memory_hci_connection_get();
9596a45072S[email protected]     if (!conn) return NULL;
9696a45072S[email protected]     BD_ADDR_COPY(conn->address, addr);
9796a45072S[email protected]     conn->address_type = addr_type;
9896a45072S[email protected]     conn->con_handle = 0xffff;
9996a45072S[email protected]     conn->authentication_flags = AUTH_FLAGS_NONE;
10096a45072S[email protected]     conn->bonding_flags = 0;
10196a45072S[email protected]     conn->requested_security_level = LEVEL_0;
10296a45072S[email protected]     linked_item_set_user(&conn->timeout.item, conn);
10396a45072S[email protected]     conn->timeout.process = hci_connection_timeout_handler;
10496a45072S[email protected]     hci_connection_timestamp(conn);
10596a45072S[email protected]     conn->acl_recombination_length = 0;
10696a45072S[email protected]     conn->acl_recombination_pos = 0;
10796a45072S[email protected]     conn->num_acl_packets_sent = 0;
10896a45072S[email protected]     linked_list_add(&hci_stack->connections, (linked_item_t *) conn);
10996a45072S[email protected]     return conn;
11096a45072S[email protected] }
11166fb9560S[email protected] 
11297addcc5Smatthias.ringwald /**
113ee091cf1Smatthias.ringwald  * get connection for a given handle
114ee091cf1Smatthias.ringwald  *
115ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
116ee091cf1Smatthias.ringwald  */
1175061f3afS[email protected] hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
118ee091cf1Smatthias.ringwald     linked_item_t *it;
1193a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
120ee091cf1Smatthias.ringwald         if ( ((hci_connection_t *) it)->con_handle == con_handle){
121ee091cf1Smatthias.ringwald             return (hci_connection_t *) it;
122ee091cf1Smatthias.ringwald         }
123ee091cf1Smatthias.ringwald     }
124ee091cf1Smatthias.ringwald     return NULL;
125ee091cf1Smatthias.ringwald }
126ee091cf1Smatthias.ringwald 
12796a45072S[email protected] /**
12896a45072S[email protected]  * get connection for given address
12996a45072S[email protected]  *
13096a45072S[email protected]  * @return connection OR NULL, if not found
13196a45072S[email protected]  */
13296a45072S[email protected] hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t * addr, bd_addr_type_t addr_type){
13362bda3fbS[email protected]     linked_item_t *it;
13462bda3fbS[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
13562bda3fbS[email protected]         hci_connection_t * connection = (hci_connection_t *) it;
13696a45072S[email protected]         if (connection->address_type != addr_type)  continue;
13796a45072S[email protected]         if (memcmp(addr, connection->address, 6) != 0) continue;
13862bda3fbS[email protected]         return connection;
13962bda3fbS[email protected]     }
14062bda3fbS[email protected]     return NULL;
14162bda3fbS[email protected] }
14262bda3fbS[email protected] 
1432b12a0b9Smatthias.ringwald static void hci_connection_timeout_handler(timer_source_t *timer){
14428ca2b46S[email protected]     hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item);
145c785ef68Smatthias.ringwald #ifdef HAVE_TIME
146ee091cf1Smatthias.ringwald     struct timeval tv;
147ee091cf1Smatthias.ringwald     gettimeofday(&tv, NULL);
148c21e6239Smatthias.ringwald     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
149ee091cf1Smatthias.ringwald         // connections might be timed out
150ee091cf1Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
151ee091cf1Smatthias.ringwald     }
1522b12a0b9Smatthias.ringwald #endif
153e5780900Smatthias.ringwald #ifdef HAVE_TICK
154c785ef68Smatthias.ringwald     if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
155c785ef68Smatthias.ringwald         // connections might be timed out
156c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
157c785ef68Smatthias.ringwald     }
158c785ef68Smatthias.ringwald #endif
159c785ef68Smatthias.ringwald     run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
160c785ef68Smatthias.ringwald     run_loop_add_timer(timer);
161c785ef68Smatthias.ringwald }
162ee091cf1Smatthias.ringwald 
163ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
164c7492964Smatthias.ringwald #ifdef HAVE_TIME
165ee091cf1Smatthias.ringwald     gettimeofday(&connection->timestamp, NULL);
166c7492964Smatthias.ringwald #endif
167e5780900Smatthias.ringwald #ifdef HAVE_TICK
168c785ef68Smatthias.ringwald     connection->timestamp = embedded_get_ticks();
169c785ef68Smatthias.ringwald #endif
170ee091cf1Smatthias.ringwald }
171ee091cf1Smatthias.ringwald 
17206b35ec0Smatthias.ringwald 
17328ca2b46S[email protected] inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
17428ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
17528ca2b46S[email protected] }
17628ca2b46S[email protected] 
17728ca2b46S[email protected] inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
17828ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
17928ca2b46S[email protected] }
18028ca2b46S[email protected] 
18128ca2b46S[email protected] 
18243bfb1bdSmatthias.ringwald /**
18380ca58a0Smatthias.ringwald  * add authentication flags and reset timer
18496a45072S[email protected]  * @note: assumes classic connection
1857fde4af9Smatthias.ringwald  */
1867fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
1877fde4af9Smatthias.ringwald     bd_addr_t addr;
1887fde4af9Smatthias.ringwald     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
18996a45072S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1907fde4af9Smatthias.ringwald     if (conn) {
19128ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
19280ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
1937fde4af9Smatthias.ringwald     }
1947fde4af9Smatthias.ringwald }
1957fde4af9Smatthias.ringwald 
19680ca58a0Smatthias.ringwald int  hci_authentication_active_for_handle(hci_con_handle_t handle){
1975061f3afS[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
19880ca58a0Smatthias.ringwald     if (!conn) return 0;
1996724cd9eS[email protected]     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
2006724cd9eS[email protected]     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
2016724cd9eS[email protected]     return 0;
20280ca58a0Smatthias.ringwald }
20380ca58a0Smatthias.ringwald 
204c12e46e7Smatthias.ringwald void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
2053a9fb326S[email protected]     if (hci_stack->remote_device_db) {
2063a9fb326S[email protected]         hci_stack->remote_device_db->delete_link_key(addr);
207c12e46e7Smatthias.ringwald     }
208c12e46e7Smatthias.ringwald }
209c12e46e7Smatthias.ringwald 
2100bf6344aS[email protected] int hci_is_le_connection(hci_connection_t * connection){
2110bf6344aS[email protected]     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
2120bf6344aS[email protected]     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
2130bf6344aS[email protected] }
2140bf6344aS[email protected] 
2157fde4af9Smatthias.ringwald 
2167fde4af9Smatthias.ringwald /**
21743bfb1bdSmatthias.ringwald  * count connections
21843bfb1bdSmatthias.ringwald  */
21940d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
22056c253c9Smatthias.ringwald     int count = 0;
22143bfb1bdSmatthias.ringwald     linked_item_t *it;
2223a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
22343bfb1bdSmatthias.ringwald     return count;
22443bfb1bdSmatthias.ringwald }
225c8e4258aSmatthias.ringwald 
22697addcc5Smatthias.ringwald /**
227ba681a6cSmatthias.ringwald  * Dummy handler called by HCI
22816833f0aSmatthias.ringwald  */
2292718e2e7Smatthias.ringwald static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
23016833f0aSmatthias.ringwald }
23116833f0aSmatthias.ringwald 
232998906cdSmatthias.ringwald uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
2335061f3afS[email protected]     hci_connection_t * connection = hci_connection_for_handle(handle);
234998906cdSmatthias.ringwald     if (!connection) {
2357d67539fSmatthias.ringwald         log_error("hci_number_outgoing_packets connectino for handle %u does not exist!\n", handle);
236998906cdSmatthias.ringwald         return 0;
237998906cdSmatthias.ringwald     }
238998906cdSmatthias.ringwald     return connection->num_acl_packets_sent;
239998906cdSmatthias.ringwald }
240998906cdSmatthias.ringwald 
241998906cdSmatthias.ringwald uint8_t hci_number_free_acl_slots(){
2423a9fb326S[email protected]     uint8_t free_slots = hci_stack->total_num_acl_packets;
243998906cdSmatthias.ringwald     linked_item_t *it;
2443a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
245998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
246998906cdSmatthias.ringwald         if (free_slots < connection->num_acl_packets_sent) {
2477d67539fSmatthias.ringwald             log_error("hci_number_free_acl_slots: sum of outgoing packets > total acl packets!\n");
248998906cdSmatthias.ringwald             return 0;
249998906cdSmatthias.ringwald         }
250998906cdSmatthias.ringwald         free_slots -= connection->num_acl_packets_sent;
251998906cdSmatthias.ringwald     }
252998906cdSmatthias.ringwald     return free_slots;
253998906cdSmatthias.ringwald }
254998906cdSmatthias.ringwald 
255c24735b1Smatthias.ringwald int hci_can_send_packet_now(uint8_t packet_type){
2562b12a0b9Smatthias.ringwald 
2572b12a0b9Smatthias.ringwald     // check for async hci transport implementations
2583a9fb326S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
2593a9fb326S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(packet_type)){
2602b12a0b9Smatthias.ringwald             return 0;
2612b12a0b9Smatthias.ringwald         }
2622b12a0b9Smatthias.ringwald     }
2632b12a0b9Smatthias.ringwald 
2642b12a0b9Smatthias.ringwald     // check regular Bluetooth flow control
265c24735b1Smatthias.ringwald     switch (packet_type) {
266c24735b1Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
267c24735b1Smatthias.ringwald             return hci_number_free_acl_slots();
268c24735b1Smatthias.ringwald         case HCI_COMMAND_DATA_PACKET:
2693a9fb326S[email protected]             return hci_stack->num_cmd_packets;
270c24735b1Smatthias.ringwald         default:
271c24735b1Smatthias.ringwald             return 0;
272c24735b1Smatthias.ringwald     }
273c24735b1Smatthias.ringwald }
274c24735b1Smatthias.ringwald 
2756b4af23dS[email protected] // same as hci_can_send_packet_now, but also checks if packet buffer is free for use
2766b4af23dS[email protected] int hci_can_send_packet_now_using_packet_buffer(uint8_t packet_type){
2776b4af23dS[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
2786b4af23dS[email protected]     return hci_can_send_packet_now(packet_type);
2796b4af23dS[email protected] }
2806b4af23dS[email protected] 
281c8b9416aS[email protected] // used for internal checks in l2cap[-le].c
282c8b9416aS[email protected] int hci_is_packet_buffer_reserved(void){
283c8b9416aS[email protected]     return hci_stack->hci_packet_buffer_reserved;
284c8b9416aS[email protected] }
285c8b9416aS[email protected] 
2866b4af23dS[email protected] // reserves outgoing packet buffer. @returns 1 if successful
2876b4af23dS[email protected] int hci_reserve_packet_buffer(void){
2886b4af23dS[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
2896b4af23dS[email protected]     hci_stack->hci_packet_buffer_reserved = 1;
2906b4af23dS[email protected]     return 1;
2916b4af23dS[email protected] }
2926b4af23dS[email protected] 
29368a0fcf7S[email protected] void hci_release_packet_buffer(void){
29468a0fcf7S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
29568a0fcf7S[email protected] }
29668a0fcf7S[email protected] 
2976b4af23dS[email protected] // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
2986b4af23dS[email protected] int hci_transport_synchronous(void){
2996b4af23dS[email protected]     return hci_stack->hci_transport->can_send_packet_now == NULL;
3006b4af23dS[email protected] }
3016b4af23dS[email protected] 
302ee091cf1Smatthias.ringwald int hci_send_acl_packet(uint8_t *packet, int size){
3037856c818Smatthias.ringwald 
3046218e6f1Smatthias.ringwald     // check for free places on BT module
3055932f1b4Smatthias.ringwald     if (!hci_number_free_acl_slots()) return BTSTACK_ACL_BUFFERS_FULL;
3066218e6f1Smatthias.ringwald 
3077856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
3085061f3afS[email protected]     hci_connection_t *connection = hci_connection_for_handle( con_handle);
30956cf178bSmatthias.ringwald     if (!connection) return 0;
31056cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
31156cf178bSmatthias.ringwald 
31256cf178bSmatthias.ringwald     // count packet
31356cf178bSmatthias.ringwald     connection->num_acl_packets_sent++;
3147b5fbe1fSmatthias.ringwald     // log_info("hci_send_acl_packet - handle %u, sent %u\n", connection->con_handle, connection->num_acl_packets_sent);
3157856c818Smatthias.ringwald 
31600d8e42eSmatthias.ringwald     // send packet
3173a9fb326S[email protected]     int err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
3186218e6f1Smatthias.ringwald 
3196b4af23dS[email protected]     // free packet buffer for synchronous transport implementations
320c8b9416aS[email protected]     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
3216b4af23dS[email protected]         hci_stack->hci_packet_buffer_reserved = 0;
3226b4af23dS[email protected]     }
3236b4af23dS[email protected] 
32400d8e42eSmatthias.ringwald     return err;
325ee091cf1Smatthias.ringwald }
326ee091cf1Smatthias.ringwald 
32716833f0aSmatthias.ringwald static void acl_handler(uint8_t *packet, int size){
3287856c818Smatthias.ringwald 
329e76a89eeS[email protected]     // log_info("acl_handler: size %u", size);
330e76a89eeS[email protected] 
3317856c818Smatthias.ringwald     // get info
3327856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
3335061f3afS[email protected]     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
3347856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
3357856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
3367856c818Smatthias.ringwald 
3377856c818Smatthias.ringwald     // ignore non-registered handle
3387856c818Smatthias.ringwald     if (!conn){
3397d67539fSmatthias.ringwald         log_error( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle);
3407856c818Smatthias.ringwald         return;
3417856c818Smatthias.ringwald     }
3427856c818Smatthias.ringwald 
343e76a89eeS[email protected]     // assert packet is complete
3449ecc3e17S[email protected]     if (acl_length + 4 != size){
345e76a89eeS[email protected]         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
346e76a89eeS[email protected]         return;
347e76a89eeS[email protected]     }
348e76a89eeS[email protected] 
3497856c818Smatthias.ringwald     // update idle timestamp
3507856c818Smatthias.ringwald     hci_connection_timestamp(conn);
3517856c818Smatthias.ringwald 
3527856c818Smatthias.ringwald     // handle different packet types
3537856c818Smatthias.ringwald     switch (acl_flags & 0x03) {
3547856c818Smatthias.ringwald 
3557856c818Smatthias.ringwald         case 0x01: // continuation fragment
3567856c818Smatthias.ringwald 
3577856c818Smatthias.ringwald             // sanity check
3587856c818Smatthias.ringwald             if (conn->acl_recombination_pos == 0) {
3597d67539fSmatthias.ringwald                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle);
3607856c818Smatthias.ringwald                 return;
3617856c818Smatthias.ringwald             }
3627856c818Smatthias.ringwald 
3637856c818Smatthias.ringwald             // append fragment payload (header already stored)
3647856c818Smatthias.ringwald             memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length );
3657856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
3667856c818Smatthias.ringwald 
3677d67539fSmatthias.ringwald             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n", acl_length,
368decc01a8Smatthias.ringwald             //        conn->acl_recombination_pos, conn->acl_recombination_length);
3697856c818Smatthias.ringwald 
3707856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
3717856c818Smatthias.ringwald             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
3727856c818Smatthias.ringwald 
3733a9fb326S[email protected]                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos);
3747856c818Smatthias.ringwald                 // reset recombination buffer
3757856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
3767856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
3777856c818Smatthias.ringwald             }
3787856c818Smatthias.ringwald             break;
3797856c818Smatthias.ringwald 
3807856c818Smatthias.ringwald         case 0x02: { // first fragment
3817856c818Smatthias.ringwald 
3827856c818Smatthias.ringwald             // sanity check
3837856c818Smatthias.ringwald             if (conn->acl_recombination_pos) {
3847d67539fSmatthias.ringwald                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle);
3857856c818Smatthias.ringwald                 return;
3867856c818Smatthias.ringwald             }
3877856c818Smatthias.ringwald 
3887856c818Smatthias.ringwald             // peek into L2CAP packet!
3897856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
3907856c818Smatthias.ringwald 
391e76a89eeS[email protected]             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length);
392decc01a8Smatthias.ringwald 
3937856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
3947856c818Smatthias.ringwald             if (acl_length >= l2cap_length + 4){
3957856c818Smatthias.ringwald 
3967856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
3973a9fb326S[email protected]                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
3987856c818Smatthias.ringwald 
3997856c818Smatthias.ringwald             } else {
4007856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
4017856c818Smatthias.ringwald                 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4);
4027856c818Smatthias.ringwald                 conn->acl_recombination_pos    = acl_length + 4;
4037856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
404decc01a8Smatthias.ringwald                 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4);
4057856c818Smatthias.ringwald             }
4067856c818Smatthias.ringwald             break;
4077856c818Smatthias.ringwald 
4087856c818Smatthias.ringwald         }
4097856c818Smatthias.ringwald         default:
4107d67539fSmatthias.ringwald             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03);
4117856c818Smatthias.ringwald             return;
4127856c818Smatthias.ringwald     }
41394ab26f8Smatthias.ringwald 
41494ab26f8Smatthias.ringwald     // execute main loop
41594ab26f8Smatthias.ringwald     hci_run();
41616833f0aSmatthias.ringwald }
41722909952Smatthias.ringwald 
41867a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
419339b6768Smatthias.ringwald     log_info("Connection closed: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
4203c4d4b90Smatthias.ringwald 
421c7e0c5f6Smatthias.ringwald     run_loop_remove_timer(&conn->timeout);
422c785ef68Smatthias.ringwald 
4233a9fb326S[email protected]     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
424a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
4253c4d4b90Smatthias.ringwald 
4263c4d4b90Smatthias.ringwald     // now it's gone
427c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
428c7e0c5f6Smatthias.ringwald }
429c7e0c5f6Smatthias.ringwald 
4300c042179S[email protected] static const uint16_t packet_type_sizes[] = {
4318f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
4328f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
4338f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
4348f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
4358f8108aaSmatthias.ringwald };
43665389bfcS[email protected] static const uint8_t  packet_type_feature_requirement_bit[] = {
43765389bfcS[email protected]      0, // 3 slot packets
43865389bfcS[email protected]      1, // 5 slot packets
43965389bfcS[email protected]     25, // EDR 2 mpbs
44065389bfcS[email protected]     26, // EDR 3 mbps
44165389bfcS[email protected]     39, // 3 slot EDR packts
44265389bfcS[email protected]     40, // 5 slot EDR packet
44365389bfcS[email protected] };
44465389bfcS[email protected] static const uint16_t packet_type_feature_packet_mask[] = {
44565389bfcS[email protected]     0x0f00, // 3 slot packets
44665389bfcS[email protected]     0xf000, // 5 slot packets
44765389bfcS[email protected]     0x1102, // EDR 2 mpbs
44865389bfcS[email protected]     0x2204, // EDR 3 mbps
44965389bfcS[email protected]     0x0300, // 3 slot EDR packts
45065389bfcS[email protected]     0x3000, // 5 slot EDR packet
45165389bfcS[email protected] };
4528f8108aaSmatthias.ringwald 
45365389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
45465389bfcS[email protected]     // enable packet types based on size
4558f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
4568f8108aaSmatthias.ringwald     int i;
4578f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
4588f8108aaSmatthias.ringwald         if (packet_type_sizes[i] == 0) continue;
4598f8108aaSmatthias.ringwald         if (packet_type_sizes[i] <= buffer_size){
4608f8108aaSmatthias.ringwald             packet_types |= 1 << i;
4618f8108aaSmatthias.ringwald         }
4628f8108aaSmatthias.ringwald     }
46365389bfcS[email protected]     // disable packet types due to missing local supported features
46465389bfcS[email protected]     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
46565389bfcS[email protected]         int bit_idx = packet_type_feature_requirement_bit[i];
46665389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
46765389bfcS[email protected]         if (feature_set) continue;
46865389bfcS[email protected]         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
46965389bfcS[email protected]         packet_types &= ~packet_type_feature_packet_mask[i];
47065389bfcS[email protected]     }
4718f8108aaSmatthias.ringwald     // flip bits for "may not be used"
4728f8108aaSmatthias.ringwald     packet_types ^= 0x3306;
4738f8108aaSmatthias.ringwald     return packet_types;
4748f8108aaSmatthias.ringwald }
4758f8108aaSmatthias.ringwald 
4768f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
4773a9fb326S[email protected]     return hci_stack->packet_types;
4788f8108aaSmatthias.ringwald }
4798f8108aaSmatthias.ringwald 
480facf93fdS[email protected] uint8_t* hci_get_outgoing_packet_buffer(void){
4817dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
4823a9fb326S[email protected]     return hci_stack->hci_packet_buffer;
4837dc17943Smatthias.ringwald }
4847dc17943Smatthias.ringwald 
485f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
4863a9fb326S[email protected]     return hci_stack->acl_data_packet_length;
4877dc17943Smatthias.ringwald }
4887dc17943Smatthias.ringwald 
4896ac9a97eS[email protected] int hci_non_flushable_packet_boundary_flag_supported(void){
4906ac9a97eS[email protected]     // No. 54, byte 6, bit 6
4916ac9a97eS[email protected]     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
4926ac9a97eS[email protected] }
4936ac9a97eS[email protected] 
494f5d8d141S[email protected] int hci_ssp_supported(void){
4956ac9a97eS[email protected]     // No. 51, byte 6, bit 3
4963a9fb326S[email protected]     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
497f5d8d141S[email protected] }
498f5d8d141S[email protected] 
499f5d8d141S[email protected] int hci_classic_supported(void){
5006ac9a97eS[email protected]     // No. 37, byte 4, bit 5, = No BR/EDR Support
5013a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
502f5d8d141S[email protected] }
503f5d8d141S[email protected] 
504f5d8d141S[email protected] int hci_le_supported(void){
505f5d8d141S[email protected] #ifdef HAVE_BLE
5066ac9a97eS[email protected]     // No. 37, byte 4, bit 6 = LE Supported (Controller)
5073a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
508f5d8d141S[email protected] #else
509f5d8d141S[email protected]     return 0;
510f5d8d141S[email protected] #endif
511f5d8d141S[email protected] }
512f5d8d141S[email protected] 
51369a97523S[email protected] // get addr type and address used in advertisement packets
51418904abdS[email protected] void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){
5153a9fb326S[email protected]     *addr_type = hci_stack->adv_addr_type;
5163a9fb326S[email protected]     if (hci_stack->adv_addr_type){
5173a9fb326S[email protected]         memcpy(addr, hci_stack->adv_address, 6);
51869a97523S[email protected]     } else {
5193a9fb326S[email protected]         memcpy(addr, hci_stack->local_bd_addr, 6);
52069a97523S[email protected]     }
52169a97523S[email protected] }
52269a97523S[email protected] 
523b2f949feS[email protected] #ifdef HAVE_BLE
52457c9da5bS[email protected] static void le_handle_advertisement_report(uint8_t *packet, int size){
52557c9da5bS[email protected]     int num_reports = packet[3];
52657c9da5bS[email protected]     int i;
52757c9da5bS[email protected]     int total_data_length = 0;
52857c9da5bS[email protected]     int data_offset = 0;
52957c9da5bS[email protected] 
53057c9da5bS[email protected]     for (i=0; i<num_reports;i++){
53157c9da5bS[email protected]         total_data_length += packet[4+num_reports*8+i];
53257c9da5bS[email protected]     }
53357c9da5bS[email protected] 
53457c9da5bS[email protected]     for (i=0; i<num_reports;i++){
53557c9da5bS[email protected]         int pos = 0;
53657c9da5bS[email protected]         uint8_t data_length = packet[4+num_reports*8+i];
5372b552b23S[email protected]         uint8_t event_size = 10 + data_length;
5382b552b23S[email protected]         uint8_t event[2 + event_size ];
5392b552b23S[email protected]         event[pos++] = GAP_LE_ADVERTISING_REPORT;
54057c9da5bS[email protected]         event[pos++] = event_size;
54157c9da5bS[email protected]         event[pos++] = packet[4+i]; // event_type;
54257c9da5bS[email protected]         event[pos++] = packet[4+num_reports+i]; // address_type;
543564fca32S[email protected]         memcpy(&event[pos], &packet[4+num_reports*2+i*6], 6); // bt address
54457c9da5bS[email protected]         pos += 6;
5452b552b23S[email protected]         event[pos++] = packet[4+num_reports*9+total_data_length + i];
54657c9da5bS[email protected]         event[pos++] = data_length;
54788ed79cfS[email protected]         memcpy(&event[pos], &packet[4+num_reports*9+data_offset], data_length);
54857c9da5bS[email protected]         data_offset += data_length;
54957c9da5bS[email protected]         pos += data_length;
55057c9da5bS[email protected]         hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
55157c9da5bS[email protected]     }
55257c9da5bS[email protected] }
553b2f949feS[email protected] #endif
55457c9da5bS[email protected] 
55574ec757aSmatthias.ringwald // avoid huge local variables
556223aafc1Smatthias.ringwald #ifndef EMBEDDED
55774ec757aSmatthias.ringwald static device_name_t device_name;
558223aafc1Smatthias.ringwald #endif
55916833f0aSmatthias.ringwald static void event_handler(uint8_t *packet, int size){
560e76a89eeS[email protected] 
561e76a89eeS[email protected]     uint16_t event_length = packet[1];
562e76a89eeS[email protected] 
563e76a89eeS[email protected]     // assert packet is complete
564e76a89eeS[email protected]     if (size != event_length + 2){
565e76a89eeS[email protected]         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
566e76a89eeS[email protected]         return;
567e76a89eeS[email protected]     }
568e76a89eeS[email protected] 
5691281a47eSmatthias.ringwald     bd_addr_t addr;
57096a45072S[email protected]     bd_addr_type_t addr_type;
5712d00edd4Smatthias.ringwald     uint8_t link_type;
572fe1ed1b8Smatthias.ringwald     hci_con_handle_t handle;
5731f7b95a1Smatthias.ringwald     hci_connection_t * conn;
57456cf178bSmatthias.ringwald     int i;
57522909952Smatthias.ringwald 
5765909f7f2Smatthias.ringwald     // printf("HCI:EVENT:%02x\n", packet[0]);
5775909f7f2Smatthias.ringwald 
5786772a24cSmatthias.ringwald     switch (packet[0]) {
57922909952Smatthias.ringwald 
5806772a24cSmatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
5817ec5eeaaSmatthias.ringwald             // get num cmd packets
5823a9fb326S[email protected]             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u\n", hci_stack->num_cmd_packets, packet[2]);
5833a9fb326S[email protected]             hci_stack->num_cmd_packets = packet[2];
5847ec5eeaaSmatthias.ringwald 
585e2edc0c3Smatthias.ringwald             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
586e2edc0c3Smatthias.ringwald                 // from offset 5
587e2edc0c3Smatthias.ringwald                 // status
5881d279b20Smatthias.ringwald                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
5893a9fb326S[email protected]                 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6);
59056cf178bSmatthias.ringwald                 // ignore: SCO data packet len (8)
5913a9fb326S[email protected]                 hci_stack->total_num_acl_packets  = packet[9];
59256cf178bSmatthias.ringwald                 // ignore: total num SCO packets
5933a9fb326S[email protected]                 if (hci_stack->state == HCI_STATE_INITIALIZING){
594a7a04bd9Smatthias.ringwald                     // determine usable ACL payload size
5953a9fb326S[email protected]                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
5963a9fb326S[email protected]                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
5978f8108aaSmatthias.ringwald                     }
59865389bfcS[email protected]                     log_info("hci_read_buffer_size: used size %u, count %u\n",
5993a9fb326S[email protected]                              hci_stack->acl_data_packet_length, hci_stack->total_num_acl_packets);
600e2edc0c3Smatthias.ringwald                 }
60156cf178bSmatthias.ringwald             }
60265a46ef3S[email protected] #ifdef HAVE_BLE
60365a46ef3S[email protected]             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){
6043a9fb326S[email protected]                 hci_stack->le_data_packet_length = READ_BT_16(packet, 6);
6053a9fb326S[email protected]                 hci_stack->total_num_le_packets  = packet[8];
6063a9fb326S[email protected]                 log_info("hci_le_read_buffer_size: size %u, count %u\n", hci_stack->le_data_packet_length, hci_stack->total_num_le_packets);
60701f1657cS[email protected] 
60801f1657cS[email protected]                 // use LE buffers if no clasic buffers have been reported
60901f1657cS[email protected]                 if (hci_stack->total_num_acl_packets == 0){
61001f1657cS[email protected]                     log_info("use le buffers instead of classic ones");
61101f1657cS[email protected]                     hci_stack->total_num_acl_packets  = hci_stack->total_num_le_packets;
61201f1657cS[email protected]                     hci_stack->acl_data_packet_length = hci_stack->le_data_packet_length;
61301f1657cS[email protected]                     // determine usable ACL payload size
61401f1657cS[email protected]                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
61501f1657cS[email protected]                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
61601f1657cS[email protected]                     }
61701f1657cS[email protected]                 }
61865a46ef3S[email protected]             }
61965a46ef3S[email protected] #endif
620188981d2Smatthias.ringwald             // Dump local address
621188981d2Smatthias.ringwald             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
6223a9fb326S[email protected]                 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
623188981d2Smatthias.ringwald                 log_info("Local Address, Status: 0x%02x: Addr: %s\n",
6243a9fb326S[email protected]                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
625188981d2Smatthias.ringwald             }
626381fbed8Smatthias.ringwald             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
6273a9fb326S[email protected]                 hci_emit_discoverable_enabled(hci_stack->discoverable);
628381fbed8Smatthias.ringwald             }
62965389bfcS[email protected]             // Note: HCI init checks
630559e517eS[email protected]             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
6313a9fb326S[email protected]                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
632559e517eS[email protected]                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
6333a9fb326S[email protected]                     hci_stack->local_supported_features[0], hci_stack->local_supported_features[1],
6343a9fb326S[email protected]                     hci_stack->local_supported_features[2], hci_stack->local_supported_features[3],
6353a9fb326S[email protected]                     hci_stack->local_supported_features[4], hci_stack->local_supported_features[5],
6363a9fb326S[email protected]                     hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]);
63765389bfcS[email protected] 
63865389bfcS[email protected]                 // determine usable ACL packet types based buffer size and supported features
6393a9fb326S[email protected]                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(hci_stack->acl_data_packet_length, &hci_stack->local_supported_features[0]);
6403a9fb326S[email protected]                 log_info("packet types %04x", hci_stack->packet_types);
641f5d8d141S[email protected] 
642f5d8d141S[email protected]                 // Classic/LE
643f5d8d141S[email protected]                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
644559e517eS[email protected]             }
64556cf178bSmatthias.ringwald             break;
64656cf178bSmatthias.ringwald 
6477ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
6487ec5eeaaSmatthias.ringwald             // get num cmd packets
6493a9fb326S[email protected]             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u\n", hci_stack->num_cmd_packets, packet[3]);
6503a9fb326S[email protected]             hci_stack->num_cmd_packets = packet[3];
6517ec5eeaaSmatthias.ringwald             break;
6527ec5eeaaSmatthias.ringwald 
65356cf178bSmatthias.ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
65456cf178bSmatthias.ringwald             for (i=0; i<packet[2];i++){
65556cf178bSmatthias.ringwald                 handle = READ_BT_16(packet, 3 + 2*i);
65656cf178bSmatthias.ringwald                 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i);
6575061f3afS[email protected]                 conn = hci_connection_for_handle(handle);
65856cf178bSmatthias.ringwald                 if (!conn){
6597d67539fSmatthias.ringwald                     log_error("hci_number_completed_packet lists unused con handle %u\n", handle);
66056cf178bSmatthias.ringwald                     continue;
66156cf178bSmatthias.ringwald                 }
66256cf178bSmatthias.ringwald                 conn->num_acl_packets_sent -= num_packets;
6637b5fbe1fSmatthias.ringwald                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent);
66456cf178bSmatthias.ringwald             }
6656772a24cSmatthias.ringwald             break;
6666772a24cSmatthias.ringwald 
6671f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
66837eaa4cfSmatthias.ringwald             bt_flip_addr(addr, &packet[2]);
66937eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
6702d00edd4Smatthias.ringwald             link_type = packet[11];
671339b6768Smatthias.ringwald             log_info("Connection_incoming: %s, type %u\n", bd_addr_to_str(addr), link_type);
67237eaa4cfSmatthias.ringwald             if (link_type == 1) { // ACL
67396a45072S[email protected]                 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
6741f7b95a1Smatthias.ringwald                 if (!conn) {
67596a45072S[email protected]                     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
6761f7b95a1Smatthias.ringwald                 }
677ce4c8fabSmatthias.ringwald                 if (!conn) {
678ce4c8fabSmatthias.ringwald                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
6793a9fb326S[email protected]                     hci_stack->decline_reason = 0x0d;
6803a9fb326S[email protected]                     BD_ADDR_COPY(hci_stack->decline_addr, addr);
681ce4c8fabSmatthias.ringwald                     break;
682ce4c8fabSmatthias.ringwald                 }
68332ab9390Smatthias.ringwald                 conn->state = RECEIVED_CONNECTION_REQUEST;
68432ab9390Smatthias.ringwald                 hci_run();
68537eaa4cfSmatthias.ringwald             } else {
686ce4c8fabSmatthias.ringwald                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
6873a9fb326S[email protected]                 hci_stack->decline_reason = 0x0a;
6883a9fb326S[email protected]                 BD_ADDR_COPY(hci_stack->decline_addr, addr);
68937eaa4cfSmatthias.ringwald             }
6901f7b95a1Smatthias.ringwald             break;
6911f7b95a1Smatthias.ringwald 
6926772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
693fe1ed1b8Smatthias.ringwald             // Connection management
694fe1ed1b8Smatthias.ringwald             bt_flip_addr(addr, &packet[5]);
695339b6768Smatthias.ringwald             log_info("Connection_complete (status=%u) %s\n", packet[2], bd_addr_to_str(addr));
69696a45072S[email protected]             addr_type = BD_ADDR_TYPE_CLASSIC;
69796a45072S[email protected]             conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
698fe1ed1b8Smatthias.ringwald             if (conn) {
699b448a0e7Smatthias.ringwald                 if (!packet[2]){
700c8e4258aSmatthias.ringwald                     conn->state = OPEN;
701fe1ed1b8Smatthias.ringwald                     conn->con_handle = READ_BT_16(packet, 3);
702ad83dc6aS[email protected]                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
703ee091cf1Smatthias.ringwald 
704c785ef68Smatthias.ringwald                     // restart timer
705c21e6239Smatthias.ringwald                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
706ee091cf1Smatthias.ringwald                     run_loop_add_timer(&conn->timeout);
707c785ef68Smatthias.ringwald 
708339b6768Smatthias.ringwald                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
70943bfb1bdSmatthias.ringwald 
71043bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
711b448a0e7Smatthias.ringwald                 } else {
712ad83dc6aS[email protected]                     // notify client if dedicated bonding
713ad83dc6aS[email protected]                     if (conn->bonding_flags & BONDING_DEDICATED){
714ad83dc6aS[email protected]                         hci_emit_dedicated_bonding_result(conn, packet[2]);
715ad83dc6aS[email protected]                     }
716ad83dc6aS[email protected] 
717b448a0e7Smatthias.ringwald                     // connection failed, remove entry
7183a9fb326S[email protected]                     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
719a3b02b71Smatthias.ringwald                     btstack_memory_hci_connection_free( conn );
720c12e46e7Smatthias.ringwald 
721c12e46e7Smatthias.ringwald                     // if authentication error, also delete link key
722c12e46e7Smatthias.ringwald                     if (packet[2] == 0x05) {
723c12e46e7Smatthias.ringwald                         hci_drop_link_key_for_bd_addr(&addr);
724c12e46e7Smatthias.ringwald                     }
725fe1ed1b8Smatthias.ringwald                 }
726fe1ed1b8Smatthias.ringwald             }
7276772a24cSmatthias.ringwald             break;
728fe1ed1b8Smatthias.ringwald 
729afd4e962S[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
730afd4e962S[email protected]             handle = READ_BT_16(packet, 3);
731afd4e962S[email protected]             conn = hci_connection_for_handle(handle);
732afd4e962S[email protected]             if (!conn) break;
733afd4e962S[email protected]             if (!packet[2]){
734afd4e962S[email protected]                 uint8_t * features = &packet[5];
735afd4e962S[email protected]                 if (features[6] & (1 << 3)){
736afd4e962S[email protected]                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
737afd4e962S[email protected]                 }
738afd4e962S[email protected]             }
739afd4e962S[email protected]             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
740ad83dc6aS[email protected]             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags);
741ad83dc6aS[email protected]             if (conn->bonding_flags & BONDING_DEDICATED){
742ad83dc6aS[email protected]                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
743ad83dc6aS[email protected]             }
744afd4e962S[email protected]             break;
745afd4e962S[email protected] 
7467fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
7477b5fbe1fSmatthias.ringwald             log_info("HCI_EVENT_LINK_KEY_REQUEST\n");
7487fde4af9Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
74974d716b5S[email protected]             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
7503a9fb326S[email protected]             if (hci_stack->bondable && !hci_stack->remote_device_db) break;
75132ab9390Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
75264472d52Smatthias.ringwald             hci_run();
753d9a327f9Smatthias.ringwald             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
75429d53098Smatthias.ringwald             return;
7557fde4af9Smatthias.ringwald 
7569ab95c90S[email protected]         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
75729d53098Smatthias.ringwald             bt_flip_addr(addr, &packet[2]);
75896a45072S[email protected]             conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
7599ab95c90S[email protected]             if (!conn) break;
7609ab95c90S[email protected]             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
7617bdc6798S[email protected]             link_key_type_t link_key_type = (link_key_type_t)packet[24];
7629ab95c90S[email protected]             // Change Connection Encryption keeps link key type
7639ab95c90S[email protected]             if (link_key_type != CHANGED_COMBINATION_KEY){
7649ab95c90S[email protected]                 conn->link_key_type = link_key_type;
7659ab95c90S[email protected]             }
7663a9fb326S[email protected]             if (!hci_stack->remote_device_db) break;
7673a9fb326S[email protected]             hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type);
76829d53098Smatthias.ringwald             // still forward event to allow dismiss of pairing dialog
7697fde4af9Smatthias.ringwald             break;
7709ab95c90S[email protected]         }
7717fde4af9Smatthias.ringwald 
7727fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
7736724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
7744c57c146S[email protected]             // non-bondable mode: pin code negative reply will be sent
7753a9fb326S[email protected]             if (!hci_stack->bondable){
776899283eaS[email protected]                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
777f8fb5f6eS[email protected]                 hci_run();
778f8fb5f6eS[email protected]                 return;
7794c57c146S[email protected]             }
780d9a327f9Smatthias.ringwald             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
7813a9fb326S[email protected]             if (!hci_stack->remote_device_db) break;
782d9a327f9Smatthias.ringwald             bt_flip_addr(addr, &packet[2]);
7833a9fb326S[email protected]             hci_stack->remote_device_db->delete_link_key(&addr);
7847fde4af9Smatthias.ringwald             break;
7857fde4af9Smatthias.ringwald 
7861d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
7871d6b20aeS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
788dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
789dbe1a790S[email protected]             break;
790dbe1a790S[email protected] 
791dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
7926724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
7933a9fb326S[email protected]             if (!hci_stack->ssp_auto_accept) break;
794dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
795dbe1a790S[email protected]             break;
796dbe1a790S[email protected] 
797dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
7986724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
7993a9fb326S[email protected]             if (!hci_stack->ssp_auto_accept) break;
800dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
8011d6b20aeS[email protected]             break;
8021d6b20aeS[email protected] 
803f0944df2S[email protected]         case HCI_EVENT_ENCRYPTION_CHANGE:
804f0944df2S[email protected]             handle = READ_BT_16(packet, 3);
805f0944df2S[email protected]             conn = hci_connection_for_handle(handle);
806f0944df2S[email protected]             if (!conn) break;
807ad83dc6aS[email protected]             if (packet[2] == 0) {
808f0944df2S[email protected]                 if (packet[5]){
809f0944df2S[email protected]                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
810f0944df2S[email protected]                 } else {
811536f9994S[email protected]                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
812f0944df2S[email protected]                 }
813ad83dc6aS[email protected]             }
814a00031e2S[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
815f0944df2S[email protected]             break;
816f0944df2S[email protected] 
8171eb2563eS[email protected]         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
8181eb2563eS[email protected]             handle = READ_BT_16(packet, 3);
8191eb2563eS[email protected]             conn = hci_connection_for_handle(handle);
8201eb2563eS[email protected]             if (!conn) break;
821ad83dc6aS[email protected] 
822ad83dc6aS[email protected]             // dedicated bonding: send result and disconnect
823ad83dc6aS[email protected]             if (conn->bonding_flags & BONDING_DEDICATED){
824ad83dc6aS[email protected]                 conn->bonding_flags &= ~BONDING_DEDICATED;
825ad83dc6aS[email protected]                 hci_emit_dedicated_bonding_result( conn, packet[2]);
826ad83dc6aS[email protected]                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
827ad83dc6aS[email protected]                 break;
828ad83dc6aS[email protected]             }
829ad83dc6aS[email protected] 
830b5cb6874S[email protected]             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
8311eb2563eS[email protected]                 // link key sufficient for requested security
8321eb2563eS[email protected]                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
833ad83dc6aS[email protected]                 break;
834ad83dc6aS[email protected]             }
8351eb2563eS[email protected]             // not enough
8361eb2563eS[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
8371eb2563eS[email protected]             break;
83834d2123cS[email protected] 
839223aafc1Smatthias.ringwald #ifndef EMBEDDED
84074ec757aSmatthias.ringwald         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
8413a9fb326S[email protected]             if (!hci_stack->remote_device_db) break;
84274ec757aSmatthias.ringwald             if (packet[2]) break; // status not ok
84374ec757aSmatthias.ringwald             bt_flip_addr(addr, &packet[3]);
8445a06394aSmatthias.ringwald             // fix for invalid remote names - terminate on 0xff
8455a06394aSmatthias.ringwald             for (i=0; i<248;i++){
8465a06394aSmatthias.ringwald                 if (packet[9+i] == 0xff){
8475a06394aSmatthias.ringwald                     packet[9+i] = 0;
8485a06394aSmatthias.ringwald                     break;
849cdc9101dSmatthias.ringwald                 }
8505a06394aSmatthias.ringwald             }
851d2fe945cS[email protected]             memset(&device_name, 0, sizeof(device_name_t));
85274ec757aSmatthias.ringwald             strncpy((char*) device_name, (char*) &packet[9], 248);
8533a9fb326S[email protected]             hci_stack->remote_device_db->put_name(&addr, &device_name);
85474ec757aSmatthias.ringwald             break;
85574ec757aSmatthias.ringwald 
85674ec757aSmatthias.ringwald         case HCI_EVENT_INQUIRY_RESULT:
85774ec757aSmatthias.ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
8583a9fb326S[email protected]             if (!hci_stack->remote_device_db) break;
85974ec757aSmatthias.ringwald             // first send inq result packet
8603a9fb326S[email protected]             hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
86174ec757aSmatthias.ringwald             // then send cached remote names
86274ec757aSmatthias.ringwald             for (i=0; i<packet[2];i++){
86374ec757aSmatthias.ringwald                 bt_flip_addr(addr, &packet[3+i*6]);
8643a9fb326S[email protected]                 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){
86574ec757aSmatthias.ringwald                     hci_emit_remote_name_cached(&addr, &device_name);
86674ec757aSmatthias.ringwald                 }
86774ec757aSmatthias.ringwald             }
86874ec757aSmatthias.ringwald             return;
869223aafc1Smatthias.ringwald #endif
87074ec757aSmatthias.ringwald 
8716772a24cSmatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
872fe1ed1b8Smatthias.ringwald             if (!packet[2]){
873fe1ed1b8Smatthias.ringwald                 handle = READ_BT_16(packet, 3);
8745061f3afS[email protected]                 hci_connection_t * conn = hci_connection_for_handle(handle);
875fe1ed1b8Smatthias.ringwald                 if (conn) {
876c7e0c5f6Smatthias.ringwald                     hci_shutdown_connection(conn);
877fe1ed1b8Smatthias.ringwald                 }
878fe1ed1b8Smatthias.ringwald             }
8796772a24cSmatthias.ringwald             break;
8806772a24cSmatthias.ringwald 
881c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
8823a9fb326S[email protected]             if(hci_stack->control && hci_stack->control->hw_error){
8833a9fb326S[email protected]                 (*hci_stack->control->hw_error)();
884c68bdf90Smatthias.ringwald             }
885c68bdf90Smatthias.ringwald             break;
886c68bdf90Smatthias.ringwald 
8876b4af23dS[email protected]         case DAEMON_EVENT_HCI_PACKET_SENT:
8886b4af23dS[email protected]             // free packet buffer for asynchronous transport
8896b4af23dS[email protected]             if (hci_transport_synchronous()) break;
8906b4af23dS[email protected]             hci_stack->hci_packet_buffer_reserved = 0;
8916b4af23dS[email protected]             break;
8926b4af23dS[email protected] 
8935909f7f2Smatthias.ringwald #ifdef HAVE_BLE
8945909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
8955909f7f2Smatthias.ringwald             switch (packet[2]){
89657c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
8977bdc6798S[email protected]                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
89857c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
8997bdc6798S[email protected]                     break;
9005909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
9015909f7f2Smatthias.ringwald                     // Connection management
9025909f7f2Smatthias.ringwald                     bt_flip_addr(addr, &packet[8]);
9037bdc6798S[email protected]                     addr_type = (bd_addr_type_t)packet[7];
90496a45072S[email protected]                     log_info("LE Connection_complete (status=%u) type %u, %s\n", packet[3], addr_type, bd_addr_to_str(addr));
9055909f7f2Smatthias.ringwald                     // LE connections are auto-accepted, so just create a connection if there isn't one already
90696a45072S[email protected]                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
9075909f7f2Smatthias.ringwald                     if (packet[3]){
9085909f7f2Smatthias.ringwald                         if (conn){
9095909f7f2Smatthias.ringwald                             // outgoing connection failed, remove entry
9103a9fb326S[email protected]                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
9115909f7f2Smatthias.ringwald                             btstack_memory_hci_connection_free( conn );
9125909f7f2Smatthias.ringwald                         }
9135909f7f2Smatthias.ringwald                         // if authentication error, also delete link key
9145909f7f2Smatthias.ringwald                         if (packet[3] == 0x05) {
9155909f7f2Smatthias.ringwald                             hci_drop_link_key_for_bd_addr(&addr);
9165909f7f2Smatthias.ringwald                         }
9175909f7f2Smatthias.ringwald                         break;
9185909f7f2Smatthias.ringwald                     }
9195909f7f2Smatthias.ringwald                     if (!conn){
92096a45072S[email protected]                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
9215909f7f2Smatthias.ringwald                     }
9225909f7f2Smatthias.ringwald                     if (!conn){
9235909f7f2Smatthias.ringwald                         // no memory
9245909f7f2Smatthias.ringwald                         break;
9255909f7f2Smatthias.ringwald                     }
9265909f7f2Smatthias.ringwald 
9275909f7f2Smatthias.ringwald                     conn->state = OPEN;
9285909f7f2Smatthias.ringwald                     conn->con_handle = READ_BT_16(packet, 4);
9295909f7f2Smatthias.ringwald 
9305909f7f2Smatthias.ringwald                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
9315909f7f2Smatthias.ringwald 
9325909f7f2Smatthias.ringwald                     // restart timer
9335909f7f2Smatthias.ringwald                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
9345909f7f2Smatthias.ringwald                     // run_loop_add_timer(&conn->timeout);
9355909f7f2Smatthias.ringwald 
9365909f7f2Smatthias.ringwald                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
9375909f7f2Smatthias.ringwald 
9385909f7f2Smatthias.ringwald                     hci_emit_nr_connections_changed();
9395909f7f2Smatthias.ringwald                     break;
9405909f7f2Smatthias.ringwald 
94165a46ef3S[email protected]             // printf("LE buffer size: %u, count %u\n", READ_BT_16(packet,6), packet[8]);
94265a46ef3S[email protected] 
9435909f7f2Smatthias.ringwald                 default:
9445909f7f2Smatthias.ringwald                     break;
9455909f7f2Smatthias.ringwald             }
9465909f7f2Smatthias.ringwald             break;
9475909f7f2Smatthias.ringwald #endif
9485909f7f2Smatthias.ringwald 
9496772a24cSmatthias.ringwald         default:
9506772a24cSmatthias.ringwald             break;
951fe1ed1b8Smatthias.ringwald     }
952fe1ed1b8Smatthias.ringwald 
9533429f56bSmatthias.ringwald     // handle BT initialization
9543a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_INITIALIZING){
9553a9fb326S[email protected]         if (hci_stack->substate % 2){
9563429f56bSmatthias.ringwald             // odd: waiting for event
957f155fca3Smatthias.ringwald             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){
958c9af4d3fS[email protected]                 // wait for explicit COMMAND COMPLETE on RESET
9593a9fb326S[email protected]                 if (hci_stack->substate > 1 || COMMAND_COMPLETE_EVENT(packet, hci_reset)) {
9603a9fb326S[email protected]                     hci_stack->substate++;
9613429f56bSmatthias.ringwald                 }
9623429f56bSmatthias.ringwald             }
96322909952Smatthias.ringwald         }
964c9af4d3fS[email protected]     }
96522909952Smatthias.ringwald 
96689db417bSmatthias.ringwald     // help with BT sleep
9673a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
9683a9fb326S[email protected]         && hci_stack->substate == 1
96989db417bSmatthias.ringwald         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
9703a9fb326S[email protected]         hci_stack->substate++;
97189db417bSmatthias.ringwald     }
97289db417bSmatthias.ringwald 
9733a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
97494ab26f8Smatthias.ringwald 
97594ab26f8Smatthias.ringwald 	// execute main loop
97694ab26f8Smatthias.ringwald 	hci_run();
97716833f0aSmatthias.ringwald }
97816833f0aSmatthias.ringwald 
9790a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
98010e830c9Smatthias.ringwald     switch (packet_type) {
98110e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
98210e830c9Smatthias.ringwald             event_handler(packet, size);
98310e830c9Smatthias.ringwald             break;
98410e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
98510e830c9Smatthias.ringwald             acl_handler(packet, size);
98610e830c9Smatthias.ringwald             break;
98710e830c9Smatthias.ringwald         default:
98810e830c9Smatthias.ringwald             break;
98910e830c9Smatthias.ringwald     }
99010e830c9Smatthias.ringwald }
99110e830c9Smatthias.ringwald 
992fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
9932718e2e7Smatthias.ringwald void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
9943a9fb326S[email protected]     hci_stack->packet_handler = handler;
99516833f0aSmatthias.ringwald }
99616833f0aSmatthias.ringwald 
997595bdbfbS[email protected] void hci_state_reset(){
998595bdbfbS[email protected]     // no connections yet
999595bdbfbS[email protected]     hci_stack->connections = NULL;
1000595bdbfbS[email protected]     hci_stack->discoverable = 0;
1001595bdbfbS[email protected]     hci_stack->connectable = 0;
1002595bdbfbS[email protected]     hci_stack->bondable = 1;
1003595bdbfbS[email protected] 
1004595bdbfbS[email protected]     // no pending cmds
1005595bdbfbS[email protected]     hci_stack->decline_reason = 0;
1006595bdbfbS[email protected]     hci_stack->new_scan_enable_value = 0xff;
1007595bdbfbS[email protected] 
1008595bdbfbS[email protected]     // LE
1009595bdbfbS[email protected]     hci_stack->adv_addr_type = 0;
1010595bdbfbS[email protected]     memset(hci_stack->adv_address, 0, 6);
1011595bdbfbS[email protected]     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1012595bdbfbS[email protected] }
1013595bdbfbS[email protected] 
10144f4fc1dfSmatthias.ringwald void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
1015475c8125Smatthias.ringwald 
10163a9fb326S[email protected] #ifdef HAVE_MALLOC
10173a9fb326S[email protected]     if (!hci_stack) {
10183a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
10193a9fb326S[email protected]     }
10203a9fb326S[email protected] #else
10213a9fb326S[email protected]     hci_stack = &hci_stack_static;
10223a9fb326S[email protected] #endif
102366fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
10243a9fb326S[email protected] 
1025475c8125Smatthias.ringwald     // reference to use transport layer implementation
10263a9fb326S[email protected]     hci_stack->hci_transport = transport;
1027475c8125Smatthias.ringwald 
102811e23e5fSmatthias.ringwald     // references to used control implementation
10293a9fb326S[email protected]     hci_stack->control = control;
103011e23e5fSmatthias.ringwald 
103111e23e5fSmatthias.ringwald     // reference to used config
10323a9fb326S[email protected]     hci_stack->config = config;
103311e23e5fSmatthias.ringwald 
103416833f0aSmatthias.ringwald     // higher level handler
10353a9fb326S[email protected]     hci_stack->packet_handler = dummy_handler;
103616833f0aSmatthias.ringwald 
1037404843c1Smatthias.ringwald     // store and open remote device db
10383a9fb326S[email protected]     hci_stack->remote_device_db = remote_device_db;
10393a9fb326S[email protected]     if (hci_stack->remote_device_db) {
10403a9fb326S[email protected]         hci_stack->remote_device_db->open();
1041404843c1Smatthias.ringwald     }
104229d53098Smatthias.ringwald 
10438fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
10443a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
10458fcba05dSmatthias.ringwald 
104616833f0aSmatthias.ringwald     // register packet handlers with transport
104710e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
1048f5454fc6Smatthias.ringwald 
10493a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
1050e2386ba1S[email protected] 
1051e2386ba1S[email protected]     // class of device
10523a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
1053a45d6b9fS[email protected] 
105463048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
10553a9fb326S[email protected]     hci_stack->ssp_enable = 1;
10563a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
10573a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
10583a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
105969a97523S[email protected] 
1060595bdbfbS[email protected]     hci_state_reset();
1061475c8125Smatthias.ringwald }
1062475c8125Smatthias.ringwald 
1063404843c1Smatthias.ringwald void hci_close(){
1064404843c1Smatthias.ringwald     // close remote device db
10653a9fb326S[email protected]     if (hci_stack->remote_device_db) {
10663a9fb326S[email protected]         hci_stack->remote_device_db->close();
1067404843c1Smatthias.ringwald     }
10683a9fb326S[email protected]     while (hci_stack->connections) {
1069bc68afe2S[email protected]         // cancel all l2cap connections
1070bc68afe2S[email protected]         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
10713a9fb326S[email protected]         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1072f5454fc6Smatthias.ringwald     }
1073f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
10743a9fb326S[email protected] 
10753a9fb326S[email protected] #ifdef HAVE_MALLOC
10763a9fb326S[email protected]     free(hci_stack);
10773a9fb326S[email protected] #endif
10783a9fb326S[email protected]     hci_stack = NULL;
1079404843c1Smatthias.ringwald }
1080404843c1Smatthias.ringwald 
10819e61646fS[email protected] void hci_set_class_of_device(uint32_t class_of_device){
10829e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
10839e61646fS[email protected] }
10849e61646fS[email protected] 
108566fb9560S[email protected] void hci_disable_l2cap_timeout_check(){
108666fb9560S[email protected]     disable_l2cap_timeouts = 1;
108766fb9560S[email protected] }
10888d213e1aSmatthias.ringwald // State-Module-Driver overview
10898d213e1aSmatthias.ringwald // state                    module  low-level
10908d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
10918d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
10928d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
10938d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
1094d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
1095d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
1096c7e0c5f6Smatthias.ringwald 
109740d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
10987301ad89Smatthias.ringwald 
1099038bc64cSmatthias.ringwald     // power on
1100f9a30166Smatthias.ringwald     int err = 0;
11013a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
11023a9fb326S[email protected]         err = (*hci_stack->control->on)(hci_stack->config);
1103f9a30166Smatthias.ringwald     }
1104038bc64cSmatthias.ringwald     if (err){
11057d67539fSmatthias.ringwald         log_error( "POWER_ON failed\n");
1106038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
1107038bc64cSmatthias.ringwald         return err;
1108038bc64cSmatthias.ringwald     }
1109038bc64cSmatthias.ringwald 
1110038bc64cSmatthias.ringwald     // open low-level device
11113a9fb326S[email protected]     err = hci_stack->hci_transport->open(hci_stack->config);
1112038bc64cSmatthias.ringwald     if (err){
11137d67539fSmatthias.ringwald         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
11143a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
11153a9fb326S[email protected]             (*hci_stack->control->off)(hci_stack->config);
1116f9a30166Smatthias.ringwald         }
1117038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
1118038bc64cSmatthias.ringwald         return err;
1119038bc64cSmatthias.ringwald     }
11208d213e1aSmatthias.ringwald     return 0;
11218d213e1aSmatthias.ringwald }
1122038bc64cSmatthias.ringwald 
112340d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
11248d213e1aSmatthias.ringwald 
11257b5fbe1fSmatthias.ringwald     log_info("hci_power_control_off\n");
11269418f9c9Smatthias.ringwald 
11278d213e1aSmatthias.ringwald     // close low-level device
11283a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
11298d213e1aSmatthias.ringwald 
11307b5fbe1fSmatthias.ringwald     log_info("hci_power_control_off - hci_transport closed\n");
11319418f9c9Smatthias.ringwald 
11328d213e1aSmatthias.ringwald     // power off
11333a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
11343a9fb326S[email protected]         (*hci_stack->control->off)(hci_stack->config);
11358d213e1aSmatthias.ringwald     }
11369418f9c9Smatthias.ringwald 
11377b5fbe1fSmatthias.ringwald     log_info("hci_power_control_off - control closed\n");
11389418f9c9Smatthias.ringwald 
11393a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
114072ea5239Smatthias.ringwald }
114172ea5239Smatthias.ringwald 
114240d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
114372ea5239Smatthias.ringwald 
11447b5fbe1fSmatthias.ringwald     log_info("hci_power_control_sleep\n");
11453144bce4Smatthias.ringwald 
1146b429b9b7Smatthias.ringwald #if 0
1147b429b9b7Smatthias.ringwald     // don't close serial port during sleep
1148b429b9b7Smatthias.ringwald 
114972ea5239Smatthias.ringwald     // close low-level device
11503a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
1151b429b9b7Smatthias.ringwald #endif
115272ea5239Smatthias.ringwald 
115372ea5239Smatthias.ringwald     // sleep mode
11543a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
11553a9fb326S[email protected]         (*hci_stack->control->sleep)(hci_stack->config);
115672ea5239Smatthias.ringwald     }
1157b429b9b7Smatthias.ringwald 
11583a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
11598d213e1aSmatthias.ringwald }
11608d213e1aSmatthias.ringwald 
116140d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
1162b429b9b7Smatthias.ringwald 
11637b5fbe1fSmatthias.ringwald     log_info("hci_power_control_wake\n");
1164b429b9b7Smatthias.ringwald 
1165b429b9b7Smatthias.ringwald     // wake on
11663a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
11673a9fb326S[email protected]         (*hci_stack->control->wake)(hci_stack->config);
1168b429b9b7Smatthias.ringwald     }
1169b429b9b7Smatthias.ringwald 
1170b429b9b7Smatthias.ringwald #if 0
1171b429b9b7Smatthias.ringwald     // open low-level device
11723a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
1173b429b9b7Smatthias.ringwald     if (err){
11747d67539fSmatthias.ringwald         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
11753a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
11763a9fb326S[email protected]             (*hci_stack->control->off)(hci_stack->config);
1177b429b9b7Smatthias.ringwald         }
1178b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
1179b429b9b7Smatthias.ringwald         return err;
1180b429b9b7Smatthias.ringwald     }
1181b429b9b7Smatthias.ringwald #endif
1182b429b9b7Smatthias.ringwald 
1183b429b9b7Smatthias.ringwald     return 0;
1184b429b9b7Smatthias.ringwald }
1185b429b9b7Smatthias.ringwald 
1186b429b9b7Smatthias.ringwald 
11878d213e1aSmatthias.ringwald int hci_power_control(HCI_POWER_MODE power_mode){
1188d661ed19Smatthias.ringwald 
11893a9fb326S[email protected]     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack->state);
1190d661ed19Smatthias.ringwald 
11918d213e1aSmatthias.ringwald     int err = 0;
11923a9fb326S[email protected]     switch (hci_stack->state){
11938d213e1aSmatthias.ringwald 
11948d213e1aSmatthias.ringwald         case HCI_STATE_OFF:
11958d213e1aSmatthias.ringwald             switch (power_mode){
11968d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
11978d213e1aSmatthias.ringwald                     err = hci_power_control_on();
11988d213e1aSmatthias.ringwald                     if (err) return err;
11997301ad89Smatthias.ringwald                     // set up state machine
12003a9fb326S[email protected]                     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
12013a9fb326S[email protected]                     hci_stack->state = HCI_STATE_INITIALIZING;
12023a9fb326S[email protected]                     hci_stack->substate = 0;
12038d213e1aSmatthias.ringwald                     break;
12048d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
12058d213e1aSmatthias.ringwald                     // do nothing
12068d213e1aSmatthias.ringwald                     break;
12078d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1208b546ac54Smatthias.ringwald                     // do nothing (with SLEEP == OFF)
12098d213e1aSmatthias.ringwald                     break;
12108d213e1aSmatthias.ringwald             }
12118d213e1aSmatthias.ringwald             break;
12127301ad89Smatthias.ringwald 
12138d213e1aSmatthias.ringwald         case HCI_STATE_INITIALIZING:
12148d213e1aSmatthias.ringwald             switch (power_mode){
12158d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
12168d213e1aSmatthias.ringwald                     // do nothing
12178d213e1aSmatthias.ringwald                     break;
12188d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
12198d213e1aSmatthias.ringwald                     // no connections yet, just turn it off
12208d213e1aSmatthias.ringwald                     hci_power_control_off();
12218d213e1aSmatthias.ringwald                     break;
12228d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1223b546ac54Smatthias.ringwald                     // no connections yet, just turn it off
122472ea5239Smatthias.ringwald                     hci_power_control_sleep();
12258d213e1aSmatthias.ringwald                     break;
12268d213e1aSmatthias.ringwald             }
12278d213e1aSmatthias.ringwald             break;
12287301ad89Smatthias.ringwald 
12298d213e1aSmatthias.ringwald         case HCI_STATE_WORKING:
12308d213e1aSmatthias.ringwald             switch (power_mode){
12318d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
12328d213e1aSmatthias.ringwald                     // do nothing
12338d213e1aSmatthias.ringwald                     break;
12348d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
1235c7e0c5f6Smatthias.ringwald                     // see hci_run
12363a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
12378d213e1aSmatthias.ringwald                     break;
12388d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1239b546ac54Smatthias.ringwald                     // see hci_run
12403a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
12413a9fb326S[email protected]                     hci_stack->substate = 0;
12428d213e1aSmatthias.ringwald                     break;
12438d213e1aSmatthias.ringwald             }
12448d213e1aSmatthias.ringwald             break;
12457301ad89Smatthias.ringwald 
12468d213e1aSmatthias.ringwald         case HCI_STATE_HALTING:
12478d213e1aSmatthias.ringwald             switch (power_mode){
12488d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
12498d213e1aSmatthias.ringwald                     // set up state machine
12503a9fb326S[email protected]                     hci_stack->state = HCI_STATE_INITIALIZING;
12513a9fb326S[email protected]                     hci_stack->substate = 0;
12528d213e1aSmatthias.ringwald                     break;
12538d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
12548d213e1aSmatthias.ringwald                     // do nothing
12558d213e1aSmatthias.ringwald                     break;
12568d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1257b546ac54Smatthias.ringwald                     // see hci_run
12583a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
12593a9fb326S[email protected]                     hci_stack->substate = 0;
12608d213e1aSmatthias.ringwald                     break;
12618d213e1aSmatthias.ringwald             }
12628d213e1aSmatthias.ringwald             break;
12638d213e1aSmatthias.ringwald 
12648d213e1aSmatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
12658d213e1aSmatthias.ringwald             switch (power_mode){
12668d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
126728171530Smatthias.ringwald 
126828171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
126928171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
127028171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
12713a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
12723a9fb326S[email protected]                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
127328171530Smatthias.ringwald                         break;
127428171530Smatthias.ringwald                     }
127528171530Smatthias.ringwald #endif
1276b546ac54Smatthias.ringwald                     // set up state machine
12773a9fb326S[email protected]                     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
12783a9fb326S[email protected]                     hci_stack->state = HCI_STATE_INITIALIZING;
12793a9fb326S[email protected]                     hci_stack->substate = 0;
12808d213e1aSmatthias.ringwald                     break;
12818d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
1282b546ac54Smatthias.ringwald                     // see hci_run
12833a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
12848d213e1aSmatthias.ringwald                     break;
12858d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1286b546ac54Smatthias.ringwald                     // do nothing
12878d213e1aSmatthias.ringwald                     break;
12888d213e1aSmatthias.ringwald             }
12898d213e1aSmatthias.ringwald             break;
12908d213e1aSmatthias.ringwald 
12918d213e1aSmatthias.ringwald         case HCI_STATE_SLEEPING:
12928d213e1aSmatthias.ringwald             switch (power_mode){
12938d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
129428171530Smatthias.ringwald 
129528171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
129628171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
129728171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
12983a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
12993a9fb326S[email protected]                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1300758b46ceSmatthias.ringwald                         hci_update_scan_enable();
130128171530Smatthias.ringwald                         break;
130228171530Smatthias.ringwald                     }
130328171530Smatthias.ringwald #endif
13043144bce4Smatthias.ringwald                     err = hci_power_control_wake();
13053144bce4Smatthias.ringwald                     if (err) return err;
1306b546ac54Smatthias.ringwald                     // set up state machine
13073a9fb326S[email protected]                     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
13083a9fb326S[email protected]                     hci_stack->state = HCI_STATE_INITIALIZING;
13093a9fb326S[email protected]                     hci_stack->substate = 0;
13108d213e1aSmatthias.ringwald                     break;
13118d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
13123a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
13138d213e1aSmatthias.ringwald                     break;
13148d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1315b546ac54Smatthias.ringwald                     // do nothing
13168d213e1aSmatthias.ringwald                     break;
13178d213e1aSmatthias.ringwald             }
13188d213e1aSmatthias.ringwald             break;
131911e23e5fSmatthias.ringwald     }
132068d92d03Smatthias.ringwald 
1321038bc64cSmatthias.ringwald     // create internal event
1322ee8bf225Smatthias.ringwald 	hci_emit_state();
1323ee8bf225Smatthias.ringwald 
132468d92d03Smatthias.ringwald 	// trigger next/first action
132568d92d03Smatthias.ringwald 	hci_run();
132668d92d03Smatthias.ringwald 
1327475c8125Smatthias.ringwald     return 0;
1328475c8125Smatthias.ringwald }
1329475c8125Smatthias.ringwald 
1330758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
1331758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
13323a9fb326S[email protected]     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1333758b46ceSmatthias.ringwald     hci_run();
1334758b46ceSmatthias.ringwald }
1335758b46ceSmatthias.ringwald 
1336381fbed8Smatthias.ringwald void hci_discoverable_control(uint8_t enable){
1337381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
1338381fbed8Smatthias.ringwald 
13393a9fb326S[email protected]     if (hci_stack->discoverable == enable){
13403a9fb326S[email protected]         hci_emit_discoverable_enabled(hci_stack->discoverable);
1341381fbed8Smatthias.ringwald         return;
1342381fbed8Smatthias.ringwald     }
1343381fbed8Smatthias.ringwald 
13443a9fb326S[email protected]     hci_stack->discoverable = enable;
1345758b46ceSmatthias.ringwald     hci_update_scan_enable();
1346758b46ceSmatthias.ringwald }
1347b031bebbSmatthias.ringwald 
1348758b46ceSmatthias.ringwald void hci_connectable_control(uint8_t enable){
1349758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
1350758b46ceSmatthias.ringwald 
1351758b46ceSmatthias.ringwald     // don't emit event
13523a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
1353758b46ceSmatthias.ringwald 
13543a9fb326S[email protected]     hci_stack->connectable = enable;
1355758b46ceSmatthias.ringwald     hci_update_scan_enable();
1356381fbed8Smatthias.ringwald }
1357381fbed8Smatthias.ringwald 
13585061f3afS[email protected] bd_addr_t * hci_local_bd_addr(void){
13593a9fb326S[email protected]     return &hci_stack->local_bd_addr;
13605061f3afS[email protected] }
13615061f3afS[email protected] 
136206b35ec0Smatthias.ringwald void hci_run(){
13638a485f27Smatthias.ringwald 
136432ab9390Smatthias.ringwald     hci_connection_t * connection;
136532ab9390Smatthias.ringwald     linked_item_t * it;
136632ab9390Smatthias.ringwald 
136764f0b431S[email protected]     if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return;
1368ce4c8fabSmatthias.ringwald 
1369b031bebbSmatthias.ringwald     // global/non-connection oriented commands
1370b031bebbSmatthias.ringwald 
1371b031bebbSmatthias.ringwald     // decline incoming connections
13723a9fb326S[email protected]     if (hci_stack->decline_reason){
13733a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
13743a9fb326S[email protected]         hci_stack->decline_reason = 0;
13753a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1376dbe1a790S[email protected]         return;
1377ce4c8fabSmatthias.ringwald     }
1378ce4c8fabSmatthias.ringwald 
1379b031bebbSmatthias.ringwald     // send scan enable
13803a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
13813a9fb326S[email protected]         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
13823a9fb326S[email protected]         hci_stack->new_scan_enable_value = 0xff;
1383dbe1a790S[email protected]         return;
1384b031bebbSmatthias.ringwald     }
1385b031bebbSmatthias.ringwald 
1386b2f949feS[email protected] #ifdef HAVE_BLE
13877bdc6798S[email protected]     // handle le scan
13887bdc6798S[email protected]     if (hci_stack->state == HCI_STATE_WORKING){
13897bdc6798S[email protected]         switch(hci_stack->le_scanning_state){
13907bdc6798S[email protected]             case LE_START_SCAN:
13917bdc6798S[email protected]                 hci_stack->le_scanning_state = LE_SCANNING;
13927bdc6798S[email protected]                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
13937bdc6798S[email protected]                 return;
13947bdc6798S[email protected] 
13957bdc6798S[email protected]             case LE_STOP_SCAN:
13967bdc6798S[email protected]                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
13977bdc6798S[email protected]                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
13987bdc6798S[email protected]                 return;
13997bdc6798S[email protected]             default:
14007bdc6798S[email protected]                 break;
14017bdc6798S[email protected]         }
14027bdc6798S[email protected]     }
1403b2f949feS[email protected] #endif
14047bdc6798S[email protected] 
140532ab9390Smatthias.ringwald     // send pending HCI commands
14063a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1407b031bebbSmatthias.ringwald         connection = (hci_connection_t *) it;
140832ab9390Smatthias.ringwald 
14090bf6344aS[email protected]         switch(connection->state){
14100bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
14114f3229d8S[email protected]                 switch(connection->address_type){
14124f3229d8S[email protected]                     case BD_ADDR_TYPE_CLASSIC:
1413564fca32S[email protected]                         log_info("sending hci_create_connection\n");
1414ad83dc6aS[email protected]                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
14154f3229d8S[email protected]                         break;
14164f3229d8S[email protected]                     default:
1417b2f949feS[email protected] #ifdef HAVE_BLE
1418564fca32S[email protected]                         log_info("sending hci_le_create_connection\n");
14194f3229d8S[email protected]                         hci_send_cmd(&hci_le_create_connection,
14204f3229d8S[email protected]                                      1000,      // scan interval: 625 ms
14214f3229d8S[email protected]                                      1000,      // scan interval: 625 ms
14224f3229d8S[email protected]                                      0,         // don't use whitelist
14234f3229d8S[email protected]                                      connection->address_type, // peer address type
14244f3229d8S[email protected]                                      connection->address,       // peer bd addr
14254f3229d8S[email protected]                                      0,         // our addr type: public
14264f3229d8S[email protected]                                      80,        // conn interval min
14274f3229d8S[email protected]                                      80,        // conn interval max (3200 * 0.625)
14284f3229d8S[email protected]                                      0,         // conn latency
14294f3229d8S[email protected]                                      2000,      // supervision timeout
14304f3229d8S[email protected]                                      0,         // min ce length
14314f3229d8S[email protected]                                      1000       // max ce length
14324f3229d8S[email protected]                                      );
14334f3229d8S[email protected] 
14344f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
1435b2f949feS[email protected] #endif
14364f3229d8S[email protected]                         break;
14374f3229d8S[email protected]                 }
1438ad83dc6aS[email protected]                 return;
1439ad83dc6aS[email protected] 
14400bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
14417b5fbe1fSmatthias.ringwald                 log_info("sending hci_accept_connection_request\n");
144232ab9390Smatthias.ringwald                 connection->state = ACCEPTED_CONNECTION_REQUEST;
144334d2123cS[email protected]                 hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1444dbe1a790S[email protected]                 return;
14450bf6344aS[email protected] 
1446a6725849S[email protected] #ifdef HAVE_BLE
14470bf6344aS[email protected]             case SEND_CANCEL_CONNECTION:
14480bf6344aS[email protected]                 connection->state = SENT_CANCEL_CONNECTION;
14490bf6344aS[email protected]                 hci_send_cmd(&hci_le_create_connection_cancel);
14500bf6344aS[email protected]                 return;
1451a6725849S[email protected] #endif
14520bf6344aS[email protected]             case SEND_DISCONNECT:
14530bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
1454*7851196eSmatthias.ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
14550bf6344aS[email protected]                 return;
14560bf6344aS[email protected] 
14570bf6344aS[email protected]             default:
14580bf6344aS[email protected]                 break;
1459c7e0c5f6Smatthias.ringwald         }
1460c7e0c5f6Smatthias.ringwald 
14610bf6344aS[email protected] 
14620bf6344aS[email protected] 
146332ab9390Smatthias.ringwald         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
146434d2123cS[email protected]             log_info("responding to link key request\n");
146534d2123cS[email protected]             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
146632ab9390Smatthias.ringwald             link_key_t link_key;
1467c77e8838S[email protected]             link_key_type_t link_key_type;
14683a9fb326S[email protected]             if ( hci_stack->remote_device_db
14693a9fb326S[email protected]               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
147034d2123cS[email protected]               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
14719ab95c90S[email protected]                connection->link_key_type = link_key_type;
147232ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
147332ab9390Smatthias.ringwald             } else {
147432ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
147532ab9390Smatthias.ringwald             }
1476dbe1a790S[email protected]             return;
147732ab9390Smatthias.ringwald         }
14781d6b20aeS[email protected] 
1479899283eaS[email protected]         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
14804c57c146S[email protected]             log_info("denying to pin request\n");
1481899283eaS[email protected]             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
148234d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
14834c57c146S[email protected]             return;
14844c57c146S[email protected]         }
14854c57c146S[email protected] 
1486dbe1a790S[email protected]         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
148734d2123cS[email protected]             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
148882d8f825S[email protected]             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
148982d8f825S[email protected]             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1490106d6d11S[email protected]                 // tweak authentication requirements
14913a9fb326S[email protected]                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1492106d6d11S[email protected]                 if (connection->bonding_flags & BONDING_DEDICATED){
14939faad3abS[email protected]                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
14949faad3abS[email protected]                 }
14959faad3abS[email protected]                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
14969faad3abS[email protected]                     authreq |= 1;
1497106d6d11S[email protected]                 }
14983a9fb326S[email protected]                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1499f8fb5f6eS[email protected]             } else {
1500f8fb5f6eS[email protected]                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1501f8fb5f6eS[email protected]             }
1502dbe1a790S[email protected]             return;
150332ab9390Smatthias.ringwald         }
150432ab9390Smatthias.ringwald 
1505dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1506dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
150734d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1508dbe1a790S[email protected]             return;
1509dbe1a790S[email protected]         }
1510dbe1a790S[email protected] 
1511dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1512dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
151334d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1514dbe1a790S[email protected]             return;
1515dbe1a790S[email protected]         }
1516afd4e962S[email protected] 
1517afd4e962S[email protected]         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1518afd4e962S[email protected]             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
151934d2123cS[email protected]             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
15202bd8b7e7S[email protected]             return;
15212bd8b7e7S[email protected]         }
15222bd8b7e7S[email protected] 
15232bd8b7e7S[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
15242bd8b7e7S[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
152534d2123cS[email protected]             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
152634d2123cS[email protected]             return;
152734d2123cS[email protected]         }
1528ad83dc6aS[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1529ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
153052d34f98S[email protected]             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1531ad83dc6aS[email protected]             return;
1532ad83dc6aS[email protected]         }
153334d2123cS[email protected]         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
153434d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
153534d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
15362bd8b7e7S[email protected]             return;
1537afd4e962S[email protected]         }
1538dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1539dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1540dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1541dce78009S[email protected]             return;
1542dce78009S[email protected]         }
1543dbe1a790S[email protected]     }
1544c7e0c5f6Smatthias.ringwald 
15453a9fb326S[email protected]     switch (hci_stack->state){
15463429f56bSmatthias.ringwald         case HCI_STATE_INITIALIZING:
15473a9fb326S[email protected]             // log_info("hci_init: substate %u\n", hci_stack->substate);
15483a9fb326S[email protected]             if (hci_stack->substate % 2) {
15493429f56bSmatthias.ringwald                 // odd: waiting for command completion
155006b35ec0Smatthias.ringwald                 return;
15513429f56bSmatthias.ringwald             }
15523a9fb326S[email protected]             switch (hci_stack->substate >> 1){
1553c7492964Smatthias.ringwald                 case 0: // RESET
1554595bdbfbS[email protected]                     hci_state_reset();
155524052c2aS[email protected] 
1556595bdbfbS[email protected]                     hci_send_cmd(&hci_reset);
15573a9fb326S[email protected]                     if (hci_stack->config == 0 || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
1558c7492964Smatthias.ringwald                         // skip baud change
15593a9fb326S[email protected]                         hci_stack->substate = 4; // >> 1 = 2
1560c7492964Smatthias.ringwald                     }
15613429f56bSmatthias.ringwald                     break;
1562c7492964Smatthias.ringwald                 case 1: // SEND BAUD CHANGE
15633a9fb326S[email protected]                     hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
15643a9fb326S[email protected]                     hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1565c7492964Smatthias.ringwald                     break;
1566c7492964Smatthias.ringwald                 case 2: // LOCAL BAUD CHANGE
15673a9fb326S[email protected]                     hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
15683a9fb326S[email protected]                     hci_stack->substate += 2;
1569c7492964Smatthias.ringwald                     // break missing here for fall through
1570c7492964Smatthias.ringwald 
1571c7492964Smatthias.ringwald                 case 3:
157224052c2aS[email protected]                     // Custom initialization
15733a9fb326S[email protected]                     if (hci_stack->control && hci_stack->control->next_cmd){
15743a9fb326S[email protected]                         int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
1575d62aca9fSmatthias.ringwald                         if (valid_cmd){
15763a9fb326S[email protected]                             int size = 3 + hci_stack->hci_packet_buffer[2];
15773a9fb326S[email protected]                             hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
15783a9fb326S[email protected]                             hci_stack->substate = 4; // more init commands
157990919203Smatthias.ringwald                             break;
158090919203Smatthias.ringwald                         }
1581d62aca9fSmatthias.ringwald                         log_info("hci_run: init script done\n\r");
158290919203Smatthias.ringwald                     }
15832f6c30e1Smatthias.ringwald                     // otherwise continue
1584f432a6ddSmatthias.ringwald 					hci_send_cmd(&hci_read_bd_addr);
1585f432a6ddSmatthias.ringwald 					break;
1586c7492964Smatthias.ringwald 				case 4:
1587e2edc0c3Smatthias.ringwald 					hci_send_cmd(&hci_read_buffer_size);
1588e2edc0c3Smatthias.ringwald 					break;
1589c7492964Smatthias.ringwald                 case 5:
159065389bfcS[email protected]                     hci_send_cmd(&hci_read_local_supported_features);
15913429f56bSmatthias.ringwald                     break;
1592c7492964Smatthias.ringwald                 case 6:
1593d7e0e3a8S[email protected]                     if (hci_le_supported()){
1594d7e0e3a8S[email protected]                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1595d7e0e3a8S[email protected]                     } else {
1596d7e0e3a8S[email protected]                         // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1597d7e0e3a8S[email protected]                         hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1598d7e0e3a8S[email protected]                     }
1599f5d8d141S[email protected] 
1600f5d8d141S[email protected]                     // skip Classic init commands for LE only chipsets
160124052c2aS[email protected]                     if (!hci_classic_supported()){
160224052c2aS[email protected]                         if (hci_le_supported()){
16033a9fb326S[email protected]                             hci_stack->substate = 11 << 1;    // skip all classic command
160424052c2aS[email protected]                         } else {
160524052c2aS[email protected]                             log_error("Neither BR/EDR nor LE supported");
16063a9fb326S[email protected]                             hci_stack->substate = 13 << 1;    // skip all
160724052c2aS[email protected]                         }
1608f5d8d141S[email protected]                     }
1609f5d8d141S[email protected]                     break;
1610f5d8d141S[email protected]                 case 7:
161124052c2aS[email protected]                     if (hci_ssp_supported()){
16123a9fb326S[email protected]                         hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1613f5d8d141S[email protected]                         break;
161424052c2aS[email protected]                     }
16153a9fb326S[email protected]                     hci_stack->substate += 2;
161624052c2aS[email protected]                     // break missing here for fall through
161724052c2aS[email protected] 
1618f5d8d141S[email protected]                 case 8:
161965389bfcS[email protected]                     // ca. 15 sec
162065389bfcS[email protected]                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1621559e517eS[email protected]                     break;
1622f5d8d141S[email protected]                 case 9:
16233a9fb326S[email protected]                     hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1624e2386ba1S[email protected]                     break;
1625f5d8d141S[email protected]                 case 10:
16263a9fb326S[email protected]                     if (hci_stack->local_name){
16273a9fb326S[email protected]                         hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
1628e2386ba1S[email protected]                     } else {
16298a485f27Smatthias.ringwald                         char hostname[30];
1630e2386ba1S[email protected] #ifdef EMBEDDED
1631e2386ba1S[email protected]                         // BTstack-11:22:33:44:55:66
1632e2386ba1S[email protected]                         strcpy(hostname, "BTstack ");
16333a9fb326S[email protected]                         strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr));
1634e2386ba1S[email protected]                         printf("---> Name %s\n", hostname);
1635e2386ba1S[email protected] #else
1636e2386ba1S[email protected]                         // hostname for POSIX systems
16378a485f27Smatthias.ringwald                         gethostname(hostname, 30);
16388a485f27Smatthias.ringwald                         hostname[29] = '\0';
1639e2386ba1S[email protected] #endif
16408a485f27Smatthias.ringwald                         hci_send_cmd(&hci_write_local_name, hostname);
16418a485f27Smatthias.ringwald                     }
16423c4d4b90Smatthias.ringwald                     break;
1643e0dbca83S[email protected]                 case 11:
16443a9fb326S[email protected] 					hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
164524052c2aS[email protected]                     if (!hci_le_supported()){
164624052c2aS[email protected]                         // SKIP LE init for Classic only configuration
16473a9fb326S[email protected]                         hci_stack->substate = 13 << 1;
164824052c2aS[email protected]                     }
1649a45d6b9fS[email protected] 					break;
165024052c2aS[email protected] 
165143aa7007S[email protected] #ifdef HAVE_BLE
165224052c2aS[email protected]                 // LE INIT
1653a45d6b9fS[email protected]                 case 12:
165424052c2aS[email protected]                     hci_send_cmd(&hci_le_read_buffer_size);
165524052c2aS[email protected]                     break;
165624052c2aS[email protected]                 case 13:
165724052c2aS[email protected]                     // LE Supported Host = 1, Simultaneous Host = 0
165824052c2aS[email protected]                     hci_send_cmd(&hci_write_le_host_supported, 1, 0);
165924052c2aS[email protected]                     break;
166043aa7007S[email protected] #endif
166124052c2aS[email protected] 
166224052c2aS[email protected]                 // DONE
166324052c2aS[email protected]                 case 14:
16643429f56bSmatthias.ringwald                     // done.
16653a9fb326S[email protected]                     hci_stack->state = HCI_STATE_WORKING;
1666b360b6adSmatthias.ringwald                     hci_emit_state();
16673429f56bSmatthias.ringwald                     break;
16683429f56bSmatthias.ringwald                 default:
16693429f56bSmatthias.ringwald                     break;
1670475c8125Smatthias.ringwald             }
16713a9fb326S[email protected]             hci_stack->substate++;
16723429f56bSmatthias.ringwald             break;
1673c7e0c5f6Smatthias.ringwald 
1674c7e0c5f6Smatthias.ringwald         case HCI_STATE_HALTING:
1675c7e0c5f6Smatthias.ringwald 
16767b5fbe1fSmatthias.ringwald             log_info("HCI_STATE_HALTING\n");
1677c7e0c5f6Smatthias.ringwald             // close all open connections
16783a9fb326S[email protected]             connection =  (hci_connection_t *) hci_stack->connections;
1679c7e0c5f6Smatthias.ringwald             if (connection){
168032ab9390Smatthias.ringwald 
1681c7e0c5f6Smatthias.ringwald                 // send disconnect
168264f0b431S[email protected]                 if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return;
168332ab9390Smatthias.ringwald 
168479bbfa0bSmatthias.ringwald                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
16856ad890d3Smatthias.ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1686c7e0c5f6Smatthias.ringwald 
1687c7e0c5f6Smatthias.ringwald                 // send disconnected event right away - causes higher layer connections to get closed, too.
1688c7e0c5f6Smatthias.ringwald                 hci_shutdown_connection(connection);
1689c7e0c5f6Smatthias.ringwald                 return;
1690c7e0c5f6Smatthias.ringwald             }
16917b5fbe1fSmatthias.ringwald             log_info("HCI_STATE_HALTING, calling off\n");
1692c7e0c5f6Smatthias.ringwald 
169372ea5239Smatthias.ringwald             // switch mode
1694c7e0c5f6Smatthias.ringwald             hci_power_control_off();
16959418f9c9Smatthias.ringwald 
16967b5fbe1fSmatthias.ringwald             log_info("HCI_STATE_HALTING, emitting state\n");
169772ea5239Smatthias.ringwald             hci_emit_state();
16987b5fbe1fSmatthias.ringwald             log_info("HCI_STATE_HALTING, done\n");
169972ea5239Smatthias.ringwald             break;
1700c7e0c5f6Smatthias.ringwald 
170172ea5239Smatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
17023a9fb326S[email protected]             switch(hci_stack->substate) {
170389db417bSmatthias.ringwald                 case 0:
17047b5fbe1fSmatthias.ringwald                     log_info("HCI_STATE_FALLING_ASLEEP\n");
170572ea5239Smatthias.ringwald                     // close all open connections
17063a9fb326S[email protected]                     connection =  (hci_connection_t *) hci_stack->connections;
170766da7044Smatthias.ringwald 
170828171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
170966da7044Smatthias.ringwald                     // don't close connections, if H4 supports power management
171066da7044Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
171166da7044Smatthias.ringwald                         connection = NULL;
171266da7044Smatthias.ringwald                     }
171366da7044Smatthias.ringwald #endif
171472ea5239Smatthias.ringwald                     if (connection){
171532ab9390Smatthias.ringwald 
171672ea5239Smatthias.ringwald                         // send disconnect
171732ab9390Smatthias.ringwald                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
171832ab9390Smatthias.ringwald 
171979bbfa0bSmatthias.ringwald                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
17206ad890d3Smatthias.ringwald                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
172172ea5239Smatthias.ringwald 
172272ea5239Smatthias.ringwald                         // send disconnected event right away - causes higher layer connections to get closed, too.
172372ea5239Smatthias.ringwald                         hci_shutdown_connection(connection);
172472ea5239Smatthias.ringwald                         return;
172572ea5239Smatthias.ringwald                     }
172672ea5239Smatthias.ringwald 
172792368cd3S[email protected]                     if (hci_classic_supported()){
172889db417bSmatthias.ringwald                         // disable page and inquiry scan
172964f0b431S[email protected]                         if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return;
173032ab9390Smatthias.ringwald 
173192368cd3S[email protected]                         log_info("HCI_STATE_HALTING, disabling inq scans\n");
17323a9fb326S[email protected]                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
173389db417bSmatthias.ringwald 
173489db417bSmatthias.ringwald                         // continue in next sub state
17353a9fb326S[email protected]                         hci_stack->substate++;
173689db417bSmatthias.ringwald                         break;
173792368cd3S[email protected]                     }
173892368cd3S[email protected]                     // fall through for ble-only chips
173992368cd3S[email protected] 
174089db417bSmatthias.ringwald                 case 2:
17417b5fbe1fSmatthias.ringwald                     log_info("HCI_STATE_HALTING, calling sleep\n");
174228171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
174328171530Smatthias.ringwald                     // don't actually go to sleep, if H4 supports power management
174428171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
174528171530Smatthias.ringwald                         // SLEEP MODE reached
17463a9fb326S[email protected]                         hci_stack->state = HCI_STATE_SLEEPING;
174728171530Smatthias.ringwald                         hci_emit_state();
174828171530Smatthias.ringwald                         break;
174928171530Smatthias.ringwald                     }
175028171530Smatthias.ringwald #endif
175172ea5239Smatthias.ringwald                     // switch mode
17523a9fb326S[email protected]                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
1753c7e0c5f6Smatthias.ringwald                     hci_emit_state();
175428171530Smatthias.ringwald                     break;
175528171530Smatthias.ringwald 
175689db417bSmatthias.ringwald                 default:
175789db417bSmatthias.ringwald                     break;
175889db417bSmatthias.ringwald             }
1759c7e0c5f6Smatthias.ringwald             break;
1760c7e0c5f6Smatthias.ringwald 
17613429f56bSmatthias.ringwald         default:
17623429f56bSmatthias.ringwald             break;
17631f504dbdSmatthias.ringwald     }
17643429f56bSmatthias.ringwald }
176516833f0aSmatthias.ringwald 
176631452debSmatthias.ringwald int hci_send_cmd_packet(uint8_t *packet, int size){
1767c8e4258aSmatthias.ringwald     bd_addr_t addr;
1768c8e4258aSmatthias.ringwald     hci_connection_t * conn;
1769c8e4258aSmatthias.ringwald     // house-keeping
1770c8e4258aSmatthias.ringwald 
1771c8e4258aSmatthias.ringwald     // create_connection?
1772c8e4258aSmatthias.ringwald     if (IS_COMMAND(packet, hci_create_connection)){
1773c8e4258aSmatthias.ringwald         bt_flip_addr(addr, &packet[3]);
1774339b6768Smatthias.ringwald         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1775c8e4258aSmatthias.ringwald 
177696a45072S[email protected]         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1777ad83dc6aS[email protected]         if (!conn){
177896a45072S[email protected]             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
177917f1ba2aSmatthias.ringwald             if (!conn){
178017f1ba2aSmatthias.ringwald                 // notify client that alloc failed
178117f1ba2aSmatthias.ringwald                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
178217f1ba2aSmatthias.ringwald                 return 0; // don't sent packet to controller
178317f1ba2aSmatthias.ringwald             }
1784ad83dc6aS[email protected]             conn->state = SEND_CREATE_CONNECTION;
1785ad83dc6aS[email protected]         }
1786ad83dc6aS[email protected]         log_info("conn state %u", conn->state);
1787ad83dc6aS[email protected]         switch (conn->state){
1788ad83dc6aS[email protected]             // if connection active exists
1789ad83dc6aS[email protected]             case OPEN:
179062bda3fbS[email protected]                 // and OPEN, emit connection complete command, don't send to controller
1791ad83dc6aS[email protected]                 hci_emit_connection_complete(conn, 0);
179262bda3fbS[email protected]                 return 0;
1793ad83dc6aS[email protected]             case SEND_CREATE_CONNECTION:
1794ad83dc6aS[email protected]                 // connection created by hci, e.g. dedicated bonding
1795ad83dc6aS[email protected]                 break;
1796ad83dc6aS[email protected]             default:
1797ad83dc6aS[email protected]                 // otherwise, just ignore as it is already in the open process
1798ad83dc6aS[email protected]                 return 0;
1799ad83dc6aS[email protected]         }
1800c8e4258aSmatthias.ringwald         conn->state = SENT_CREATE_CONNECTION;
1801c8e4258aSmatthias.ringwald     }
1802c8e4258aSmatthias.ringwald 
18037fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_reply)){
18047fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
18057fde4af9Smatthias.ringwald     }
18067fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
18077fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
18087fde4af9Smatthias.ringwald     }
18097fde4af9Smatthias.ringwald 
18108ef73945Smatthias.ringwald     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
18113a9fb326S[email protected]         if (hci_stack->remote_device_db){
18128ef73945Smatthias.ringwald             bt_flip_addr(addr, &packet[3]);
18133a9fb326S[email protected]             hci_stack->remote_device_db->delete_link_key(&addr);
18148ef73945Smatthias.ringwald         }
18158ef73945Smatthias.ringwald     }
1816c8e4258aSmatthias.ringwald 
18176724cd9eS[email protected]     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
18186724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
18196724cd9eS[email protected]         bt_flip_addr(addr, &packet[3]);
182096a45072S[email protected]         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
18216724cd9eS[email protected]         if (conn){
18226724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
18236724cd9eS[email protected]         }
18246724cd9eS[email protected]     }
18256724cd9eS[email protected] 
18266724cd9eS[email protected]     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
18276724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
18286724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
18296724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
18306724cd9eS[email protected]         bt_flip_addr(addr, &packet[3]);
183196a45072S[email protected]         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
18326724cd9eS[email protected]         if (conn){
18336724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
18346724cd9eS[email protected]         }
18356724cd9eS[email protected]     }
18366724cd9eS[email protected] 
183769a97523S[email protected] #ifdef HAVE_BLE
183869a97523S[email protected]     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
18393a9fb326S[email protected]         hci_stack->adv_addr_type = packet[8];
184069a97523S[email protected]     }
184169a97523S[email protected]     if (IS_COMMAND(packet, hci_le_set_random_address)){
18423a9fb326S[email protected]         bt_flip_addr(hci_stack->adv_address, &packet[3]);
184369a97523S[email protected]     }
184469a97523S[email protected] #endif
184569a97523S[email protected] 
18463a9fb326S[email protected]     hci_stack->num_cmd_packets--;
18476b4af23dS[email protected]     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
18486b4af23dS[email protected] 
18496b4af23dS[email protected]     // free packet buffer for synchronous transport implementations
1850c8b9416aS[email protected]     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
18516b4af23dS[email protected]         hci_stack->hci_packet_buffer_reserved = 0;
18526b4af23dS[email protected]     }
18536b4af23dS[email protected] 
18546b4af23dS[email protected]     return err;
185531452debSmatthias.ringwald }
18568adf0ddaSmatthias.ringwald 
18572bd8b7e7S[email protected] // disconnect because of security block
18582bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
18592bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
18602bd8b7e7S[email protected]     if (!connection) return;
18612bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
18622bd8b7e7S[email protected] }
18632bd8b7e7S[email protected] 
18642bd8b7e7S[email protected] 
1865dbe1a790S[email protected] // Configure Secure Simple Pairing
1866dbe1a790S[email protected] 
1867dbe1a790S[email protected] // enable will enable SSP during init
1868dbe1a790S[email protected] void hci_ssp_set_enable(int enable){
18693a9fb326S[email protected]     hci_stack->ssp_enable = enable;
1870dbe1a790S[email protected] }
1871dbe1a790S[email protected] 
18722bd8b7e7S[email protected] int hci_local_ssp_activated(){
18733a9fb326S[email protected]     return hci_ssp_supported() && hci_stack->ssp_enable;
18742bd8b7e7S[email protected] }
18752bd8b7e7S[email protected] 
1876dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
1877dbe1a790S[email protected] void hci_ssp_set_io_capability(int io_capability){
18783a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
1879dbe1a790S[email protected] }
1880dbe1a790S[email protected] void hci_ssp_set_authentication_requirement(int authentication_requirement){
18813a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
1882dbe1a790S[email protected] }
1883dbe1a790S[email protected] 
1884dbe1a790S[email protected] // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
1885dbe1a790S[email protected] void hci_ssp_set_auto_accept(int auto_accept){
18863a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
1887dbe1a790S[email protected] }
1888dbe1a790S[email protected] 
18891cd208adSmatthias.ringwald /**
18901cd208adSmatthias.ringwald  * pre: numcmds >= 0 - it's allowed to send a command to the controller
18911cd208adSmatthias.ringwald  */
1892fe35119dSmatthias.ringwald int hci_send_cmd(const hci_cmd_t *cmd, ...){
18931cd208adSmatthias.ringwald     va_list argptr;
18941cd208adSmatthias.ringwald     va_start(argptr, cmd);
18953a9fb326S[email protected]     uint16_t size = hci_create_cmd_internal(hci_stack->hci_packet_buffer, cmd, argptr);
18961cd208adSmatthias.ringwald     va_end(argptr);
18973a9fb326S[email protected]     return hci_send_cmd_packet(hci_stack->hci_packet_buffer, size);
189893b8dc03Smatthias.ringwald }
1899c8e4258aSmatthias.ringwald 
1900ee091cf1Smatthias.ringwald // Create various non-HCI events.
1901ee091cf1Smatthias.ringwald // TODO: generalize, use table similar to hci_create_command
1902ee091cf1Smatthias.ringwald 
1903c8e4258aSmatthias.ringwald void hci_emit_state(){
19043a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
1905425d1371Smatthias.ringwald     uint8_t event[3];
190680d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
1907425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
19083a9fb326S[email protected]     event[2] = hci_stack->state;
1909425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
19103a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1911c8e4258aSmatthias.ringwald }
1912c8e4258aSmatthias.ringwald 
191317f1ba2aSmatthias.ringwald void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1914425d1371Smatthias.ringwald     uint8_t event[13];
1915c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1916425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
191717f1ba2aSmatthias.ringwald     event[2] = status;
1918c8e4258aSmatthias.ringwald     bt_store_16(event, 3, conn->con_handle);
1919c8e4258aSmatthias.ringwald     bt_flip_addr(&event[5], conn->address);
1920c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
1921c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
1922425d1371Smatthias.ringwald     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
19233a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1924c8e4258aSmatthias.ringwald }
1925c8e4258aSmatthias.ringwald 
19264f3229d8S[email protected] void hci_emit_le_connection_complete(hci_connection_t *conn, uint8_t status){
19274f3229d8S[email protected]     uint8_t event[21];
19284f3229d8S[email protected]     event[0] = HCI_EVENT_LE_META;
19294f3229d8S[email protected]     event[1] = sizeof(event) - 2;
19304f3229d8S[email protected]     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
19314f3229d8S[email protected]     event[3] = status;
19324f3229d8S[email protected]     bt_store_16(event, 4, conn->con_handle);
19334f3229d8S[email protected]     event[6] = 0; // TODO: role
19344f3229d8S[email protected]     event[7] = conn->address_type;
19354f3229d8S[email protected]     bt_flip_addr(&event[8], conn->address);
19364f3229d8S[email protected]     bt_store_16(event, 14, 0); // interval
19374f3229d8S[email protected]     bt_store_16(event, 16, 0); // latency
19384f3229d8S[email protected]     bt_store_16(event, 18, 0); // supervision timeout
19394f3229d8S[email protected]     event[20] = 0; // master clock accuracy
19404f3229d8S[email protected]     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
19414f3229d8S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
19424f3229d8S[email protected] }
19434f3229d8S[email protected] 
19443c4d4b90Smatthias.ringwald void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1945425d1371Smatthias.ringwald     uint8_t event[6];
19463c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1947e518c4b8Smatthias.ringwald     event[1] = sizeof(event) - 2;
19483c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
19493c4d4b90Smatthias.ringwald     bt_store_16(event, 3, handle);
19503c4d4b90Smatthias.ringwald     event[5] = reason;
1951425d1371Smatthias.ringwald     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
19523a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
19533c4d4b90Smatthias.ringwald }
19543c4d4b90Smatthias.ringwald 
1955ee091cf1Smatthias.ringwald void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
195666fb9560S[email protected]     if (disable_l2cap_timeouts) return;
1957e0abb8e7S[email protected]     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
1958425d1371Smatthias.ringwald     uint8_t event[4];
195980d52d6bSmatthias.ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1960425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
1961ee091cf1Smatthias.ringwald     bt_store_16(event, 2, conn->con_handle);
1962425d1371Smatthias.ringwald     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
19633a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1964ee091cf1Smatthias.ringwald }
196543bfb1bdSmatthias.ringwald 
196643bfb1bdSmatthias.ringwald void hci_emit_nr_connections_changed(){
1967e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
1968425d1371Smatthias.ringwald     uint8_t event[3];
196980d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1970425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
197143bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
1972425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
19733a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
197443bfb1bdSmatthias.ringwald }
1975038bc64cSmatthias.ringwald 
1976038bc64cSmatthias.ringwald void hci_emit_hci_open_failed(){
1977e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
1978425d1371Smatthias.ringwald     uint8_t event[2];
197980d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1980425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
1981425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
19823a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1983038bc64cSmatthias.ringwald }
19841b0e3922Smatthias.ringwald 
198509ba8edeSmatthias.ringwald #ifndef EMBEDDED
19861b0e3922Smatthias.ringwald void hci_emit_btstack_version() {
1987e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
1988425d1371Smatthias.ringwald     uint8_t event[6];
19891b0e3922Smatthias.ringwald     event[0] = BTSTACK_EVENT_VERSION;
1990425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
1991425d1371Smatthias.ringwald     event[2] = BTSTACK_MAJOR;
1992425d1371Smatthias.ringwald     event[3] = BTSTACK_MINOR;
1993425d1371Smatthias.ringwald     bt_store_16(event, 4, BTSTACK_REVISION);
1994425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
19953a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
19961b0e3922Smatthias.ringwald }
199709ba8edeSmatthias.ringwald #endif
19981b0e3922Smatthias.ringwald 
19992ed6235cSmatthias.ringwald void hci_emit_system_bluetooth_enabled(uint8_t enabled){
2000e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
2001425d1371Smatthias.ringwald     uint8_t event[3];
20022ed6235cSmatthias.ringwald     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
2003425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
20042ed6235cSmatthias.ringwald     event[2] = enabled;
2005425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
20063a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
20072ed6235cSmatthias.ringwald }
2008627c2f45Smatthias.ringwald 
2009627c2f45Smatthias.ringwald void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
2010e0abb8e7S[email protected]     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
2011627c2f45Smatthias.ringwald     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
2012e0abb8e7S[email protected]     event[1] = sizeof(event) - 2 - 1;
2013f653b6bdSmatthias.ringwald     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
20142f89d309Smatthias.ringwald     bt_flip_addr(&event[3], *addr);
2015f653b6bdSmatthias.ringwald     memcpy(&event[9], name, 248);
2016e0abb8e7S[email protected] 
2017e0abb8e7S[email protected]     event[9+248] = 0;   // assert \0 for log_info
2018e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2019e0abb8e7S[email protected] 
2020e0abb8e7S[email protected]     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
20213a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2022627c2f45Smatthias.ringwald }
2023381fbed8Smatthias.ringwald 
2024381fbed8Smatthias.ringwald void hci_emit_discoverable_enabled(uint8_t enabled){
2025e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2026425d1371Smatthias.ringwald     uint8_t event[3];
2027381fbed8Smatthias.ringwald     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2028425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2029381fbed8Smatthias.ringwald     event[2] = enabled;
2030425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
20313a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2032381fbed8Smatthias.ringwald }
2033458bf4e8S[email protected] 
2034a00031e2S[email protected] void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2035df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2036a00031e2S[email protected]     uint8_t event[5];
2037e00caf9cS[email protected]     int pos = 0;
2038a00031e2S[email protected]     event[pos++] = GAP_SECURITY_LEVEL;
2039e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
2040a00031e2S[email protected]     bt_store_16(event, 2, con_handle);
2041e00caf9cS[email protected]     pos += 2;
2042e00caf9cS[email protected]     event[pos++] = level;
2043e00caf9cS[email protected]     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
20443a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2045e00caf9cS[email protected] }
2046e00caf9cS[email protected] 
2047ad83dc6aS[email protected] void hci_emit_dedicated_bonding_result(hci_connection_t * connection, uint8_t status){
2048ad83dc6aS[email protected]     log_info("hci_emit_dedicated_bonding_result %u ", status);
2049ad83dc6aS[email protected]     uint8_t event[9];
2050ad83dc6aS[email protected]     int pos = 0;
2051ad83dc6aS[email protected]     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2052ad83dc6aS[email protected]     event[pos++] = sizeof(event) - 2;
2053ad83dc6aS[email protected]     event[pos++] = status;
2054ad83dc6aS[email protected]     bt_flip_addr( * (bd_addr_t *) &event[pos], connection->address);
2055ad83dc6aS[email protected]     pos += 6;
2056ad83dc6aS[email protected]     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
20573a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2058ad83dc6aS[email protected] }
2059ad83dc6aS[email protected] 
20602bd8b7e7S[email protected] // query if remote side supports SSP
20612bd8b7e7S[email protected] int hci_remote_ssp_supported(hci_con_handle_t con_handle){
20622bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
20632bd8b7e7S[email protected]     if (!connection) return 0;
20642bd8b7e7S[email protected]     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
20652bd8b7e7S[email protected] }
20662bd8b7e7S[email protected] 
2067df3354fcS[email protected] int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2068df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2069df3354fcS[email protected] }
2070df3354fcS[email protected] 
2071458bf4e8S[email protected] // GAP API
2072458bf4e8S[email protected] /**
2073458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
2074458bf4e8S[email protected]  * @praram enabled
2075458bf4e8S[email protected]  */
20764c57c146S[email protected] void gap_set_bondable_mode(int enable){
20773a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
2078458bf4e8S[email protected] }
2079cb230b9dS[email protected] 
2080cb230b9dS[email protected] /**
208134d2123cS[email protected]  * @brief map link keys to security levels
2082cb230b9dS[email protected]  */
208334d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
208434d2123cS[email protected]     switch (link_key_type){
20853c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
20863c68dfa9S[email protected]             return LEVEL_4;
20873c68dfa9S[email protected]         case COMBINATION_KEY:
20883c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
20893c68dfa9S[email protected]             return LEVEL_3;
20903c68dfa9S[email protected]         default:
20913c68dfa9S[email protected]             return LEVEL_2;
20923c68dfa9S[email protected]     }
2093cb230b9dS[email protected] }
2094cb230b9dS[email protected] 
2095a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
209634d2123cS[email protected]     if (!connection) return LEVEL_0;
209734d2123cS[email protected]     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
209834d2123cS[email protected]     return gap_security_level_for_link_key_type(connection->link_key_type);
209934d2123cS[email protected] }
210034d2123cS[email protected] 
210134d2123cS[email protected] 
2102106d6d11S[email protected] int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
210382d8f825S[email protected]     printf("gap_mitm_protection_required_for_security_level %u\n", level);
2104106d6d11S[email protected]     return level > LEVEL_2;
2105106d6d11S[email protected] }
2106106d6d11S[email protected] 
210734d2123cS[email protected] /**
210834d2123cS[email protected]  * @brief get current security level
210934d2123cS[email protected]  */
211034d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
211134d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
211234d2123cS[email protected]     if (!connection) return LEVEL_0;
211334d2123cS[email protected]     return gap_security_level_for_connection(connection);
211434d2123cS[email protected] }
211534d2123cS[email protected] 
2116cb230b9dS[email protected] /**
2117cb230b9dS[email protected]  * @brief request connection to device to
2118cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
2119cb230b9dS[email protected]  */
212034d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
212134d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
212234d2123cS[email protected]     if (!connection){
2123a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
212434d2123cS[email protected]         return;
212534d2123cS[email protected]     }
212634d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
212734d2123cS[email protected]     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
212834d2123cS[email protected]     if (current_level >= requested_level){
2129a00031e2S[email protected]         hci_emit_security_level(con_handle, current_level);
213034d2123cS[email protected]         return;
213134d2123cS[email protected]     }
2132a00031e2S[email protected] 
213334d2123cS[email protected]     connection->requested_security_level = requested_level;
2134a00031e2S[email protected] 
2135fb8ba0dbS[email protected]     // would enabling ecnryption suffice (>= LEVEL_2)?
21363a9fb326S[email protected]     if (hci_stack->remote_device_db){
2137a00031e2S[email protected]         link_key_type_t link_key_type;
2138a00031e2S[email protected]         link_key_t      link_key;
21393a9fb326S[email protected]         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2140a00031e2S[email protected]             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2141a00031e2S[email protected]                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2142a00031e2S[email protected]                 return;
2143a00031e2S[email protected]             }
2144a00031e2S[email protected]         }
2145a00031e2S[email protected]     }
2146a00031e2S[email protected] 
21471eb2563eS[email protected]     // try to authenticate connection
21481eb2563eS[email protected]     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2149e80b2cf9S[email protected]     hci_run();
2150e00caf9cS[email protected] }
2151ad83dc6aS[email protected] 
2152ad83dc6aS[email protected] /**
2153ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
2154ad83dc6aS[email protected]  * @param device
2155ad83dc6aS[email protected]  * @param request MITM protection
2156ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
2157ad83dc6aS[email protected]  */
2158ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2159ad83dc6aS[email protected] 
2160ad83dc6aS[email protected]     // create connection state machine
216196a45072S[email protected]     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2162ad83dc6aS[email protected] 
2163ad83dc6aS[email protected]     if (!connection){
2164ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
2165ad83dc6aS[email protected]     }
2166ad83dc6aS[email protected] 
2167ad83dc6aS[email protected]     // delete linkn key
2168ad83dc6aS[email protected]     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2169ad83dc6aS[email protected] 
2170ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
2171ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
2172ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
217382d8f825S[email protected]     printf("gap_dedicated_bonding, mitm %u -> level %u\n", mitm_protection_required, connection->requested_security_level);
2174ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
2175ad83dc6aS[email protected] 
2176ad83dc6aS[email protected]     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2177ad83dc6aS[email protected] 
2178ad83dc6aS[email protected]     // handle: connnection failure (connection complete != ok)
2179ad83dc6aS[email protected]     // handle: authentication failure
2180ad83dc6aS[email protected]     // handle: disconnect on done
2181ad83dc6aS[email protected] 
2182ad83dc6aS[email protected]     hci_run();
2183ad83dc6aS[email protected] 
2184ad83dc6aS[email protected]     return 0;
2185ad83dc6aS[email protected] }
21868e618f72S[email protected] 
21878e618f72S[email protected] void gap_set_local_name(const char * local_name){
21888e618f72S[email protected]     hci_stack->local_name = local_name;
21898e618f72S[email protected] }
21908e618f72S[email protected] 
21917bdc6798S[email protected] le_command_status_t le_central_start_scan(){
219236af3e18S[email protected]     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
21937bdc6798S[email protected]     hci_stack->le_scanning_state = LE_START_SCAN;
21947bdc6798S[email protected]     hci_run();
21957bdc6798S[email protected]     return BLE_PERIPHERAL_OK;
21967bdc6798S[email protected] }
21978e618f72S[email protected] 
21987bdc6798S[email protected] le_command_status_t le_central_stop_scan(){
219936af3e18S[email protected]     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
22007bdc6798S[email protected]     hci_stack->le_scanning_state = LE_STOP_SCAN;
22017bdc6798S[email protected]     hci_run();
22027bdc6798S[email protected]     return BLE_PERIPHERAL_OK;
22037bdc6798S[email protected] }
22044f3229d8S[email protected] 
22054f3229d8S[email protected] 
22064f3229d8S[email protected] le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
22074f3229d8S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2208564fca32S[email protected]     log_info("le_central_connect, conn struct %p", conn);
22094f3229d8S[email protected]     if (!conn){
22104f3229d8S[email protected]         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
22114f3229d8S[email protected]         if (!conn){
22124f3229d8S[email protected]             // notify client that alloc failed
22134f3229d8S[email protected]             hci_emit_le_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
22144f3229d8S[email protected]             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
22154f3229d8S[email protected]         }
22164f3229d8S[email protected]         conn->state = SEND_CREATE_CONNECTION;
2217564fca32S[email protected]         log_info("le_central_connect, state %u", conn->state);
2218564fca32S[email protected]         hci_run();
22194f3229d8S[email protected]         return BLE_PERIPHERAL_OK;
22204f3229d8S[email protected]     }
22210bf6344aS[email protected] 
22220bf6344aS[email protected]     if (!hci_is_le_connection(conn) ||
22230bf6344aS[email protected]         conn->state == SEND_CREATE_CONNECTION ||
22240bf6344aS[email protected]         conn->state == SENT_CREATE_CONNECTION) {
22250bf6344aS[email protected]         hci_emit_le_connection_complete(conn, ERROR_CODE_COMMAND_DISALLOWED);
22260bf6344aS[email protected]         return BLE_PERIPHERAL_IN_WRONG_STATE;
22270bf6344aS[email protected]     }
22280bf6344aS[email protected] 
2229564fca32S[email protected]     log_info("le_central_connect, state %u", conn->state);
22304f3229d8S[email protected]     hci_emit_le_connection_complete(conn, 0);
22314f3229d8S[email protected]     hci_run();
22324f3229d8S[email protected]     return BLE_PERIPHERAL_OK;
22334f3229d8S[email protected] }
22344f3229d8S[email protected] 
2235*7851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
2236*7851196eSmatthias.ringwald static hci_connection_t * le_central_get_outgoing_connection(){
22370bf6344aS[email protected]     linked_item_t *it;
22380bf6344aS[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
22390bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
22400bf6344aS[email protected]         if (!hci_is_le_connection(conn)) continue;
22410bf6344aS[email protected]         switch (conn->state){
2242a6725849S[email protected]             case SEND_CREATE_CONNECTION:
2243*7851196eSmatthias.ringwald             case SENT_CREATE_CONNECTION:
2244*7851196eSmatthias.ringwald                 return conn;
2245*7851196eSmatthias.ringwald             default:
2246*7851196eSmatthias.ringwald                 break;
2247*7851196eSmatthias.ringwald         };
2248*7851196eSmatthias.ringwald     }
2249*7851196eSmatthias.ringwald     return NULL;
2250*7851196eSmatthias.ringwald }
2251*7851196eSmatthias.ringwald 
2252*7851196eSmatthias.ringwald le_command_status_t le_central_connect_cancel(){
2253*7851196eSmatthias.ringwald     hci_connection_t * conn = le_central_get_outgoing_connection();
2254*7851196eSmatthias.ringwald     switch (conn->state){
2255*7851196eSmatthias.ringwald         case SEND_CREATE_CONNECTION:
2256*7851196eSmatthias.ringwald             // skip sending create connection and emit event instead
22570bf6344aS[email protected]             hci_emit_le_connection_complete(conn, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
2258*7851196eSmatthias.ringwald             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
2259*7851196eSmatthias.ringwald             btstack_memory_hci_connection_free( conn );
22600bf6344aS[email protected]             break;
2261a6725849S[email protected]         case SENT_CREATE_CONNECTION:
2262*7851196eSmatthias.ringwald             // request to send cancel connection
22630bf6344aS[email protected]             conn->state = SEND_CANCEL_CONNECTION;
22640bf6344aS[email protected]             hci_run();
22650bf6344aS[email protected]             break;
22660bf6344aS[email protected]         default:
22670bf6344aS[email protected]             break;
22680bf6344aS[email protected]     }
2269e31f89a7S[email protected]     return BLE_PERIPHERAL_OK;
2270e31f89a7S[email protected] }
22714f3229d8S[email protected] 
22725917a5c5S[email protected] le_command_status_t gap_disconnect(hci_con_handle_t handle){
22735917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
22745917a5c5S[email protected]     if (!conn){
2275*7851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
22765917a5c5S[email protected]         return BLE_PERIPHERAL_OK;
22775917a5c5S[email protected]     }
22785917a5c5S[email protected]     conn->state = SEND_DISCONNECT;
22795917a5c5S[email protected]     hci_run();
22804f3229d8S[email protected]     return BLE_PERIPHERAL_OK;
22814f3229d8S[email protected] }
2282