xref: /btstack/src/hci.c (revision 6c26b087476c4858600668a8fc09217a9cc8ecff)
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
693d7a3f67S[email protected] #include "../platforms/ios/src/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);
767586ee35S[email protected] static int  hci_power_control_on(void);
777586ee35S[email protected] static void hci_power_control_off(void);
786155b3d3S[email protected] static void hci_state_reset();
79758b46ceSmatthias.ringwald 
8006b35ec0Smatthias.ringwald // the STACK is here
813a9fb326S[email protected] #ifndef HAVE_MALLOC
823a9fb326S[email protected] static hci_stack_t   hci_stack_static;
833a9fb326S[email protected] #endif
843a9fb326S[email protected] static hci_stack_t * hci_stack = NULL;
8516833f0aSmatthias.ringwald 
8666fb9560S[email protected] // test helper
8766fb9560S[email protected] static uint8_t disable_l2cap_timeouts = 0;
8866fb9560S[email protected] 
8996a45072S[email protected] /**
9096a45072S[email protected]  * create connection for given address
9196a45072S[email protected]  *
9296a45072S[email protected]  * @return connection OR NULL, if no memory left
9396a45072S[email protected]  */
9496a45072S[email protected] static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
9596a45072S[email protected] 
965127cc62S[email protected]     log_info("create_connection_for_addr %s", bd_addr_to_str(addr));
97bb69aaaeS[email protected]     hci_connection_t * conn = btstack_memory_hci_connection_get();
9896a45072S[email protected]     if (!conn) return NULL;
9996a45072S[email protected]     BD_ADDR_COPY(conn->address, addr);
10096a45072S[email protected]     conn->address_type = addr_type;
10196a45072S[email protected]     conn->con_handle = 0xffff;
10296a45072S[email protected]     conn->authentication_flags = AUTH_FLAGS_NONE;
10396a45072S[email protected]     conn->bonding_flags = 0;
10496a45072S[email protected]     conn->requested_security_level = LEVEL_0;
10596a45072S[email protected]     linked_item_set_user(&conn->timeout.item, conn);
10696a45072S[email protected]     conn->timeout.process = hci_connection_timeout_handler;
10796a45072S[email protected]     hci_connection_timestamp(conn);
10896a45072S[email protected]     conn->acl_recombination_length = 0;
10996a45072S[email protected]     conn->acl_recombination_pos = 0;
11096a45072S[email protected]     conn->num_acl_packets_sent = 0;
11196a45072S[email protected]     linked_list_add(&hci_stack->connections, (linked_item_t *) conn);
11296a45072S[email protected]     return conn;
11396a45072S[email protected] }
11466fb9560S[email protected] 
11597addcc5Smatthias.ringwald /**
116ee091cf1Smatthias.ringwald  * get connection for a given handle
117ee091cf1Smatthias.ringwald  *
118ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
119ee091cf1Smatthias.ringwald  */
1205061f3afS[email protected] hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
121ee091cf1Smatthias.ringwald     linked_item_t *it;
1223a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
123ee091cf1Smatthias.ringwald         if ( ((hci_connection_t *) it)->con_handle == con_handle){
124ee091cf1Smatthias.ringwald             return (hci_connection_t *) it;
125ee091cf1Smatthias.ringwald         }
126ee091cf1Smatthias.ringwald     }
127ee091cf1Smatthias.ringwald     return NULL;
128ee091cf1Smatthias.ringwald }
129ee091cf1Smatthias.ringwald 
13096a45072S[email protected] /**
13196a45072S[email protected]  * get connection for given address
13296a45072S[email protected]  *
13396a45072S[email protected]  * @return connection OR NULL, if not found
13496a45072S[email protected]  */
13596a45072S[email protected] hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t * addr, bd_addr_type_t addr_type){
13662bda3fbS[email protected]     linked_item_t *it;
13762bda3fbS[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
13862bda3fbS[email protected]         hci_connection_t * connection = (hci_connection_t *) it;
13996a45072S[email protected]         if (connection->address_type != addr_type)  continue;
14096a45072S[email protected]         if (memcmp(addr, connection->address, 6) != 0) continue;
14162bda3fbS[email protected]         return connection;
14262bda3fbS[email protected]     }
14362bda3fbS[email protected]     return NULL;
14462bda3fbS[email protected] }
14562bda3fbS[email protected] 
1462b12a0b9Smatthias.ringwald static void hci_connection_timeout_handler(timer_source_t *timer){
14728ca2b46S[email protected]     hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item);
148c785ef68Smatthias.ringwald #ifdef HAVE_TIME
149ee091cf1Smatthias.ringwald     struct timeval tv;
150ee091cf1Smatthias.ringwald     gettimeofday(&tv, NULL);
151c21e6239Smatthias.ringwald     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
152ee091cf1Smatthias.ringwald         // connections might be timed out
153ee091cf1Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
154ee091cf1Smatthias.ringwald     }
1552b12a0b9Smatthias.ringwald #endif
156e5780900Smatthias.ringwald #ifdef HAVE_TICK
157c785ef68Smatthias.ringwald     if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
158c785ef68Smatthias.ringwald         // connections might be timed out
159c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
160c785ef68Smatthias.ringwald     }
161c785ef68Smatthias.ringwald #endif
162c785ef68Smatthias.ringwald     run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
163c785ef68Smatthias.ringwald     run_loop_add_timer(timer);
164c785ef68Smatthias.ringwald }
165ee091cf1Smatthias.ringwald 
166ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
167c7492964Smatthias.ringwald #ifdef HAVE_TIME
168ee091cf1Smatthias.ringwald     gettimeofday(&connection->timestamp, NULL);
169c7492964Smatthias.ringwald #endif
170e5780900Smatthias.ringwald #ifdef HAVE_TICK
171c785ef68Smatthias.ringwald     connection->timestamp = embedded_get_ticks();
172c785ef68Smatthias.ringwald #endif
173ee091cf1Smatthias.ringwald }
174ee091cf1Smatthias.ringwald 
17506b35ec0Smatthias.ringwald 
17628ca2b46S[email protected] inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
17728ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
17828ca2b46S[email protected] }
17928ca2b46S[email protected] 
18028ca2b46S[email protected] inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
18128ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
18228ca2b46S[email protected] }
18328ca2b46S[email protected] 
18428ca2b46S[email protected] 
18543bfb1bdSmatthias.ringwald /**
18680ca58a0Smatthias.ringwald  * add authentication flags and reset timer
18796a45072S[email protected]  * @note: assumes classic connection
1887fde4af9Smatthias.ringwald  */
1897fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
1907fde4af9Smatthias.ringwald     bd_addr_t addr;
1917fde4af9Smatthias.ringwald     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
19296a45072S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1937fde4af9Smatthias.ringwald     if (conn) {
19428ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
19580ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
1967fde4af9Smatthias.ringwald     }
1977fde4af9Smatthias.ringwald }
1987fde4af9Smatthias.ringwald 
19980ca58a0Smatthias.ringwald int  hci_authentication_active_for_handle(hci_con_handle_t handle){
2005061f3afS[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
20180ca58a0Smatthias.ringwald     if (!conn) return 0;
2026724cd9eS[email protected]     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
2036724cd9eS[email protected]     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
2046724cd9eS[email protected]     return 0;
20580ca58a0Smatthias.ringwald }
20680ca58a0Smatthias.ringwald 
207c12e46e7Smatthias.ringwald void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
2083a9fb326S[email protected]     if (hci_stack->remote_device_db) {
2093a9fb326S[email protected]         hci_stack->remote_device_db->delete_link_key(addr);
210c12e46e7Smatthias.ringwald     }
211c12e46e7Smatthias.ringwald }
212c12e46e7Smatthias.ringwald 
2130bf6344aS[email protected] int hci_is_le_connection(hci_connection_t * connection){
2140bf6344aS[email protected]     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
2150bf6344aS[email protected]     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
2160bf6344aS[email protected] }
2170bf6344aS[email protected] 
2187fde4af9Smatthias.ringwald 
2197fde4af9Smatthias.ringwald /**
22043bfb1bdSmatthias.ringwald  * count connections
22143bfb1bdSmatthias.ringwald  */
22240d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
22356c253c9Smatthias.ringwald     int count = 0;
22443bfb1bdSmatthias.ringwald     linked_item_t *it;
2253a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
22643bfb1bdSmatthias.ringwald     return count;
22743bfb1bdSmatthias.ringwald }
228c8e4258aSmatthias.ringwald 
22997addcc5Smatthias.ringwald /**
230ba681a6cSmatthias.ringwald  * Dummy handler called by HCI
23116833f0aSmatthias.ringwald  */
2322718e2e7Smatthias.ringwald static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
23316833f0aSmatthias.ringwald }
23416833f0aSmatthias.ringwald 
235998906cdSmatthias.ringwald uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
2365061f3afS[email protected]     hci_connection_t * connection = hci_connection_for_handle(handle);
237998906cdSmatthias.ringwald     if (!connection) {
2389da54300S[email protected]         log_error("hci_number_outgoing_packets: connection for handle %u does not exist!", handle);
239998906cdSmatthias.ringwald         return 0;
240998906cdSmatthias.ringwald     }
241998906cdSmatthias.ringwald     return connection->num_acl_packets_sent;
242998906cdSmatthias.ringwald }
243998906cdSmatthias.ringwald 
244e79abdd6S[email protected] uint8_t hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
245ee303eddS[email protected] 
246ee303eddS[email protected]     int num_packets_sent_classic = 0;
247ee303eddS[email protected]     int num_packets_sent_le = 0;
248ee303eddS[email protected] 
249ee303eddS[email protected]     bd_addr_type_t address_type = BD_ADDR_TYPE_UNKNOWN;
250ee303eddS[email protected] 
251998906cdSmatthias.ringwald     linked_item_t *it;
2523a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
253998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
254ee303eddS[email protected]         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
255ee303eddS[email protected]             num_packets_sent_classic += connection->num_acl_packets_sent;
256ee303eddS[email protected]         } else {
257ee303eddS[email protected]             num_packets_sent_le += connection->num_acl_packets_sent;
258ee303eddS[email protected]         }
259ee303eddS[email protected]         if (connection->con_handle == con_handle){
260ee303eddS[email protected]             address_type = connection->address_type;
261ee303eddS[email protected]         }
262ee303eddS[email protected]     }
263ee303eddS[email protected] 
264ee303eddS[email protected]     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
265ee303eddS[email protected]     int free_slots_le = 0;
266ee303eddS[email protected] 
267ee303eddS[email protected]     if (free_slots_classic < 0){
2689da54300S[email protected]         log_error("hci_number_free_acl_slots: outgoing classic packets (%u) > total classic packets (%u)", num_packets_sent_classic, hci_stack->acl_packets_total_num);
269998906cdSmatthias.ringwald         return 0;
270998906cdSmatthias.ringwald     }
271ee303eddS[email protected] 
272ee303eddS[email protected]     if (hci_stack->le_acl_packets_total_num){
273ee303eddS[email protected]         // if we have LE slots, they are used
274ee303eddS[email protected]         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
275ee303eddS[email protected]         if (free_slots_le < 0){
2769da54300S[email protected]             log_error("hci_number_free_acl_slots: outgoing le packets (%u) > total le packets (%u)", num_packets_sent_le, hci_stack->le_acl_packets_total_num);
277ee303eddS[email protected]             return 0;
278998906cdSmatthias.ringwald         }
279ee303eddS[email protected]     } else {
280ee303eddS[email protected]         // otherwise, classic slots are used for LE, too
281ee303eddS[email protected]         free_slots_classic -= num_packets_sent_le;
282ee303eddS[email protected]         if (free_slots_classic < 0){
2839da54300S[email protected]             log_error("hci_number_free_acl_slots: outgoing classic + le packets (%u + %u) > total packets (%u)", num_packets_sent_classic, num_packets_sent_le, hci_stack->acl_packets_total_num);
284ee303eddS[email protected]             return 0;
285ee303eddS[email protected]         }
286ee303eddS[email protected]     }
287ee303eddS[email protected] 
288ee303eddS[email protected]     switch (address_type){
289ee303eddS[email protected]         case BD_ADDR_TYPE_UNKNOWN:
2909da54300S[email protected]             log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
291ee303eddS[email protected]             return 0;
292ee303eddS[email protected] 
293ee303eddS[email protected]         case BD_ADDR_TYPE_CLASSIC:
294ee303eddS[email protected]             return free_slots_classic;
295ee303eddS[email protected] 
296ee303eddS[email protected]         default:
297cb00d3aaS[email protected]            if (hci_stack->le_acl_packets_total_num){
298ee303eddS[email protected]                return free_slots_le;
299ee303eddS[email protected]            }
300cb00d3aaS[email protected]            return free_slots_classic;
301cb00d3aaS[email protected]     }
302998906cdSmatthias.ringwald }
303998906cdSmatthias.ringwald 
304ac928cc2S[email protected] 
305ac928cc2S[email protected] // @deprecated
306c24735b1Smatthias.ringwald int hci_can_send_packet_now(uint8_t packet_type){
307c24735b1Smatthias.ringwald     switch (packet_type) {
308c24735b1Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
309ac928cc2S[email protected]             return hci_can_send_prepared_acl_packet_now(0);
310c24735b1Smatthias.ringwald         case HCI_COMMAND_DATA_PACKET:
311ac928cc2S[email protected]             return hci_can_send_command_packet_now();
312c24735b1Smatthias.ringwald         default:
313c24735b1Smatthias.ringwald             return 0;
314c24735b1Smatthias.ringwald     }
315c24735b1Smatthias.ringwald }
316c24735b1Smatthias.ringwald 
317ac928cc2S[email protected] // @deprecated
3186b4af23dS[email protected] // same as hci_can_send_packet_now, but also checks if packet buffer is free for use
3196b4af23dS[email protected] int hci_can_send_packet_now_using_packet_buffer(uint8_t packet_type){
320ac928cc2S[email protected] 
3216b4af23dS[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
322ac928cc2S[email protected] 
323ac928cc2S[email protected]     switch (packet_type) {
324ac928cc2S[email protected]         case HCI_ACL_DATA_PACKET:
325ac928cc2S[email protected]             return hci_can_send_acl_packet_now(0);
326ac928cc2S[email protected]         case HCI_COMMAND_DATA_PACKET:
327ac928cc2S[email protected]             return hci_can_send_command_packet_now();
328ac928cc2S[email protected]         default:
329ac928cc2S[email protected]             return 0;
330ac928cc2S[email protected]     }
331ac928cc2S[email protected] }
332ac928cc2S[email protected] 
333ac928cc2S[email protected] 
334ac928cc2S[email protected] // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
335ac928cc2S[email protected] int hci_can_send_command_packet_now(void){
336ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
337ac928cc2S[email protected] 
338ac928cc2S[email protected]     // check for async hci transport implementations
339ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
340ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
341ac928cc2S[email protected]             return 0;
342ac928cc2S[email protected]         }
343ac928cc2S[email protected]     }
344ac928cc2S[email protected] 
345ac928cc2S[email protected]     return hci_stack->num_cmd_packets > 0;
346ac928cc2S[email protected] }
347ac928cc2S[email protected] 
348ac928cc2S[email protected] int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
349ac928cc2S[email protected]     // check for async hci transport implementations
350ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
351ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_ACL_DATA_PACKET)){
352ac928cc2S[email protected]             return 0;
353ac928cc2S[email protected]         }
354ac928cc2S[email protected]     }
355e79abdd6S[email protected]     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
356ac928cc2S[email protected] }
357ac928cc2S[email protected] 
358ac928cc2S[email protected] int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
359ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
360ac928cc2S[email protected]     return hci_can_send_prepared_acl_packet_now(con_handle);
3616b4af23dS[email protected] }
3626b4af23dS[email protected] 
363c8b9416aS[email protected] // used for internal checks in l2cap[-le].c
364c8b9416aS[email protected] int hci_is_packet_buffer_reserved(void){
365c8b9416aS[email protected]     return hci_stack->hci_packet_buffer_reserved;
366c8b9416aS[email protected] }
367c8b9416aS[email protected] 
3686b4af23dS[email protected] // reserves outgoing packet buffer. @returns 1 if successful
3696b4af23dS[email protected] int hci_reserve_packet_buffer(void){
3709d14b626S[email protected]     if (hci_stack->hci_packet_buffer_reserved) {
3719d14b626S[email protected]         log_error("hci_reserve_packet_buffer called but buffer already reserved");
3729d14b626S[email protected]         return 0;
3739d14b626S[email protected]     }
3746b4af23dS[email protected]     hci_stack->hci_packet_buffer_reserved = 1;
3756b4af23dS[email protected]     return 1;
3766b4af23dS[email protected] }
3776b4af23dS[email protected] 
37868a0fcf7S[email protected] void hci_release_packet_buffer(void){
37968a0fcf7S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
38068a0fcf7S[email protected] }
38168a0fcf7S[email protected] 
3826b4af23dS[email protected] // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
3836b4af23dS[email protected] int hci_transport_synchronous(void){
3846b4af23dS[email protected]     return hci_stack->hci_transport->can_send_packet_now == NULL;
3856b4af23dS[email protected] }
3866b4af23dS[email protected] 
387*6c26b087S[email protected] uint16_t hci_max_acl_le_data_packet_length(void){
388*6c26b087S[email protected]     return hci_stack->le_data_packets_length > 0 ? hci_stack->le_data_packets_length : hci_stack->acl_data_packet_length;
389*6c26b087S[email protected] }
390*6c26b087S[email protected] 
391452cf3bbS[email protected] static int hci_send_acl_packet_fragments(hci_connection_t *connection){
392452cf3bbS[email protected] 
393452cf3bbS[email protected]     // log_info("hci_send_acl_packet_fragments  %u/%u (con 0x%04x)", hci_stack->acl_fragmentation_pos, hci_stack->acl_fragmentation_total_size, connection->con_handle);
394452cf3bbS[email protected] 
395452cf3bbS[email protected]     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
396452cf3bbS[email protected]     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
397452cf3bbS[email protected]     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
398452cf3bbS[email protected]         max_acl_data_packet_length = hci_stack->le_data_packets_length;
399452cf3bbS[email protected]     }
400452cf3bbS[email protected] 
401452cf3bbS[email protected]     // testing: reduce buffer to minimum
402452cf3bbS[email protected]     // max_acl_data_packet_length = 52;
403452cf3bbS[email protected] 
404452cf3bbS[email protected]     int err;
405452cf3bbS[email protected]     // multiple packets could be send on a synchronous HCI transport
406452cf3bbS[email protected]     while (1){
407452cf3bbS[email protected] 
408452cf3bbS[email protected]         // get current data
409452cf3bbS[email protected]         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
410452cf3bbS[email protected]         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
411452cf3bbS[email protected]         int more_fragments = 0;
412452cf3bbS[email protected] 
413452cf3bbS[email protected]         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
414452cf3bbS[email protected]         if (current_acl_data_packet_length > max_acl_data_packet_length){
415452cf3bbS[email protected]             more_fragments = 1;
416452cf3bbS[email protected]             current_acl_data_packet_length = max_acl_data_packet_length;
417452cf3bbS[email protected]         }
418452cf3bbS[email protected] 
419452cf3bbS[email protected]         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
420452cf3bbS[email protected]         if (acl_header_pos > 0){
421452cf3bbS[email protected]             uint16_t handle_and_flags = READ_BT_16(hci_stack->hci_packet_buffer, 0);
422452cf3bbS[email protected]             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
423452cf3bbS[email protected]             bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
424452cf3bbS[email protected]         }
425452cf3bbS[email protected] 
426452cf3bbS[email protected]         // update header len
427452cf3bbS[email protected]         bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
428452cf3bbS[email protected] 
429452cf3bbS[email protected]         // count packet
430452cf3bbS[email protected]         connection->num_acl_packets_sent++;
431452cf3bbS[email protected] 
432452cf3bbS[email protected]         // send packet
433452cf3bbS[email protected]         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
434452cf3bbS[email protected]         const int size = current_acl_data_packet_length + 4;
435452cf3bbS[email protected]         // hexdump(packet, size);
436452cf3bbS[email protected]         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
437452cf3bbS[email protected] 
438452cf3bbS[email protected]         // done yet?
439452cf3bbS[email protected]         if (!more_fragments) break;
440452cf3bbS[email protected] 
441452cf3bbS[email protected]         // update start of next fragment to send
442452cf3bbS[email protected]         hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
443452cf3bbS[email protected] 
444452cf3bbS[email protected]         // can send more?
445452cf3bbS[email protected]         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
446452cf3bbS[email protected]     }
447452cf3bbS[email protected] 
448452cf3bbS[email protected]     // done
449452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 0;
450452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = 0;
451452cf3bbS[email protected] 
452452cf3bbS[email protected]     // free buffer now for synchronous transport
453452cf3bbS[email protected]     if (!hci_transport_synchronous()){
454452cf3bbS[email protected]         hci_release_packet_buffer();
455452cf3bbS[email protected]     }
456452cf3bbS[email protected] 
457452cf3bbS[email protected]     return err;
458452cf3bbS[email protected] }
459452cf3bbS[email protected] 
460826f7347S[email protected] // pre: caller has reserved the packet buffer
461826f7347S[email protected] int hci_send_acl_packet_buffer(int size){
4627856c818Smatthias.ringwald 
463452cf3bbS[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
464452cf3bbS[email protected] 
465826f7347S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
466826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
467826f7347S[email protected]         return 0;
468826f7347S[email protected]     }
469826f7347S[email protected] 
470d713a683S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
471d713a683S[email protected]     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
472d713a683S[email protected] 
473826f7347S[email protected]     // check for free places on Bluetooth module
474d713a683S[email protected]     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
475826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
47697b61c7bS[email protected]         hci_release_packet_buffer();
47797b61c7bS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
47897b61c7bS[email protected]     }
4796218e6f1Smatthias.ringwald 
4805061f3afS[email protected]     hci_connection_t *connection = hci_connection_for_handle( con_handle);
48197b61c7bS[email protected]     if (!connection) {
4825fa0b7cfS[email protected]         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
48397b61c7bS[email protected]         hci_release_packet_buffer();
48497b61c7bS[email protected]         return 0;
48597b61c7bS[email protected]     }
48656cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
48756cf178bSmatthias.ringwald 
488452cf3bbS[email protected]     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
4897856c818Smatthias.ringwald 
490452cf3bbS[email protected]     // setup data
491452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = size;
492452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
4936218e6f1Smatthias.ringwald 
494452cf3bbS[email protected]     return hci_send_acl_packet_fragments(connection);
495ee091cf1Smatthias.ringwald }
496ee091cf1Smatthias.ringwald 
49716833f0aSmatthias.ringwald static void acl_handler(uint8_t *packet, int size){
4987856c818Smatthias.ringwald 
499e76a89eeS[email protected]     // log_info("acl_handler: size %u", size);
500e76a89eeS[email protected] 
5017856c818Smatthias.ringwald     // get info
5027856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
5035061f3afS[email protected]     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
5047856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
5057856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
5067856c818Smatthias.ringwald 
5077856c818Smatthias.ringwald     // ignore non-registered handle
5087856c818Smatthias.ringwald     if (!conn){
5099da54300S[email protected]         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
5107856c818Smatthias.ringwald         return;
5117856c818Smatthias.ringwald     }
5127856c818Smatthias.ringwald 
513e76a89eeS[email protected]     // assert packet is complete
5149ecc3e17S[email protected]     if (acl_length + 4 != size){
515e76a89eeS[email protected]         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
516e76a89eeS[email protected]         return;
517e76a89eeS[email protected]     }
518e76a89eeS[email protected] 
5197856c818Smatthias.ringwald     // update idle timestamp
5207856c818Smatthias.ringwald     hci_connection_timestamp(conn);
5217856c818Smatthias.ringwald 
5227856c818Smatthias.ringwald     // handle different packet types
5237856c818Smatthias.ringwald     switch (acl_flags & 0x03) {
5247856c818Smatthias.ringwald 
5257856c818Smatthias.ringwald         case 0x01: // continuation fragment
5267856c818Smatthias.ringwald 
5277856c818Smatthias.ringwald             // sanity check
5287856c818Smatthias.ringwald             if (conn->acl_recombination_pos == 0) {
5299da54300S[email protected]                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
5307856c818Smatthias.ringwald                 return;
5317856c818Smatthias.ringwald             }
5327856c818Smatthias.ringwald 
5337856c818Smatthias.ringwald             // append fragment payload (header already stored)
5347856c818Smatthias.ringwald             memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length );
5357856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
5367856c818Smatthias.ringwald 
5379da54300S[email protected]             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
538decc01a8Smatthias.ringwald             //        conn->acl_recombination_pos, conn->acl_recombination_length);
5397856c818Smatthias.ringwald 
5407856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
5417856c818Smatthias.ringwald             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
5427856c818Smatthias.ringwald 
5433a9fb326S[email protected]                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos);
5447856c818Smatthias.ringwald                 // reset recombination buffer
5457856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
5467856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
5477856c818Smatthias.ringwald             }
5487856c818Smatthias.ringwald             break;
5497856c818Smatthias.ringwald 
5507856c818Smatthias.ringwald         case 0x02: { // first fragment
5517856c818Smatthias.ringwald 
5527856c818Smatthias.ringwald             // sanity check
5537856c818Smatthias.ringwald             if (conn->acl_recombination_pos) {
5549da54300S[email protected]                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x", con_handle);
5557856c818Smatthias.ringwald                 return;
5567856c818Smatthias.ringwald             }
5577856c818Smatthias.ringwald 
5587856c818Smatthias.ringwald             // peek into L2CAP packet!
5597856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
5607856c818Smatthias.ringwald 
5619da54300S[email protected]             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
562decc01a8Smatthias.ringwald 
5637856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
5647856c818Smatthias.ringwald             if (acl_length >= l2cap_length + 4){
5657856c818Smatthias.ringwald 
5667856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
5673a9fb326S[email protected]                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
5687856c818Smatthias.ringwald 
5697856c818Smatthias.ringwald             } else {
5707856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
5717856c818Smatthias.ringwald                 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4);
5727856c818Smatthias.ringwald                 conn->acl_recombination_pos    = acl_length + 4;
5737856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
574decc01a8Smatthias.ringwald                 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4);
5757856c818Smatthias.ringwald             }
5767856c818Smatthias.ringwald             break;
5777856c818Smatthias.ringwald 
5787856c818Smatthias.ringwald         }
5797856c818Smatthias.ringwald         default:
5809da54300S[email protected]             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
5817856c818Smatthias.ringwald             return;
5827856c818Smatthias.ringwald     }
58394ab26f8Smatthias.ringwald 
58494ab26f8Smatthias.ringwald     // execute main loop
58594ab26f8Smatthias.ringwald     hci_run();
58616833f0aSmatthias.ringwald }
58722909952Smatthias.ringwald 
58867a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
5899da54300S[email protected]     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
5903c4d4b90Smatthias.ringwald 
591c7e0c5f6Smatthias.ringwald     run_loop_remove_timer(&conn->timeout);
592c785ef68Smatthias.ringwald 
5933a9fb326S[email protected]     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
594a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
5953c4d4b90Smatthias.ringwald 
5963c4d4b90Smatthias.ringwald     // now it's gone
597c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
598c7e0c5f6Smatthias.ringwald }
599c7e0c5f6Smatthias.ringwald 
6000c042179S[email protected] static const uint16_t packet_type_sizes[] = {
6018f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
6028f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
6038f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
6048f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
6058f8108aaSmatthias.ringwald };
60665389bfcS[email protected] static const uint8_t  packet_type_feature_requirement_bit[] = {
60765389bfcS[email protected]      0, // 3 slot packets
60865389bfcS[email protected]      1, // 5 slot packets
60965389bfcS[email protected]     25, // EDR 2 mpbs
61065389bfcS[email protected]     26, // EDR 3 mbps
61165389bfcS[email protected]     39, // 3 slot EDR packts
61265389bfcS[email protected]     40, // 5 slot EDR packet
61365389bfcS[email protected] };
61465389bfcS[email protected] static const uint16_t packet_type_feature_packet_mask[] = {
61565389bfcS[email protected]     0x0f00, // 3 slot packets
61665389bfcS[email protected]     0xf000, // 5 slot packets
61765389bfcS[email protected]     0x1102, // EDR 2 mpbs
61865389bfcS[email protected]     0x2204, // EDR 3 mbps
61965389bfcS[email protected]     0x0300, // 3 slot EDR packts
62065389bfcS[email protected]     0x3000, // 5 slot EDR packet
62165389bfcS[email protected] };
6228f8108aaSmatthias.ringwald 
62365389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
62465389bfcS[email protected]     // enable packet types based on size
6258f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
6268f8108aaSmatthias.ringwald     int i;
6278f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
6288f8108aaSmatthias.ringwald         if (packet_type_sizes[i] == 0) continue;
6298f8108aaSmatthias.ringwald         if (packet_type_sizes[i] <= buffer_size){
6308f8108aaSmatthias.ringwald             packet_types |= 1 << i;
6318f8108aaSmatthias.ringwald         }
6328f8108aaSmatthias.ringwald     }
63365389bfcS[email protected]     // disable packet types due to missing local supported features
63465389bfcS[email protected]     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
63565389bfcS[email protected]         int bit_idx = packet_type_feature_requirement_bit[i];
63665389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
63765389bfcS[email protected]         if (feature_set) continue;
63865389bfcS[email protected]         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
63965389bfcS[email protected]         packet_types &= ~packet_type_feature_packet_mask[i];
64065389bfcS[email protected]     }
6418f8108aaSmatthias.ringwald     // flip bits for "may not be used"
6428f8108aaSmatthias.ringwald     packet_types ^= 0x3306;
6438f8108aaSmatthias.ringwald     return packet_types;
6448f8108aaSmatthias.ringwald }
6458f8108aaSmatthias.ringwald 
6468f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
6473a9fb326S[email protected]     return hci_stack->packet_types;
6488f8108aaSmatthias.ringwald }
6498f8108aaSmatthias.ringwald 
650facf93fdS[email protected] uint8_t* hci_get_outgoing_packet_buffer(void){
6517dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
6523a9fb326S[email protected]     return hci_stack->hci_packet_buffer;
6537dc17943Smatthias.ringwald }
6547dc17943Smatthias.ringwald 
655f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
6563a9fb326S[email protected]     return hci_stack->acl_data_packet_length;
6577dc17943Smatthias.ringwald }
6587dc17943Smatthias.ringwald 
6596ac9a97eS[email protected] int hci_non_flushable_packet_boundary_flag_supported(void){
6606ac9a97eS[email protected]     // No. 54, byte 6, bit 6
6616ac9a97eS[email protected]     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
6626ac9a97eS[email protected] }
6636ac9a97eS[email protected] 
664f5d8d141S[email protected] int hci_ssp_supported(void){
6656ac9a97eS[email protected]     // No. 51, byte 6, bit 3
6663a9fb326S[email protected]     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
667f5d8d141S[email protected] }
668f5d8d141S[email protected] 
669f5d8d141S[email protected] int hci_classic_supported(void){
6706ac9a97eS[email protected]     // No. 37, byte 4, bit 5, = No BR/EDR Support
6713a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
672f5d8d141S[email protected] }
673f5d8d141S[email protected] 
674f5d8d141S[email protected] int hci_le_supported(void){
675f5d8d141S[email protected] #ifdef HAVE_BLE
6766ac9a97eS[email protected]     // No. 37, byte 4, bit 6 = LE Supported (Controller)
6773a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
678f5d8d141S[email protected] #else
679f5d8d141S[email protected]     return 0;
680f5d8d141S[email protected] #endif
681f5d8d141S[email protected] }
682f5d8d141S[email protected] 
68369a97523S[email protected] // get addr type and address used in advertisement packets
68418904abdS[email protected] void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){
6853a9fb326S[email protected]     *addr_type = hci_stack->adv_addr_type;
6863a9fb326S[email protected]     if (hci_stack->adv_addr_type){
6873a9fb326S[email protected]         memcpy(addr, hci_stack->adv_address, 6);
68869a97523S[email protected]     } else {
6893a9fb326S[email protected]         memcpy(addr, hci_stack->local_bd_addr, 6);
69069a97523S[email protected]     }
69169a97523S[email protected] }
69269a97523S[email protected] 
693b2f949feS[email protected] #ifdef HAVE_BLE
694e01fe8b6S[email protected] void le_handle_advertisement_report(uint8_t *packet, int size){
695d1dc057bS[email protected]     int offset = 3;
696d1dc057bS[email protected]     int num_reports = packet[offset];
697d1dc057bS[email protected]     offset += 1;
698d1dc057bS[email protected] 
69957c9da5bS[email protected]     int i;
7004f4b43f3S[email protected]     log_info("HCI: handle adv report with num reports: %d", num_reports);
70157c9da5bS[email protected]     for (i=0; i<num_reports;i++){
702210c6774S[email protected]         uint8_t data_length = packet[offset + 8];
7032b552b23S[email protected]         uint8_t event_size = 10 + data_length;
7042b552b23S[email protected]         uint8_t event[2 + event_size ];
705d1dc057bS[email protected]         int pos = 0;
7062b552b23S[email protected]         event[pos++] = GAP_LE_ADVERTISING_REPORT;
70757c9da5bS[email protected]         event[pos++] = event_size;
708210c6774S[email protected]         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
709d1dc057bS[email protected]         offset += 8;
710d1dc057bS[email protected]         pos += 8;
711d1dc057bS[email protected]         event[pos++] = packet[offset + 1 + data_length]; // rssi
712d1dc057bS[email protected]         event[pos++] = packet[offset++]; //data_length;
713d1dc057bS[email protected]         memcpy(&event[pos], &packet[offset], data_length);
71457c9da5bS[email protected]         pos += data_length;
715d1dc057bS[email protected]         offset += data_length + 1; // rssi
7164f4b43f3S[email protected]         hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
71757c9da5bS[email protected]         hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
71857c9da5bS[email protected]     }
71957c9da5bS[email protected] }
720b2f949feS[email protected] #endif
72157c9da5bS[email protected] 
7226155b3d3S[email protected] static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
723a2481739S[email protected]     uint8_t command_completed = 0;
724a2481739S[email protected]     if ((hci_stack->substate % 2) == 0) return;
7256155b3d3S[email protected]     // odd: waiting for event
7266155b3d3S[email protected]     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
7276155b3d3S[email protected]         uint16_t opcode = READ_BT_16(packet,3);
7286155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
729a2481739S[email protected]             command_completed = 1;
7306155b3d3S[email protected]             log_info("Command complete for expected opcode %04x -> new substate %u", opcode, hci_stack->substate);
7316155b3d3S[email protected]         } else {
7326155b3d3S[email protected]             log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
7336155b3d3S[email protected]         }
7346155b3d3S[email protected]     }
7356155b3d3S[email protected]     if (packet[0] == HCI_EVENT_COMMAND_STATUS){
7366155b3d3S[email protected]         uint8_t  status = packet[2];
7376155b3d3S[email protected]         uint16_t opcode = READ_BT_16(packet,4);
7386155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
7396155b3d3S[email protected]             if (status){
740a2481739S[email protected]                 command_completed = 1;
7416155b3d3S[email protected]                 log_error("Command status error 0x%02x for expected opcode %04x -> new substate %u", status, opcode, hci_stack->substate);
7426155b3d3S[email protected]             } else {
7436155b3d3S[email protected]                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
7446155b3d3S[email protected]             }
7456155b3d3S[email protected]         } else {
7466155b3d3S[email protected]             log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
7476155b3d3S[email protected]         }
7486155b3d3S[email protected]     }
749a2481739S[email protected] 
750a2481739S[email protected]     if (!command_completed) return;
751a2481739S[email protected] 
752a2481739S[email protected]     switch(hci_stack->substate >> 1){
753a2481739S[email protected]         default:
754a2481739S[email protected]             hci_stack->substate++;
755a2481739S[email protected]             break;
7566155b3d3S[email protected]     }
7576155b3d3S[email protected] }
7586155b3d3S[email protected] 
7596155b3d3S[email protected] static void hci_initializing_state_machine(){
7609da54300S[email protected]         // log_info("hci_init: substate %u", hci_stack->substate);
7616155b3d3S[email protected]     if (hci_stack->substate % 2) {
7626155b3d3S[email protected]         // odd: waiting for command completion
7636155b3d3S[email protected]         return;
7646155b3d3S[email protected]     }
7656155b3d3S[email protected]     switch (hci_stack->substate >> 1){
7666155b3d3S[email protected]         case 0: // RESET
7676155b3d3S[email protected]             hci_state_reset();
7686155b3d3S[email protected] 
7696155b3d3S[email protected]             hci_send_cmd(&hci_reset);
7706155b3d3S[email protected]             if (hci_stack->config == NULL || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
7716155b3d3S[email protected]                 // skip baud change
7726155b3d3S[email protected]                 hci_stack->substate = 4; // >> 1 = 2
7736155b3d3S[email protected]             }
7746155b3d3S[email protected]             break;
7756155b3d3S[email protected]         case 1: // SEND BAUD CHANGE
7766155b3d3S[email protected]             hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
77788789c61Smatthias.ringwald             hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
7786155b3d3S[email protected]             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
7796155b3d3S[email protected]             break;
7806155b3d3S[email protected]         case 2: // LOCAL BAUD CHANGE
7816155b3d3S[email protected]             log_info("Local baud rate change");
7826155b3d3S[email protected]             hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
7836155b3d3S[email protected]             hci_stack->substate += 2;
7846155b3d3S[email protected]             // break missing here for fall through
7856155b3d3S[email protected] 
7866155b3d3S[email protected]         case 3:
7876155b3d3S[email protected]             log_info("Custom init");
7886155b3d3S[email protected]             // Custom initialization
7896155b3d3S[email protected]             if (hci_stack->control && hci_stack->control->next_cmd){
7906155b3d3S[email protected]                 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
7916155b3d3S[email protected]                 if (valid_cmd){
7926155b3d3S[email protected]                     int size = 3 + hci_stack->hci_packet_buffer[2];
7936155b3d3S[email protected]                     hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
7946155b3d3S[email protected]                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
7956155b3d3S[email protected]                     hci_stack->substate = 4; // more init commands
7966155b3d3S[email protected]                     break;
7976155b3d3S[email protected]                 }
7989da54300S[email protected]                 log_info("hci_run: init script done");
7996155b3d3S[email protected]             }
8006155b3d3S[email protected]             // otherwise continue
8016155b3d3S[email protected]             hci_send_cmd(&hci_read_bd_addr);
8026155b3d3S[email protected]             break;
8036155b3d3S[email protected]         case 4:
8046155b3d3S[email protected]             hci_send_cmd(&hci_read_buffer_size);
8056155b3d3S[email protected]             break;
8066155b3d3S[email protected]         case 5:
8076155b3d3S[email protected]             hci_send_cmd(&hci_read_local_supported_features);
8086155b3d3S[email protected]             break;
8096155b3d3S[email protected]         case 6:
8106155b3d3S[email protected]             if (hci_le_supported()){
8116155b3d3S[email protected]                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
8126155b3d3S[email protected]             } else {
8136155b3d3S[email protected]                 // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
8146155b3d3S[email protected]                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
8156155b3d3S[email protected]             }
8166155b3d3S[email protected] 
8176155b3d3S[email protected]             // skip Classic init commands for LE only chipsets
8186155b3d3S[email protected]             if (!hci_classic_supported()){
8196155b3d3S[email protected]                 if (hci_le_supported()){
8206155b3d3S[email protected]                     hci_stack->substate = 11 << 1;    // skip all classic command
8216155b3d3S[email protected]                 } else {
8226155b3d3S[email protected]                     log_error("Neither BR/EDR nor LE supported");
8236155b3d3S[email protected]                     hci_stack->substate = 14 << 1;    // skip all
8246155b3d3S[email protected]                 }
8256155b3d3S[email protected]             }
8266155b3d3S[email protected]             break;
8276155b3d3S[email protected]         case 7:
8286155b3d3S[email protected]             if (hci_ssp_supported()){
8296155b3d3S[email protected]                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
8306155b3d3S[email protected]                 break;
8316155b3d3S[email protected]             }
8326155b3d3S[email protected]             hci_stack->substate += 2;
8336155b3d3S[email protected]             // break missing here for fall through
8346155b3d3S[email protected] 
8356155b3d3S[email protected]         case 8:
8366155b3d3S[email protected]             // ca. 15 sec
8376155b3d3S[email protected]             hci_send_cmd(&hci_write_page_timeout, 0x6000);
8386155b3d3S[email protected]             break;
8396155b3d3S[email protected]         case 9:
8406155b3d3S[email protected]             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
8416155b3d3S[email protected]             break;
8426155b3d3S[email protected]         case 10:
8436155b3d3S[email protected]             if (hci_stack->local_name){
8446155b3d3S[email protected]                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
8456155b3d3S[email protected]             } else {
8466155b3d3S[email protected]                 char hostname[30];
8476155b3d3S[email protected] #ifdef EMBEDDED
8486155b3d3S[email protected]                 // BTstack-11:22:33:44:55:66
8496155b3d3S[email protected]                 strcpy(hostname, "BTstack ");
8506155b3d3S[email protected]                 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr));
8516155b3d3S[email protected]                 log_info("---> Name %s", hostname);
8526155b3d3S[email protected] #else
8536155b3d3S[email protected]                 // hostname for POSIX systems
8546155b3d3S[email protected]                 gethostname(hostname, 30);
8556155b3d3S[email protected]                 hostname[29] = '\0';
8566155b3d3S[email protected] #endif
8576155b3d3S[email protected]                 hci_send_cmd(&hci_write_local_name, hostname);
8586155b3d3S[email protected]             }
8596155b3d3S[email protected]             break;
8606155b3d3S[email protected]         case 11:
8616155b3d3S[email protected]             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
8626155b3d3S[email protected]             if (!hci_le_supported()){
8636155b3d3S[email protected]                 // SKIP LE init for Classic only configuration
8646155b3d3S[email protected]                 hci_stack->substate = 14 << 1;
8656155b3d3S[email protected]             }
8666155b3d3S[email protected]             break;
8676155b3d3S[email protected] 
8686155b3d3S[email protected] #ifdef HAVE_BLE
8696155b3d3S[email protected]         // LE INIT
8706155b3d3S[email protected]         case 12:
8716155b3d3S[email protected]             hci_send_cmd(&hci_le_read_buffer_size);
8726155b3d3S[email protected]             break;
8736155b3d3S[email protected]         case 13:
8746155b3d3S[email protected]             // LE Supported Host = 1, Simultaneous Host = 0
8756155b3d3S[email protected]             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
8766155b3d3S[email protected]             break;
8776155b3d3S[email protected]         case 14:
8786155b3d3S[email protected]             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs
8796155b3d3S[email protected]             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0);
8806155b3d3S[email protected]             break;
8816155b3d3S[email protected] #endif
8826155b3d3S[email protected] 
8836155b3d3S[email protected]         // DONE
8846155b3d3S[email protected]         case 15:
8856155b3d3S[email protected]             // done.
8866155b3d3S[email protected]             hci_stack->state = HCI_STATE_WORKING;
8876155b3d3S[email protected]             hci_emit_state();
8886155b3d3S[email protected]             break;
8896155b3d3S[email protected]         default:
8906155b3d3S[email protected]             break;
8916155b3d3S[email protected]     }
8926155b3d3S[email protected]     hci_stack->substate++;
8936155b3d3S[email protected] }
8946155b3d3S[email protected] 
89574ec757aSmatthias.ringwald // avoid huge local variables
896223aafc1Smatthias.ringwald #ifndef EMBEDDED
89774ec757aSmatthias.ringwald static device_name_t device_name;
898223aafc1Smatthias.ringwald #endif
89916833f0aSmatthias.ringwald static void event_handler(uint8_t *packet, int size){
900e76a89eeS[email protected] 
901e76a89eeS[email protected]     uint16_t event_length = packet[1];
902e76a89eeS[email protected] 
903e76a89eeS[email protected]     // assert packet is complete
904e76a89eeS[email protected]     if (size != event_length + 2){
905e76a89eeS[email protected]         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
906e76a89eeS[email protected]         return;
907e76a89eeS[email protected]     }
908e76a89eeS[email protected] 
9091281a47eSmatthias.ringwald     bd_addr_t addr;
91096a45072S[email protected]     bd_addr_type_t addr_type;
9112d00edd4Smatthias.ringwald     uint8_t link_type;
912fe1ed1b8Smatthias.ringwald     hci_con_handle_t handle;
9131f7b95a1Smatthias.ringwald     hci_connection_t * conn;
91456cf178bSmatthias.ringwald     int i;
91522909952Smatthias.ringwald 
9169da54300S[email protected]     // log_info("HCI:EVENT:%02x", packet[0]);
9175909f7f2Smatthias.ringwald 
9186772a24cSmatthias.ringwald     switch (packet[0]) {
91922909952Smatthias.ringwald 
9206772a24cSmatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
9217ec5eeaaSmatthias.ringwald             // get num cmd packets
9229da54300S[email protected]             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]);
9233a9fb326S[email protected]             hci_stack->num_cmd_packets = packet[2];
9247ec5eeaaSmatthias.ringwald 
925e2edc0c3Smatthias.ringwald             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
926e2edc0c3Smatthias.ringwald                 // from offset 5
927e2edc0c3Smatthias.ringwald                 // status
9281d279b20Smatthias.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"
9293a9fb326S[email protected]                 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6);
93056cf178bSmatthias.ringwald                 // ignore: SCO data packet len (8)
931ee303eddS[email protected]                 hci_stack->acl_packets_total_num  = packet[9];
93256cf178bSmatthias.ringwald                 // ignore: total num SCO packets
9333a9fb326S[email protected]                 if (hci_stack->state == HCI_STATE_INITIALIZING){
934a7a04bd9Smatthias.ringwald                     // determine usable ACL payload size
9353a9fb326S[email protected]                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
9363a9fb326S[email protected]                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
9378f8108aaSmatthias.ringwald                     }
9389da54300S[email protected]                     log_info("hci_read_buffer_size: used size %u, count %u",
939ee303eddS[email protected]                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num);
940e2edc0c3Smatthias.ringwald                 }
94156cf178bSmatthias.ringwald             }
94265a46ef3S[email protected] #ifdef HAVE_BLE
94365a46ef3S[email protected]             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){
944219eea5fS[email protected]                 hci_stack->le_data_packets_length = READ_BT_16(packet, 6);
945ee303eddS[email protected]                 hci_stack->le_acl_packets_total_num  = packet[8];
946*6c26b087S[email protected]                     // determine usable ACL payload size
947*6c26b087S[email protected]                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
948*6c26b087S[email protected]                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
949*6c26b087S[email protected]                     }
9509da54300S[email protected]                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
95165a46ef3S[email protected]             }
95265a46ef3S[email protected] #endif
953188981d2Smatthias.ringwald             // Dump local address
954188981d2Smatthias.ringwald             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
9553a9fb326S[email protected]                 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
9569da54300S[email protected]                 log_info("Local Address, Status: 0x%02x: Addr: %s",
9573a9fb326S[email protected]                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
958188981d2Smatthias.ringwald             }
959381fbed8Smatthias.ringwald             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
9603a9fb326S[email protected]                 hci_emit_discoverable_enabled(hci_stack->discoverable);
961381fbed8Smatthias.ringwald             }
96265389bfcS[email protected]             // Note: HCI init checks
963559e517eS[email protected]             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
9643a9fb326S[email protected]                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
965559e517eS[email protected]                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
9663a9fb326S[email protected]                     hci_stack->local_supported_features[0], hci_stack->local_supported_features[1],
9673a9fb326S[email protected]                     hci_stack->local_supported_features[2], hci_stack->local_supported_features[3],
9683a9fb326S[email protected]                     hci_stack->local_supported_features[4], hci_stack->local_supported_features[5],
9693a9fb326S[email protected]                     hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]);
97065389bfcS[email protected] 
97165389bfcS[email protected]                 // determine usable ACL packet types based buffer size and supported features
9723a9fb326S[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]);
9733a9fb326S[email protected]                 log_info("packet types %04x", hci_stack->packet_types);
974f5d8d141S[email protected] 
975f5d8d141S[email protected]                 // Classic/LE
976f5d8d141S[email protected]                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
977559e517eS[email protected]             }
97856cf178bSmatthias.ringwald             break;
97956cf178bSmatthias.ringwald 
9807ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
9817ec5eeaaSmatthias.ringwald             // get num cmd packets
9829da54300S[email protected]             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]);
9833a9fb326S[email protected]             hci_stack->num_cmd_packets = packet[3];
9847ec5eeaaSmatthias.ringwald             break;
9857ec5eeaaSmatthias.ringwald 
9862e440c8aS[email protected]         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
9872e440c8aS[email protected]             int offset = 3;
98856cf178bSmatthias.ringwald             for (i=0; i<packet[2];i++){
9892e440c8aS[email protected]                 handle = READ_BT_16(packet, offset);
9902e440c8aS[email protected]                 offset += 2;
9912e440c8aS[email protected]                 uint16_t num_packets = READ_BT_16(packet, offset);
9922e440c8aS[email protected]                 offset += 2;
9932e440c8aS[email protected] 
9945061f3afS[email protected]                 conn = hci_connection_for_handle(handle);
99556cf178bSmatthias.ringwald                 if (!conn){
9969da54300S[email protected]                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
99756cf178bSmatthias.ringwald                     continue;
99856cf178bSmatthias.ringwald                 }
99923bed257S[email protected] 
100023bed257S[email protected]                 if (conn->num_acl_packets_sent >= num_packets){
100156cf178bSmatthias.ringwald                     conn->num_acl_packets_sent -= num_packets;
100223bed257S[email protected]                 } else {
100323bed257S[email protected]                     log_error("hci_number_completed_packets, more slots freed then sent.");
100423bed257S[email protected]                     conn->num_acl_packets_sent = 0;
100523bed257S[email protected]                 }
10069da54300S[email protected]                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
100756cf178bSmatthias.ringwald             }
10086772a24cSmatthias.ringwald             break;
10092e440c8aS[email protected]         }
10101f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
101137eaa4cfSmatthias.ringwald             bt_flip_addr(addr, &packet[2]);
101237eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
10132d00edd4Smatthias.ringwald             link_type = packet[11];
10149da54300S[email protected]             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
101537eaa4cfSmatthias.ringwald             if (link_type == 1) { // ACL
101696a45072S[email protected]                 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
10171f7b95a1Smatthias.ringwald                 if (!conn) {
101896a45072S[email protected]                     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
10191f7b95a1Smatthias.ringwald                 }
1020ce4c8fabSmatthias.ringwald                 if (!conn) {
1021ce4c8fabSmatthias.ringwald                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
10223a9fb326S[email protected]                     hci_stack->decline_reason = 0x0d;
10233a9fb326S[email protected]                     BD_ADDR_COPY(hci_stack->decline_addr, addr);
1024ce4c8fabSmatthias.ringwald                     break;
1025ce4c8fabSmatthias.ringwald                 }
102632ab9390Smatthias.ringwald                 conn->state = RECEIVED_CONNECTION_REQUEST;
102732ab9390Smatthias.ringwald                 hci_run();
102837eaa4cfSmatthias.ringwald             } else {
1029ce4c8fabSmatthias.ringwald                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
10303a9fb326S[email protected]                 hci_stack->decline_reason = 0x0a;
10313a9fb326S[email protected]                 BD_ADDR_COPY(hci_stack->decline_addr, addr);
103237eaa4cfSmatthias.ringwald             }
10331f7b95a1Smatthias.ringwald             break;
10341f7b95a1Smatthias.ringwald 
10356772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1036fe1ed1b8Smatthias.ringwald             // Connection management
1037fe1ed1b8Smatthias.ringwald             bt_flip_addr(addr, &packet[5]);
10389da54300S[email protected]             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
103996a45072S[email protected]             addr_type = BD_ADDR_TYPE_CLASSIC;
104096a45072S[email protected]             conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1041fe1ed1b8Smatthias.ringwald             if (conn) {
1042b448a0e7Smatthias.ringwald                 if (!packet[2]){
1043c8e4258aSmatthias.ringwald                     conn->state = OPEN;
1044fe1ed1b8Smatthias.ringwald                     conn->con_handle = READ_BT_16(packet, 3);
1045ad83dc6aS[email protected]                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1046ee091cf1Smatthias.ringwald 
1047c785ef68Smatthias.ringwald                     // restart timer
1048c21e6239Smatthias.ringwald                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1049ee091cf1Smatthias.ringwald                     run_loop_add_timer(&conn->timeout);
1050c785ef68Smatthias.ringwald 
10519da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
105243bfb1bdSmatthias.ringwald 
105343bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
1054b448a0e7Smatthias.ringwald                 } else {
10551bd5283dS[email protected]                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
10561bd5283dS[email protected]                     uint8_t status = packet[2];
10571bd5283dS[email protected]                     bd_addr_t bd_address;
10581bd5283dS[email protected]                     memcpy(&bd_address, conn->address, 6);
1059ad83dc6aS[email protected] 
1060b448a0e7Smatthias.ringwald                     // connection failed, remove entry
10613a9fb326S[email protected]                     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1062a3b02b71Smatthias.ringwald                     btstack_memory_hci_connection_free( conn );
1063c12e46e7Smatthias.ringwald 
10641bd5283dS[email protected]                     // notify client if dedicated bonding
10651bd5283dS[email protected]                     if (notify_dedicated_bonding_failed){
10661bd5283dS[email protected]                         log_info("hci notify_dedicated_bonding_failed");
10671bd5283dS[email protected]                         hci_emit_dedicated_bonding_result(bd_address, status);
10681bd5283dS[email protected]                     }
10691bd5283dS[email protected] 
1070c12e46e7Smatthias.ringwald                     // if authentication error, also delete link key
1071c12e46e7Smatthias.ringwald                     if (packet[2] == 0x05) {
1072c12e46e7Smatthias.ringwald                         hci_drop_link_key_for_bd_addr(&addr);
1073c12e46e7Smatthias.ringwald                     }
1074fe1ed1b8Smatthias.ringwald                 }
1075fe1ed1b8Smatthias.ringwald             }
10766772a24cSmatthias.ringwald             break;
1077fe1ed1b8Smatthias.ringwald 
1078afd4e962S[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1079afd4e962S[email protected]             handle = READ_BT_16(packet, 3);
1080afd4e962S[email protected]             conn = hci_connection_for_handle(handle);
1081afd4e962S[email protected]             if (!conn) break;
1082afd4e962S[email protected]             if (!packet[2]){
1083afd4e962S[email protected]                 uint8_t * features = &packet[5];
1084afd4e962S[email protected]                 if (features[6] & (1 << 3)){
1085afd4e962S[email protected]                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1086afd4e962S[email protected]                 }
1087afd4e962S[email protected]             }
1088afd4e962S[email protected]             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1089ad83dc6aS[email protected]             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags);
1090ad83dc6aS[email protected]             if (conn->bonding_flags & BONDING_DEDICATED){
1091ad83dc6aS[email protected]                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1092ad83dc6aS[email protected]             }
1093afd4e962S[email protected]             break;
1094afd4e962S[email protected] 
10957fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
10969da54300S[email protected]             log_info("HCI_EVENT_LINK_KEY_REQUEST");
10977fde4af9Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
109874d716b5S[email protected]             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
10993a9fb326S[email protected]             if (hci_stack->bondable && !hci_stack->remote_device_db) break;
110032ab9390Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
110164472d52Smatthias.ringwald             hci_run();
1102d9a327f9Smatthias.ringwald             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
110329d53098Smatthias.ringwald             return;
11047fde4af9Smatthias.ringwald 
11059ab95c90S[email protected]         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
110629d53098Smatthias.ringwald             bt_flip_addr(addr, &packet[2]);
110796a45072S[email protected]             conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
11089ab95c90S[email protected]             if (!conn) break;
11099ab95c90S[email protected]             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
11107bdc6798S[email protected]             link_key_type_t link_key_type = (link_key_type_t)packet[24];
11119ab95c90S[email protected]             // Change Connection Encryption keeps link key type
11129ab95c90S[email protected]             if (link_key_type != CHANGED_COMBINATION_KEY){
11139ab95c90S[email protected]                 conn->link_key_type = link_key_type;
11149ab95c90S[email protected]             }
11153a9fb326S[email protected]             if (!hci_stack->remote_device_db) break;
11163a9fb326S[email protected]             hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type);
111729d53098Smatthias.ringwald             // still forward event to allow dismiss of pairing dialog
11187fde4af9Smatthias.ringwald             break;
11199ab95c90S[email protected]         }
11207fde4af9Smatthias.ringwald 
11217fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
11226724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
11234c57c146S[email protected]             // non-bondable mode: pin code negative reply will be sent
11243a9fb326S[email protected]             if (!hci_stack->bondable){
1125899283eaS[email protected]                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1126f8fb5f6eS[email protected]                 hci_run();
1127f8fb5f6eS[email protected]                 return;
11284c57c146S[email protected]             }
1129d9a327f9Smatthias.ringwald             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
11303a9fb326S[email protected]             if (!hci_stack->remote_device_db) break;
1131d9a327f9Smatthias.ringwald             bt_flip_addr(addr, &packet[2]);
11323a9fb326S[email protected]             hci_stack->remote_device_db->delete_link_key(&addr);
11337fde4af9Smatthias.ringwald             break;
11347fde4af9Smatthias.ringwald 
11351d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
11361d6b20aeS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1137dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1138dbe1a790S[email protected]             break;
1139dbe1a790S[email protected] 
1140dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
11416724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
11423a9fb326S[email protected]             if (!hci_stack->ssp_auto_accept) break;
1143dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1144dbe1a790S[email protected]             break;
1145dbe1a790S[email protected] 
1146dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
11476724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
11483a9fb326S[email protected]             if (!hci_stack->ssp_auto_accept) break;
1149dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
11501d6b20aeS[email protected]             break;
11511d6b20aeS[email protected] 
1152f0944df2S[email protected]         case HCI_EVENT_ENCRYPTION_CHANGE:
1153f0944df2S[email protected]             handle = READ_BT_16(packet, 3);
1154f0944df2S[email protected]             conn = hci_connection_for_handle(handle);
1155f0944df2S[email protected]             if (!conn) break;
1156ad83dc6aS[email protected]             if (packet[2] == 0) {
1157f0944df2S[email protected]                 if (packet[5]){
1158f0944df2S[email protected]                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1159f0944df2S[email protected]                 } else {
1160536f9994S[email protected]                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1161f0944df2S[email protected]                 }
1162ad83dc6aS[email protected]             }
1163a00031e2S[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1164f0944df2S[email protected]             break;
1165f0944df2S[email protected] 
11661eb2563eS[email protected]         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
11671eb2563eS[email protected]             handle = READ_BT_16(packet, 3);
11681eb2563eS[email protected]             conn = hci_connection_for_handle(handle);
11691eb2563eS[email protected]             if (!conn) break;
1170ad83dc6aS[email protected] 
1171ad83dc6aS[email protected]             // dedicated bonding: send result and disconnect
1172ad83dc6aS[email protected]             if (conn->bonding_flags & BONDING_DEDICATED){
1173ad83dc6aS[email protected]                 conn->bonding_flags &= ~BONDING_DEDICATED;
1174ad83dc6aS[email protected]                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
11751bd5283dS[email protected]                 conn->bonding_status = packet[2];
1176ad83dc6aS[email protected]                 break;
1177ad83dc6aS[email protected]             }
1178ad83dc6aS[email protected] 
1179b5cb6874S[email protected]             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
11801eb2563eS[email protected]                 // link key sufficient for requested security
11811eb2563eS[email protected]                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1182ad83dc6aS[email protected]                 break;
1183ad83dc6aS[email protected]             }
11841eb2563eS[email protected]             // not enough
11851eb2563eS[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
11861eb2563eS[email protected]             break;
118734d2123cS[email protected] 
1188223aafc1Smatthias.ringwald #ifndef EMBEDDED
118974ec757aSmatthias.ringwald         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
11903a9fb326S[email protected]             if (!hci_stack->remote_device_db) break;
119174ec757aSmatthias.ringwald             if (packet[2]) break; // status not ok
119274ec757aSmatthias.ringwald             bt_flip_addr(addr, &packet[3]);
11935a06394aSmatthias.ringwald             // fix for invalid remote names - terminate on 0xff
11945a06394aSmatthias.ringwald             for (i=0; i<248;i++){
11955a06394aSmatthias.ringwald                 if (packet[9+i] == 0xff){
11965a06394aSmatthias.ringwald                     packet[9+i] = 0;
11975a06394aSmatthias.ringwald                     break;
1198cdc9101dSmatthias.ringwald                 }
11995a06394aSmatthias.ringwald             }
1200d2fe945cS[email protected]             memset(&device_name, 0, sizeof(device_name_t));
120174ec757aSmatthias.ringwald             strncpy((char*) device_name, (char*) &packet[9], 248);
12023a9fb326S[email protected]             hci_stack->remote_device_db->put_name(&addr, &device_name);
120374ec757aSmatthias.ringwald             break;
120474ec757aSmatthias.ringwald 
120574ec757aSmatthias.ringwald         case HCI_EVENT_INQUIRY_RESULT:
1206206a9031S[email protected]         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{
12073a9fb326S[email protected]             if (!hci_stack->remote_device_db) break;
120874ec757aSmatthias.ringwald             // first send inq result packet
12093a9fb326S[email protected]             hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
121074ec757aSmatthias.ringwald             // then send cached remote names
1211206a9031S[email protected]             int offset = 3;
121274ec757aSmatthias.ringwald             for (i=0; i<packet[2];i++){
1213206a9031S[email protected]                 bt_flip_addr(addr, &packet[offset]);
1214206a9031S[email protected]                 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2;
12153a9fb326S[email protected]                 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){
121674ec757aSmatthias.ringwald                     hci_emit_remote_name_cached(&addr, &device_name);
121774ec757aSmatthias.ringwald                 }
121874ec757aSmatthias.ringwald             }
121974ec757aSmatthias.ringwald             return;
1220206a9031S[email protected]         }
1221223aafc1Smatthias.ringwald #endif
122274ec757aSmatthias.ringwald 
122386805605S[email protected]         // HCI_EVENT_DISCONNECTION_COMPLETE
122486805605S[email protected]         // has been moved down, to first notify stack before shutting connection down
12256772a24cSmatthias.ringwald 
1226c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
12273a9fb326S[email protected]             if(hci_stack->control && hci_stack->control->hw_error){
12283a9fb326S[email protected]                 (*hci_stack->control->hw_error)();
12297586ee35S[email protected]             } else {
12307586ee35S[email protected]                 // if no special requests, just reboot stack
12317586ee35S[email protected]                 hci_power_control_off();
12327586ee35S[email protected]                 hci_power_control_on();
1233c68bdf90Smatthias.ringwald             }
1234c68bdf90Smatthias.ringwald             break;
1235c68bdf90Smatthias.ringwald 
12366b4af23dS[email protected]         case DAEMON_EVENT_HCI_PACKET_SENT:
12376b4af23dS[email protected]             // free packet buffer for asynchronous transport
12386b4af23dS[email protected]             if (hci_transport_synchronous()) break;
12396b4af23dS[email protected]             hci_stack->hci_packet_buffer_reserved = 0;
12406b4af23dS[email protected]             break;
12416b4af23dS[email protected] 
12425909f7f2Smatthias.ringwald #ifdef HAVE_BLE
12435909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
12445909f7f2Smatthias.ringwald             switch (packet[2]){
124557c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
12469da54300S[email protected]                     log_info("advertising report received");
12477bdc6798S[email protected]                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
124857c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
12497bdc6798S[email protected]                     break;
12505909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
12515909f7f2Smatthias.ringwald                     // Connection management
12525909f7f2Smatthias.ringwald                     bt_flip_addr(addr, &packet[8]);
12537bdc6798S[email protected]                     addr_type = (bd_addr_type_t)packet[7];
12549da54300S[email protected]                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
12555909f7f2Smatthias.ringwald                     // LE connections are auto-accepted, so just create a connection if there isn't one already
125696a45072S[email protected]                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
12575909f7f2Smatthias.ringwald                     if (packet[3]){
12585909f7f2Smatthias.ringwald                         if (conn){
12595909f7f2Smatthias.ringwald                             // outgoing connection failed, remove entry
12603a9fb326S[email protected]                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
12615909f7f2Smatthias.ringwald                             btstack_memory_hci_connection_free( conn );
12625909f7f2Smatthias.ringwald                         }
12635909f7f2Smatthias.ringwald                         // if authentication error, also delete link key
12645909f7f2Smatthias.ringwald                         if (packet[3] == 0x05) {
12655909f7f2Smatthias.ringwald                             hci_drop_link_key_for_bd_addr(&addr);
12665909f7f2Smatthias.ringwald                         }
12675909f7f2Smatthias.ringwald                         break;
12685909f7f2Smatthias.ringwald                     }
12695909f7f2Smatthias.ringwald                     if (!conn){
127096a45072S[email protected]                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
12715909f7f2Smatthias.ringwald                     }
12725909f7f2Smatthias.ringwald                     if (!conn){
12735909f7f2Smatthias.ringwald                         // no memory
12745909f7f2Smatthias.ringwald                         break;
12755909f7f2Smatthias.ringwald                     }
12765909f7f2Smatthias.ringwald 
12775909f7f2Smatthias.ringwald                     conn->state = OPEN;
12785909f7f2Smatthias.ringwald                     conn->con_handle = READ_BT_16(packet, 4);
12795909f7f2Smatthias.ringwald 
12805909f7f2Smatthias.ringwald                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
12815909f7f2Smatthias.ringwald 
12825909f7f2Smatthias.ringwald                     // restart timer
12835909f7f2Smatthias.ringwald                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
12845909f7f2Smatthias.ringwald                     // run_loop_add_timer(&conn->timeout);
12855909f7f2Smatthias.ringwald 
12869da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
12875909f7f2Smatthias.ringwald 
12885909f7f2Smatthias.ringwald                     hci_emit_nr_connections_changed();
12895909f7f2Smatthias.ringwald                     break;
12905909f7f2Smatthias.ringwald 
12919da54300S[email protected]             // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]);
129265a46ef3S[email protected] 
12935909f7f2Smatthias.ringwald                 default:
12945909f7f2Smatthias.ringwald                     break;
12955909f7f2Smatthias.ringwald             }
12965909f7f2Smatthias.ringwald             break;
12975909f7f2Smatthias.ringwald #endif
12986772a24cSmatthias.ringwald         default:
12996772a24cSmatthias.ringwald             break;
1300fe1ed1b8Smatthias.ringwald     }
1301fe1ed1b8Smatthias.ringwald 
13023429f56bSmatthias.ringwald     // handle BT initialization
13033a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_INITIALIZING){
13046155b3d3S[email protected]         hci_initializing_event_handler(packet, size);
1305c9af4d3fS[email protected]     }
130622909952Smatthias.ringwald 
130789db417bSmatthias.ringwald     // help with BT sleep
13083a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
13093a9fb326S[email protected]         && hci_stack->substate == 1
131089db417bSmatthias.ringwald         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
13113a9fb326S[email protected]         hci_stack->substate++;
131289db417bSmatthias.ringwald     }
131389db417bSmatthias.ringwald 
131486805605S[email protected]     // notify upper stack
13153a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
131694ab26f8Smatthias.ringwald 
131786805605S[email protected]     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
131886805605S[email protected]     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
131986805605S[email protected]         if (!packet[2]){
132086805605S[email protected]             handle = READ_BT_16(packet, 3);
132186805605S[email protected]             hci_connection_t * conn = hci_connection_for_handle(handle);
132286805605S[email protected]             if (conn) {
132386805605S[email protected]                 uint8_t status = conn->bonding_status;
132486805605S[email protected]                 bd_addr_t bd_address;
132586805605S[email protected]                 memcpy(&bd_address, conn->address, 6);
132686805605S[email protected]                 hci_shutdown_connection(conn);
132786805605S[email protected]                 if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
132886805605S[email protected]                     hci_emit_dedicated_bonding_result(bd_address, status);
132986805605S[email protected]                 }
133086805605S[email protected]             }
133186805605S[email protected]         }
133286805605S[email protected]     }
133386805605S[email protected] 
133494ab26f8Smatthias.ringwald 	// execute main loop
133594ab26f8Smatthias.ringwald 	hci_run();
133616833f0aSmatthias.ringwald }
133716833f0aSmatthias.ringwald 
13380a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
133910e830c9Smatthias.ringwald     switch (packet_type) {
134010e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
134110e830c9Smatthias.ringwald             event_handler(packet, size);
134210e830c9Smatthias.ringwald             break;
134310e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
134410e830c9Smatthias.ringwald             acl_handler(packet, size);
134510e830c9Smatthias.ringwald             break;
134610e830c9Smatthias.ringwald         default:
134710e830c9Smatthias.ringwald             break;
134810e830c9Smatthias.ringwald     }
134910e830c9Smatthias.ringwald }
135010e830c9Smatthias.ringwald 
1351fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
13522718e2e7Smatthias.ringwald void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
13533a9fb326S[email protected]     hci_stack->packet_handler = handler;
135416833f0aSmatthias.ringwald }
135516833f0aSmatthias.ringwald 
13566155b3d3S[email protected] static void hci_state_reset(){
1357595bdbfbS[email protected]     // no connections yet
1358595bdbfbS[email protected]     hci_stack->connections = NULL;
135974308b23Smatthias.ringwald 
136074308b23Smatthias.ringwald     // keep discoverable/connectable as this has been requested by the client(s)
136174308b23Smatthias.ringwald     // hci_stack->discoverable = 0;
136274308b23Smatthias.ringwald     // hci_stack->connectable = 0;
136374308b23Smatthias.ringwald     // hci_stack->bondable = 1;
1364595bdbfbS[email protected] 
136544935e40S[email protected]     // buffer is free
136644935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
136744935e40S[email protected] 
1368595bdbfbS[email protected]     // no pending cmds
1369595bdbfbS[email protected]     hci_stack->decline_reason = 0;
1370595bdbfbS[email protected]     hci_stack->new_scan_enable_value = 0xff;
1371595bdbfbS[email protected] 
1372595bdbfbS[email protected]     // LE
1373595bdbfbS[email protected]     hci_stack->adv_addr_type = 0;
1374595bdbfbS[email protected]     memset(hci_stack->adv_address, 0, 6);
1375595bdbfbS[email protected]     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1376e2602ea2Smatthias.ringwald     hci_stack->le_scan_type = 0xff;
1377595bdbfbS[email protected] }
1378595bdbfbS[email protected] 
13794f4fc1dfSmatthias.ringwald void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
1380475c8125Smatthias.ringwald 
13813a9fb326S[email protected] #ifdef HAVE_MALLOC
13823a9fb326S[email protected]     if (!hci_stack) {
13833a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
13843a9fb326S[email protected]     }
13853a9fb326S[email protected] #else
13863a9fb326S[email protected]     hci_stack = &hci_stack_static;
13873a9fb326S[email protected] #endif
138866fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
13893a9fb326S[email protected] 
1390475c8125Smatthias.ringwald     // reference to use transport layer implementation
13913a9fb326S[email protected]     hci_stack->hci_transport = transport;
1392475c8125Smatthias.ringwald 
139311e23e5fSmatthias.ringwald     // references to used control implementation
13943a9fb326S[email protected]     hci_stack->control = control;
139511e23e5fSmatthias.ringwald 
139611e23e5fSmatthias.ringwald     // reference to used config
13973a9fb326S[email protected]     hci_stack->config = config;
139811e23e5fSmatthias.ringwald 
139916833f0aSmatthias.ringwald     // higher level handler
14003a9fb326S[email protected]     hci_stack->packet_handler = dummy_handler;
140116833f0aSmatthias.ringwald 
1402404843c1Smatthias.ringwald     // store and open remote device db
14033a9fb326S[email protected]     hci_stack->remote_device_db = remote_device_db;
14043a9fb326S[email protected]     if (hci_stack->remote_device_db) {
14053a9fb326S[email protected]         hci_stack->remote_device_db->open();
1406404843c1Smatthias.ringwald     }
140729d53098Smatthias.ringwald 
14088fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
14093a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
14108fcba05dSmatthias.ringwald 
141116833f0aSmatthias.ringwald     // register packet handlers with transport
141210e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
1413f5454fc6Smatthias.ringwald 
14143a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
1415e2386ba1S[email protected] 
1416e2386ba1S[email protected]     // class of device
14173a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
1418a45d6b9fS[email protected] 
1419f20168b8Smatthias.ringwald     // bondable by default
1420f20168b8Smatthias.ringwald     hci_stack->bondable = 1;
1421f20168b8Smatthias.ringwald 
142263048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
14233a9fb326S[email protected]     hci_stack->ssp_enable = 1;
14243a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
14253a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
14263a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
142769a97523S[email protected] 
1428595bdbfbS[email protected]     hci_state_reset();
1429475c8125Smatthias.ringwald }
1430475c8125Smatthias.ringwald 
1431404843c1Smatthias.ringwald void hci_close(){
1432404843c1Smatthias.ringwald     // close remote device db
14333a9fb326S[email protected]     if (hci_stack->remote_device_db) {
14343a9fb326S[email protected]         hci_stack->remote_device_db->close();
1435404843c1Smatthias.ringwald     }
14363a9fb326S[email protected]     while (hci_stack->connections) {
1437bc68afe2S[email protected]         // cancel all l2cap connections
1438bc68afe2S[email protected]         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
14393a9fb326S[email protected]         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1440f5454fc6Smatthias.ringwald     }
1441f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
14423a9fb326S[email protected] 
14433a9fb326S[email protected] #ifdef HAVE_MALLOC
14443a9fb326S[email protected]     free(hci_stack);
14453a9fb326S[email protected] #endif
14463a9fb326S[email protected]     hci_stack = NULL;
1447404843c1Smatthias.ringwald }
1448404843c1Smatthias.ringwald 
14499e61646fS[email protected] void hci_set_class_of_device(uint32_t class_of_device){
14509e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
14519e61646fS[email protected] }
14529e61646fS[email protected] 
145366fb9560S[email protected] void hci_disable_l2cap_timeout_check(){
145466fb9560S[email protected]     disable_l2cap_timeouts = 1;
145566fb9560S[email protected] }
14568d213e1aSmatthias.ringwald // State-Module-Driver overview
14578d213e1aSmatthias.ringwald // state                    module  low-level
14588d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
14598d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
14608d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
14618d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
1462d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
1463d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
1464c7e0c5f6Smatthias.ringwald 
146540d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
14667301ad89Smatthias.ringwald 
1467038bc64cSmatthias.ringwald     // power on
1468f9a30166Smatthias.ringwald     int err = 0;
14693a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
14703a9fb326S[email protected]         err = (*hci_stack->control->on)(hci_stack->config);
1471f9a30166Smatthias.ringwald     }
1472038bc64cSmatthias.ringwald     if (err){
14739da54300S[email protected]         log_error( "POWER_ON failed");
1474038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
1475038bc64cSmatthias.ringwald         return err;
1476038bc64cSmatthias.ringwald     }
1477038bc64cSmatthias.ringwald 
1478038bc64cSmatthias.ringwald     // open low-level device
14793a9fb326S[email protected]     err = hci_stack->hci_transport->open(hci_stack->config);
1480038bc64cSmatthias.ringwald     if (err){
14819da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
14823a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
14833a9fb326S[email protected]             (*hci_stack->control->off)(hci_stack->config);
1484f9a30166Smatthias.ringwald         }
1485038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
1486038bc64cSmatthias.ringwald         return err;
1487038bc64cSmatthias.ringwald     }
14888d213e1aSmatthias.ringwald     return 0;
14898d213e1aSmatthias.ringwald }
1490038bc64cSmatthias.ringwald 
149140d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
14928d213e1aSmatthias.ringwald 
14939da54300S[email protected]     log_info("hci_power_control_off");
14949418f9c9Smatthias.ringwald 
14958d213e1aSmatthias.ringwald     // close low-level device
14963a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
14978d213e1aSmatthias.ringwald 
14989da54300S[email protected]     log_info("hci_power_control_off - hci_transport closed");
14999418f9c9Smatthias.ringwald 
15008d213e1aSmatthias.ringwald     // power off
15013a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
15023a9fb326S[email protected]         (*hci_stack->control->off)(hci_stack->config);
15038d213e1aSmatthias.ringwald     }
15049418f9c9Smatthias.ringwald 
15059da54300S[email protected]     log_info("hci_power_control_off - control closed");
15069418f9c9Smatthias.ringwald 
15073a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
150872ea5239Smatthias.ringwald }
150972ea5239Smatthias.ringwald 
151040d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
151172ea5239Smatthias.ringwald 
15129da54300S[email protected]     log_info("hci_power_control_sleep");
15133144bce4Smatthias.ringwald 
1514b429b9b7Smatthias.ringwald #if 0
1515b429b9b7Smatthias.ringwald     // don't close serial port during sleep
1516b429b9b7Smatthias.ringwald 
151772ea5239Smatthias.ringwald     // close low-level device
15183a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
1519b429b9b7Smatthias.ringwald #endif
152072ea5239Smatthias.ringwald 
152172ea5239Smatthias.ringwald     // sleep mode
15223a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
15233a9fb326S[email protected]         (*hci_stack->control->sleep)(hci_stack->config);
152472ea5239Smatthias.ringwald     }
1525b429b9b7Smatthias.ringwald 
15263a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
15278d213e1aSmatthias.ringwald }
15288d213e1aSmatthias.ringwald 
152940d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
1530b429b9b7Smatthias.ringwald 
15319da54300S[email protected]     log_info("hci_power_control_wake");
1532b429b9b7Smatthias.ringwald 
1533b429b9b7Smatthias.ringwald     // wake on
15343a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
15353a9fb326S[email protected]         (*hci_stack->control->wake)(hci_stack->config);
1536b429b9b7Smatthias.ringwald     }
1537b429b9b7Smatthias.ringwald 
1538b429b9b7Smatthias.ringwald #if 0
1539b429b9b7Smatthias.ringwald     // open low-level device
15403a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
1541b429b9b7Smatthias.ringwald     if (err){
15429da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
15433a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
15443a9fb326S[email protected]             (*hci_stack->control->off)(hci_stack->config);
1545b429b9b7Smatthias.ringwald         }
1546b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
1547b429b9b7Smatthias.ringwald         return err;
1548b429b9b7Smatthias.ringwald     }
1549b429b9b7Smatthias.ringwald #endif
1550b429b9b7Smatthias.ringwald 
1551b429b9b7Smatthias.ringwald     return 0;
1552b429b9b7Smatthias.ringwald }
1553b429b9b7Smatthias.ringwald 
155444935e40S[email protected] static void hci_power_transition_to_initializing(void){
155544935e40S[email protected]     // set up state machine
155644935e40S[email protected]     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
155744935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
155844935e40S[email protected]     hci_stack->state = HCI_STATE_INITIALIZING;
155944935e40S[email protected]     hci_stack->substate = 0;
156044935e40S[email protected] }
1561b429b9b7Smatthias.ringwald 
15628d213e1aSmatthias.ringwald int hci_power_control(HCI_POWER_MODE power_mode){
1563d661ed19Smatthias.ringwald 
15649da54300S[email protected]     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
1565d661ed19Smatthias.ringwald 
15668d213e1aSmatthias.ringwald     int err = 0;
15673a9fb326S[email protected]     switch (hci_stack->state){
15688d213e1aSmatthias.ringwald 
15698d213e1aSmatthias.ringwald         case HCI_STATE_OFF:
15708d213e1aSmatthias.ringwald             switch (power_mode){
15718d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
15728d213e1aSmatthias.ringwald                     err = hci_power_control_on();
157397b61c7bS[email protected]                     if (err) {
157497b61c7bS[email protected]                         log_error("hci_power_control_on() error %u", err);
157597b61c7bS[email protected]                         return err;
157697b61c7bS[email protected]                     }
157744935e40S[email protected]                     hci_power_transition_to_initializing();
15788d213e1aSmatthias.ringwald                     break;
15798d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
15808d213e1aSmatthias.ringwald                     // do nothing
15818d213e1aSmatthias.ringwald                     break;
15828d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1583b546ac54Smatthias.ringwald                     // do nothing (with SLEEP == OFF)
15848d213e1aSmatthias.ringwald                     break;
15858d213e1aSmatthias.ringwald             }
15868d213e1aSmatthias.ringwald             break;
15877301ad89Smatthias.ringwald 
15888d213e1aSmatthias.ringwald         case HCI_STATE_INITIALIZING:
15898d213e1aSmatthias.ringwald             switch (power_mode){
15908d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
15918d213e1aSmatthias.ringwald                     // do nothing
15928d213e1aSmatthias.ringwald                     break;
15938d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
15948d213e1aSmatthias.ringwald                     // no connections yet, just turn it off
15958d213e1aSmatthias.ringwald                     hci_power_control_off();
15968d213e1aSmatthias.ringwald                     break;
15978d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1598b546ac54Smatthias.ringwald                     // no connections yet, just turn it off
159972ea5239Smatthias.ringwald                     hci_power_control_sleep();
16008d213e1aSmatthias.ringwald                     break;
16018d213e1aSmatthias.ringwald             }
16028d213e1aSmatthias.ringwald             break;
16037301ad89Smatthias.ringwald 
16048d213e1aSmatthias.ringwald         case HCI_STATE_WORKING:
16058d213e1aSmatthias.ringwald             switch (power_mode){
16068d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
16078d213e1aSmatthias.ringwald                     // do nothing
16088d213e1aSmatthias.ringwald                     break;
16098d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
1610c7e0c5f6Smatthias.ringwald                     // see hci_run
16113a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
16128d213e1aSmatthias.ringwald                     break;
16138d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1614b546ac54Smatthias.ringwald                     // see hci_run
16153a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
16163a9fb326S[email protected]                     hci_stack->substate = 0;
16178d213e1aSmatthias.ringwald                     break;
16188d213e1aSmatthias.ringwald             }
16198d213e1aSmatthias.ringwald             break;
16207301ad89Smatthias.ringwald 
16218d213e1aSmatthias.ringwald         case HCI_STATE_HALTING:
16228d213e1aSmatthias.ringwald             switch (power_mode){
16238d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
162444935e40S[email protected]                     hci_power_transition_to_initializing();
16258d213e1aSmatthias.ringwald                     break;
16268d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
16278d213e1aSmatthias.ringwald                     // do nothing
16288d213e1aSmatthias.ringwald                     break;
16298d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1630b546ac54Smatthias.ringwald                     // see hci_run
16313a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
16323a9fb326S[email protected]                     hci_stack->substate = 0;
16338d213e1aSmatthias.ringwald                     break;
16348d213e1aSmatthias.ringwald             }
16358d213e1aSmatthias.ringwald             break;
16368d213e1aSmatthias.ringwald 
16378d213e1aSmatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
16388d213e1aSmatthias.ringwald             switch (power_mode){
16398d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
164028171530Smatthias.ringwald 
164128171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
164228171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
164328171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
16443a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
16453a9fb326S[email protected]                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
164628171530Smatthias.ringwald                         break;
164728171530Smatthias.ringwald                     }
164828171530Smatthias.ringwald #endif
164944935e40S[email protected]                     hci_power_transition_to_initializing();
16508d213e1aSmatthias.ringwald                     break;
16518d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
1652b546ac54Smatthias.ringwald                     // see hci_run
16533a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
16548d213e1aSmatthias.ringwald                     break;
16558d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1656b546ac54Smatthias.ringwald                     // do nothing
16578d213e1aSmatthias.ringwald                     break;
16588d213e1aSmatthias.ringwald             }
16598d213e1aSmatthias.ringwald             break;
16608d213e1aSmatthias.ringwald 
16618d213e1aSmatthias.ringwald         case HCI_STATE_SLEEPING:
16628d213e1aSmatthias.ringwald             switch (power_mode){
16638d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
166428171530Smatthias.ringwald 
166528171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
166628171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
166728171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
16683a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
16693a9fb326S[email protected]                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1670758b46ceSmatthias.ringwald                         hci_update_scan_enable();
167128171530Smatthias.ringwald                         break;
167228171530Smatthias.ringwald                     }
167328171530Smatthias.ringwald #endif
16743144bce4Smatthias.ringwald                     err = hci_power_control_wake();
16753144bce4Smatthias.ringwald                     if (err) return err;
167644935e40S[email protected]                     hci_power_transition_to_initializing();
16778d213e1aSmatthias.ringwald                     break;
16788d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
16793a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
16808d213e1aSmatthias.ringwald                     break;
16818d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1682b546ac54Smatthias.ringwald                     // do nothing
16838d213e1aSmatthias.ringwald                     break;
16848d213e1aSmatthias.ringwald             }
16858d213e1aSmatthias.ringwald             break;
168611e23e5fSmatthias.ringwald     }
168768d92d03Smatthias.ringwald 
1688038bc64cSmatthias.ringwald     // create internal event
1689ee8bf225Smatthias.ringwald 	hci_emit_state();
1690ee8bf225Smatthias.ringwald 
169168d92d03Smatthias.ringwald 	// trigger next/first action
169268d92d03Smatthias.ringwald 	hci_run();
169368d92d03Smatthias.ringwald 
1694475c8125Smatthias.ringwald     return 0;
1695475c8125Smatthias.ringwald }
1696475c8125Smatthias.ringwald 
1697758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
1698758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
16993a9fb326S[email protected]     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1700758b46ceSmatthias.ringwald     hci_run();
1701758b46ceSmatthias.ringwald }
1702758b46ceSmatthias.ringwald 
1703381fbed8Smatthias.ringwald void hci_discoverable_control(uint8_t enable){
1704381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
1705381fbed8Smatthias.ringwald 
17063a9fb326S[email protected]     if (hci_stack->discoverable == enable){
17073a9fb326S[email protected]         hci_emit_discoverable_enabled(hci_stack->discoverable);
1708381fbed8Smatthias.ringwald         return;
1709381fbed8Smatthias.ringwald     }
1710381fbed8Smatthias.ringwald 
17113a9fb326S[email protected]     hci_stack->discoverable = enable;
1712758b46ceSmatthias.ringwald     hci_update_scan_enable();
1713758b46ceSmatthias.ringwald }
1714b031bebbSmatthias.ringwald 
1715758b46ceSmatthias.ringwald void hci_connectable_control(uint8_t enable){
1716758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
1717758b46ceSmatthias.ringwald 
1718758b46ceSmatthias.ringwald     // don't emit event
17193a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
1720758b46ceSmatthias.ringwald 
17213a9fb326S[email protected]     hci_stack->connectable = enable;
1722758b46ceSmatthias.ringwald     hci_update_scan_enable();
1723381fbed8Smatthias.ringwald }
1724381fbed8Smatthias.ringwald 
17255061f3afS[email protected] bd_addr_t * hci_local_bd_addr(void){
17263a9fb326S[email protected]     return &hci_stack->local_bd_addr;
17275061f3afS[email protected] }
17285061f3afS[email protected] 
172906b35ec0Smatthias.ringwald void hci_run(){
17308a485f27Smatthias.ringwald 
173132ab9390Smatthias.ringwald     hci_connection_t * connection;
173232ab9390Smatthias.ringwald     linked_item_t * it;
173332ab9390Smatthias.ringwald 
1734d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()) return;
1735ce4c8fabSmatthias.ringwald 
1736b031bebbSmatthias.ringwald     // global/non-connection oriented commands
1737b031bebbSmatthias.ringwald 
1738b031bebbSmatthias.ringwald     // decline incoming connections
17393a9fb326S[email protected]     if (hci_stack->decline_reason){
17403a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
17413a9fb326S[email protected]         hci_stack->decline_reason = 0;
17423a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1743dbe1a790S[email protected]         return;
1744ce4c8fabSmatthias.ringwald     }
1745ce4c8fabSmatthias.ringwald 
1746b031bebbSmatthias.ringwald     // send scan enable
17473a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
17483a9fb326S[email protected]         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
17493a9fb326S[email protected]         hci_stack->new_scan_enable_value = 0xff;
1750dbe1a790S[email protected]         return;
1751b031bebbSmatthias.ringwald     }
1752b031bebbSmatthias.ringwald 
1753b2f949feS[email protected] #ifdef HAVE_BLE
17547bdc6798S[email protected]     // handle le scan
17557bdc6798S[email protected]     if (hci_stack->state == HCI_STATE_WORKING){
17567bdc6798S[email protected]         switch(hci_stack->le_scanning_state){
17577bdc6798S[email protected]             case LE_START_SCAN:
17587bdc6798S[email protected]                 hci_stack->le_scanning_state = LE_SCANNING;
17597bdc6798S[email protected]                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
17607bdc6798S[email protected]                 return;
17617bdc6798S[email protected] 
17627bdc6798S[email protected]             case LE_STOP_SCAN:
17637bdc6798S[email protected]                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
17647bdc6798S[email protected]                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
17657bdc6798S[email protected]                 return;
17667bdc6798S[email protected]             default:
17677bdc6798S[email protected]                 break;
17687bdc6798S[email protected]         }
1769e2602ea2Smatthias.ringwald         if (hci_stack->le_scan_type != 0xff){
1770e2602ea2Smatthias.ringwald             // defaults: active scanning, accept all advertisement packets
1771e2602ea2Smatthias.ringwald             int scan_type = hci_stack->le_scan_type;
1772e2602ea2Smatthias.ringwald             hci_stack->le_scan_type = 0xff;
1773e2602ea2Smatthias.ringwald             hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->adv_addr_type, 0);
1774e2602ea2Smatthias.ringwald             return;
1775e2602ea2Smatthias.ringwald         }
17767bdc6798S[email protected]     }
1777b2f949feS[email protected] #endif
17787bdc6798S[email protected] 
177932ab9390Smatthias.ringwald     // send pending HCI commands
17803a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1781b031bebbSmatthias.ringwald         connection = (hci_connection_t *) it;
178232ab9390Smatthias.ringwald 
17830bf6344aS[email protected]         switch(connection->state){
17840bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
17854f3229d8S[email protected]                 switch(connection->address_type){
17864f3229d8S[email protected]                     case BD_ADDR_TYPE_CLASSIC:
17879da54300S[email protected]                         log_info("sending hci_create_connection");
1788ad83dc6aS[email protected]                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
17894f3229d8S[email protected]                         break;
17904f3229d8S[email protected]                     default:
1791b2f949feS[email protected] #ifdef HAVE_BLE
17929da54300S[email protected]                         log_info("sending hci_le_create_connection");
17934f3229d8S[email protected]                         hci_send_cmd(&hci_le_create_connection,
1794b2571179Smatthias.ringwald                                      0x0060,    // scan interval: 60 ms
1795b2571179Smatthias.ringwald                                      0x0030,    // scan interval: 30 ms
17964f3229d8S[email protected]                                      0,         // don't use whitelist
17974f3229d8S[email protected]                                      connection->address_type, // peer address type
17984f3229d8S[email protected]                                      connection->address,      // peer bd addr
1799b2571179Smatthias.ringwald                                      hci_stack->adv_addr_type, // our addr type:
1800b2571179Smatthias.ringwald                                      0x0008,    // conn interval min
1801b2571179Smatthias.ringwald                                      0x0018,    // conn interval max
18024f3229d8S[email protected]                                      0,         // conn latency
1803b2571179Smatthias.ringwald                                      0x0048,    // supervision timeout
1804b2571179Smatthias.ringwald                                      0x0001,    // min ce length
1805b2571179Smatthias.ringwald                                      0x0001     // max ce length
18064f3229d8S[email protected]                                      );
18074f3229d8S[email protected] 
18084f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
1809b2f949feS[email protected] #endif
18104f3229d8S[email protected]                         break;
18114f3229d8S[email protected]                 }
1812ad83dc6aS[email protected]                 return;
1813ad83dc6aS[email protected] 
18140bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
18159da54300S[email protected]                 log_info("sending hci_accept_connection_request");
181632ab9390Smatthias.ringwald                 connection->state = ACCEPTED_CONNECTION_REQUEST;
181734d2123cS[email protected]                 hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1818dbe1a790S[email protected]                 return;
18190bf6344aS[email protected] 
1820a6725849S[email protected] #ifdef HAVE_BLE
18210bf6344aS[email protected]             case SEND_CANCEL_CONNECTION:
18220bf6344aS[email protected]                 connection->state = SENT_CANCEL_CONNECTION;
18230bf6344aS[email protected]                 hci_send_cmd(&hci_le_create_connection_cancel);
18240bf6344aS[email protected]                 return;
1825a6725849S[email protected] #endif
18260bf6344aS[email protected]             case SEND_DISCONNECT:
18270bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
18287851196eSmatthias.ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
18290bf6344aS[email protected]                 return;
18300bf6344aS[email protected] 
18310bf6344aS[email protected]             default:
18320bf6344aS[email protected]                 break;
1833c7e0c5f6Smatthias.ringwald         }
1834c7e0c5f6Smatthias.ringwald 
183532ab9390Smatthias.ringwald         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
18369da54300S[email protected]             log_info("responding to link key request");
183734d2123cS[email protected]             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
183832ab9390Smatthias.ringwald             link_key_t link_key;
1839c77e8838S[email protected]             link_key_type_t link_key_type;
18403a9fb326S[email protected]             if ( hci_stack->remote_device_db
18413a9fb326S[email protected]               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
184234d2123cS[email protected]               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
18439ab95c90S[email protected]                connection->link_key_type = link_key_type;
184432ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
184532ab9390Smatthias.ringwald             } else {
184632ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
184732ab9390Smatthias.ringwald             }
1848dbe1a790S[email protected]             return;
184932ab9390Smatthias.ringwald         }
18501d6b20aeS[email protected] 
1851899283eaS[email protected]         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
18529da54300S[email protected]             log_info("denying to pin request");
1853899283eaS[email protected]             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
185434d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
18554c57c146S[email protected]             return;
18564c57c146S[email protected]         }
18574c57c146S[email protected] 
1858dbe1a790S[email protected]         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
185934d2123cS[email protected]             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
186082d8f825S[email protected]             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
186182d8f825S[email protected]             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1862106d6d11S[email protected]                 // tweak authentication requirements
18633a9fb326S[email protected]                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1864106d6d11S[email protected]                 if (connection->bonding_flags & BONDING_DEDICATED){
18659faad3abS[email protected]                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
18669faad3abS[email protected]                 }
18679faad3abS[email protected]                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
18689faad3abS[email protected]                     authreq |= 1;
1869106d6d11S[email protected]                 }
18703a9fb326S[email protected]                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1871f8fb5f6eS[email protected]             } else {
1872f8fb5f6eS[email protected]                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1873f8fb5f6eS[email protected]             }
1874dbe1a790S[email protected]             return;
187532ab9390Smatthias.ringwald         }
187632ab9390Smatthias.ringwald 
1877dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1878dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
187934d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1880dbe1a790S[email protected]             return;
1881dbe1a790S[email protected]         }
1882dbe1a790S[email protected] 
1883dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1884dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
188534d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1886dbe1a790S[email protected]             return;
1887dbe1a790S[email protected]         }
1888afd4e962S[email protected] 
1889afd4e962S[email protected]         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1890afd4e962S[email protected]             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
189134d2123cS[email protected]             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
18922bd8b7e7S[email protected]             return;
18932bd8b7e7S[email protected]         }
18942bd8b7e7S[email protected] 
18952bd8b7e7S[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
18962bd8b7e7S[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
189734d2123cS[email protected]             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
189834d2123cS[email protected]             return;
189934d2123cS[email protected]         }
1900ad83dc6aS[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1901ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
19021bd5283dS[email protected]             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
190352d34f98S[email protected]             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1904ad83dc6aS[email protected]             return;
1905ad83dc6aS[email protected]         }
190634d2123cS[email protected]         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
190734d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
190834d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
19092bd8b7e7S[email protected]             return;
1910afd4e962S[email protected]         }
1911dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1912dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1913dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1914dce78009S[email protected]             return;
1915dce78009S[email protected]         }
1916c37a3166S[email protected] #ifdef HAVE_BLE
1917c37a3166S[email protected]         if (connection->le_conn_interval_min){
1918c37a3166S[email protected]             uint16_t connection_interval_min = connection->le_conn_interval_min;
1919c37a3166S[email protected]             connection->le_conn_interval_min = 0;
1920c37a3166S[email protected]             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
1921c37a3166S[email protected]                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
1922c37a3166S[email protected]                 0x0000, 0xffff);
1923c37a3166S[email protected]         }
1924c37a3166S[email protected] #endif
1925dbe1a790S[email protected]     }
1926c7e0c5f6Smatthias.ringwald 
1927452cf3bbS[email protected]     // send continuation fragments
1928452cf3bbS[email protected]     if (hci_stack->acl_fragmentation_total_size > 0) {
1929452cf3bbS[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
1930452cf3bbS[email protected]         if (hci_can_send_prepared_acl_packet_now(con_handle)){
1931452cf3bbS[email protected]             hci_connection_t *connection = hci_connection_for_handle(con_handle);
1932452cf3bbS[email protected]             if (connection) {
1933452cf3bbS[email protected]                 hci_send_acl_packet_fragments(connection);
1934452cf3bbS[email protected]                 return;
1935452cf3bbS[email protected]             }
1936452cf3bbS[email protected]             // connection gone -> discard further fragments
1937452cf3bbS[email protected]             hci_stack->acl_fragmentation_total_size = 0;
1938452cf3bbS[email protected]             hci_stack->acl_fragmentation_pos = 0;
1939452cf3bbS[email protected]         }
1940452cf3bbS[email protected]     }
1941452cf3bbS[email protected] 
19423a9fb326S[email protected]     switch (hci_stack->state){
19433429f56bSmatthias.ringwald         case HCI_STATE_INITIALIZING:
1944bd88fde9S[email protected]             hci_initializing_state_machine();
19453429f56bSmatthias.ringwald             break;
1946c7e0c5f6Smatthias.ringwald 
1947c7e0c5f6Smatthias.ringwald         case HCI_STATE_HALTING:
1948c7e0c5f6Smatthias.ringwald 
19499da54300S[email protected]             log_info("HCI_STATE_HALTING");
1950c7e0c5f6Smatthias.ringwald             // close all open connections
19513a9fb326S[email protected]             connection =  (hci_connection_t *) hci_stack->connections;
1952c7e0c5f6Smatthias.ringwald             if (connection){
195332ab9390Smatthias.ringwald 
1954c7e0c5f6Smatthias.ringwald                 // send disconnect
1955d94d3cafS[email protected]                 if (!hci_can_send_command_packet_now()) return;
195632ab9390Smatthias.ringwald 
19579da54300S[email protected]                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
19586ad890d3Smatthias.ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1959c7e0c5f6Smatthias.ringwald 
1960c7e0c5f6Smatthias.ringwald                 // send disconnected event right away - causes higher layer connections to get closed, too.
1961c7e0c5f6Smatthias.ringwald                 hci_shutdown_connection(connection);
1962c7e0c5f6Smatthias.ringwald                 return;
1963c7e0c5f6Smatthias.ringwald             }
19649da54300S[email protected]             log_info("HCI_STATE_HALTING, calling off");
1965c7e0c5f6Smatthias.ringwald 
196672ea5239Smatthias.ringwald             // switch mode
1967c7e0c5f6Smatthias.ringwald             hci_power_control_off();
19689418f9c9Smatthias.ringwald 
19699da54300S[email protected]             log_info("HCI_STATE_HALTING, emitting state");
197072ea5239Smatthias.ringwald             hci_emit_state();
19719da54300S[email protected]             log_info("HCI_STATE_HALTING, done");
197272ea5239Smatthias.ringwald             break;
1973c7e0c5f6Smatthias.ringwald 
197472ea5239Smatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
19753a9fb326S[email protected]             switch(hci_stack->substate) {
197689db417bSmatthias.ringwald                 case 0:
19779da54300S[email protected]                     log_info("HCI_STATE_FALLING_ASLEEP");
197872ea5239Smatthias.ringwald                     // close all open connections
19793a9fb326S[email protected]                     connection =  (hci_connection_t *) hci_stack->connections;
198066da7044Smatthias.ringwald 
198128171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
198266da7044Smatthias.ringwald                     // don't close connections, if H4 supports power management
198366da7044Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
198466da7044Smatthias.ringwald                         connection = NULL;
198566da7044Smatthias.ringwald                     }
198666da7044Smatthias.ringwald #endif
198772ea5239Smatthias.ringwald                     if (connection){
198832ab9390Smatthias.ringwald 
198972ea5239Smatthias.ringwald                         // send disconnect
1990d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
199132ab9390Smatthias.ringwald 
19929da54300S[email protected]                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
19936ad890d3Smatthias.ringwald                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
199472ea5239Smatthias.ringwald 
199572ea5239Smatthias.ringwald                         // send disconnected event right away - causes higher layer connections to get closed, too.
199672ea5239Smatthias.ringwald                         hci_shutdown_connection(connection);
199772ea5239Smatthias.ringwald                         return;
199872ea5239Smatthias.ringwald                     }
199972ea5239Smatthias.ringwald 
200092368cd3S[email protected]                     if (hci_classic_supported()){
200189db417bSmatthias.ringwald                         // disable page and inquiry scan
2002d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
200332ab9390Smatthias.ringwald 
20049da54300S[email protected]                         log_info("HCI_STATE_HALTING, disabling inq scans");
20053a9fb326S[email protected]                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
200689db417bSmatthias.ringwald 
200789db417bSmatthias.ringwald                         // continue in next sub state
20083a9fb326S[email protected]                         hci_stack->substate++;
200989db417bSmatthias.ringwald                         break;
201092368cd3S[email protected]                     }
201192368cd3S[email protected]                     // fall through for ble-only chips
201292368cd3S[email protected] 
201389db417bSmatthias.ringwald                 case 2:
20149da54300S[email protected]                     log_info("HCI_STATE_HALTING, calling sleep");
201528171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
201628171530Smatthias.ringwald                     // don't actually go to sleep, if H4 supports power management
201728171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
201828171530Smatthias.ringwald                         // SLEEP MODE reached
20193a9fb326S[email protected]                         hci_stack->state = HCI_STATE_SLEEPING;
202028171530Smatthias.ringwald                         hci_emit_state();
202128171530Smatthias.ringwald                         break;
202228171530Smatthias.ringwald                     }
202328171530Smatthias.ringwald #endif
202472ea5239Smatthias.ringwald                     // switch mode
20253a9fb326S[email protected]                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
2026c7e0c5f6Smatthias.ringwald                     hci_emit_state();
202728171530Smatthias.ringwald                     break;
202828171530Smatthias.ringwald 
202989db417bSmatthias.ringwald                 default:
203089db417bSmatthias.ringwald                     break;
203189db417bSmatthias.ringwald             }
2032c7e0c5f6Smatthias.ringwald             break;
2033c7e0c5f6Smatthias.ringwald 
20343429f56bSmatthias.ringwald         default:
20353429f56bSmatthias.ringwald             break;
20361f504dbdSmatthias.ringwald     }
20373429f56bSmatthias.ringwald }
203816833f0aSmatthias.ringwald 
203931452debSmatthias.ringwald int hci_send_cmd_packet(uint8_t *packet, int size){
2040c8e4258aSmatthias.ringwald     bd_addr_t addr;
2041c8e4258aSmatthias.ringwald     hci_connection_t * conn;
2042c8e4258aSmatthias.ringwald     // house-keeping
2043c8e4258aSmatthias.ringwald 
2044c8e4258aSmatthias.ringwald     // create_connection?
2045c8e4258aSmatthias.ringwald     if (IS_COMMAND(packet, hci_create_connection)){
2046c8e4258aSmatthias.ringwald         bt_flip_addr(addr, &packet[3]);
20479da54300S[email protected]         log_info("Create_connection to %s", bd_addr_to_str(addr));
2048c8e4258aSmatthias.ringwald 
204996a45072S[email protected]         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2050ad83dc6aS[email protected]         if (!conn){
205196a45072S[email protected]             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
205217f1ba2aSmatthias.ringwald             if (!conn){
205317f1ba2aSmatthias.ringwald                 // notify client that alloc failed
205417f1ba2aSmatthias.ringwald                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
205517f1ba2aSmatthias.ringwald                 return 0; // don't sent packet to controller
205617f1ba2aSmatthias.ringwald             }
2057ad83dc6aS[email protected]             conn->state = SEND_CREATE_CONNECTION;
2058ad83dc6aS[email protected]         }
2059ad83dc6aS[email protected]         log_info("conn state %u", conn->state);
2060ad83dc6aS[email protected]         switch (conn->state){
2061ad83dc6aS[email protected]             // if connection active exists
2062ad83dc6aS[email protected]             case OPEN:
206362bda3fbS[email protected]                 // and OPEN, emit connection complete command, don't send to controller
2064ad83dc6aS[email protected]                 hci_emit_connection_complete(conn, 0);
206562bda3fbS[email protected]                 return 0;
2066ad83dc6aS[email protected]             case SEND_CREATE_CONNECTION:
2067ad83dc6aS[email protected]                 // connection created by hci, e.g. dedicated bonding
2068ad83dc6aS[email protected]                 break;
2069ad83dc6aS[email protected]             default:
2070ad83dc6aS[email protected]                 // otherwise, just ignore as it is already in the open process
2071ad83dc6aS[email protected]                 return 0;
2072ad83dc6aS[email protected]         }
2073c8e4258aSmatthias.ringwald         conn->state = SENT_CREATE_CONNECTION;
2074c8e4258aSmatthias.ringwald     }
2075c8e4258aSmatthias.ringwald 
20767fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_reply)){
20777fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
20787fde4af9Smatthias.ringwald     }
20797fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
20807fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
20817fde4af9Smatthias.ringwald     }
20827fde4af9Smatthias.ringwald 
20838ef73945Smatthias.ringwald     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
20843a9fb326S[email protected]         if (hci_stack->remote_device_db){
20858ef73945Smatthias.ringwald             bt_flip_addr(addr, &packet[3]);
20863a9fb326S[email protected]             hci_stack->remote_device_db->delete_link_key(&addr);
20878ef73945Smatthias.ringwald         }
20888ef73945Smatthias.ringwald     }
2089c8e4258aSmatthias.ringwald 
20906724cd9eS[email protected]     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
20916724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
20926724cd9eS[email protected]         bt_flip_addr(addr, &packet[3]);
209396a45072S[email protected]         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
20946724cd9eS[email protected]         if (conn){
20956724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
20966724cd9eS[email protected]         }
20976724cd9eS[email protected]     }
20986724cd9eS[email protected] 
20996724cd9eS[email protected]     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
21006724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
21016724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
21026724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
21036724cd9eS[email protected]         bt_flip_addr(addr, &packet[3]);
210496a45072S[email protected]         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
21056724cd9eS[email protected]         if (conn){
21066724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
21076724cd9eS[email protected]         }
21086724cd9eS[email protected]     }
21096724cd9eS[email protected] 
211069a97523S[email protected] #ifdef HAVE_BLE
211169a97523S[email protected]     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
21123a9fb326S[email protected]         hci_stack->adv_addr_type = packet[8];
211369a97523S[email protected]     }
211469a97523S[email protected]     if (IS_COMMAND(packet, hci_le_set_random_address)){
21153a9fb326S[email protected]         bt_flip_addr(hci_stack->adv_address, &packet[3]);
211669a97523S[email protected]     }
211769a97523S[email protected] #endif
211869a97523S[email protected] 
21193a9fb326S[email protected]     hci_stack->num_cmd_packets--;
21206b4af23dS[email protected]     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
21216b4af23dS[email protected] 
21226b4af23dS[email protected]     // free packet buffer for synchronous transport implementations
2123c8b9416aS[email protected]     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
21246b4af23dS[email protected]         hci_stack->hci_packet_buffer_reserved = 0;
21256b4af23dS[email protected]     }
21266b4af23dS[email protected] 
21276b4af23dS[email protected]     return err;
212831452debSmatthias.ringwald }
21298adf0ddaSmatthias.ringwald 
21302bd8b7e7S[email protected] // disconnect because of security block
21312bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
21322bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
21332bd8b7e7S[email protected]     if (!connection) return;
21342bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
21352bd8b7e7S[email protected] }
21362bd8b7e7S[email protected] 
21372bd8b7e7S[email protected] 
2138dbe1a790S[email protected] // Configure Secure Simple Pairing
2139dbe1a790S[email protected] 
2140dbe1a790S[email protected] // enable will enable SSP during init
2141dbe1a790S[email protected] void hci_ssp_set_enable(int enable){
21423a9fb326S[email protected]     hci_stack->ssp_enable = enable;
2143dbe1a790S[email protected] }
2144dbe1a790S[email protected] 
21452bd8b7e7S[email protected] int hci_local_ssp_activated(){
21463a9fb326S[email protected]     return hci_ssp_supported() && hci_stack->ssp_enable;
21472bd8b7e7S[email protected] }
21482bd8b7e7S[email protected] 
2149dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
2150dbe1a790S[email protected] void hci_ssp_set_io_capability(int io_capability){
21513a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
2152dbe1a790S[email protected] }
2153dbe1a790S[email protected] void hci_ssp_set_authentication_requirement(int authentication_requirement){
21543a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
2155dbe1a790S[email protected] }
2156dbe1a790S[email protected] 
2157dbe1a790S[email protected] // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2158dbe1a790S[email protected] void hci_ssp_set_auto_accept(int auto_accept){
21593a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
2160dbe1a790S[email protected] }
2161dbe1a790S[email protected] 
21621cd208adSmatthias.ringwald /**
21631cd208adSmatthias.ringwald  * pre: numcmds >= 0 - it's allowed to send a command to the controller
21641cd208adSmatthias.ringwald  */
2165fe35119dSmatthias.ringwald int hci_send_cmd(const hci_cmd_t *cmd, ...){
21665127cc62S[email protected] 
2167d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()){
21689d14b626S[email protected]         log_error("hci_send_cmd called but cannot send packet now");
21699d14b626S[email protected]         return 0;
21709d14b626S[email protected]     }
21719d14b626S[email protected] 
21725127cc62S[email protected]     // for HCI INITIALIZATION
21739da54300S[email protected]     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
21745127cc62S[email protected]     hci_stack->last_cmd_opcode = cmd->opcode;
21755127cc62S[email protected] 
21769d14b626S[email protected]     hci_reserve_packet_buffer();
21779d14b626S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
21789d14b626S[email protected] 
21791cd208adSmatthias.ringwald     va_list argptr;
21801cd208adSmatthias.ringwald     va_start(argptr, cmd);
21819d14b626S[email protected]     uint16_t size = hci_create_cmd_internal(packet, cmd, argptr);
21821cd208adSmatthias.ringwald     va_end(argptr);
21839d14b626S[email protected] 
21849d14b626S[email protected]     return hci_send_cmd_packet(packet, size);
218593b8dc03Smatthias.ringwald }
2186c8e4258aSmatthias.ringwald 
2187ee091cf1Smatthias.ringwald // Create various non-HCI events.
2188ee091cf1Smatthias.ringwald // TODO: generalize, use table similar to hci_create_command
2189ee091cf1Smatthias.ringwald 
2190c8e4258aSmatthias.ringwald void hci_emit_state(){
21913a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2192425d1371Smatthias.ringwald     uint8_t event[3];
219380d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
2194425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
21953a9fb326S[email protected]     event[2] = hci_stack->state;
2196425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
21973a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2198c8e4258aSmatthias.ringwald }
2199c8e4258aSmatthias.ringwald 
220017f1ba2aSmatthias.ringwald void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
2201425d1371Smatthias.ringwald     uint8_t event[13];
2202c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
2203425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
220417f1ba2aSmatthias.ringwald     event[2] = status;
2205c8e4258aSmatthias.ringwald     bt_store_16(event, 3, conn->con_handle);
2206c8e4258aSmatthias.ringwald     bt_flip_addr(&event[5], conn->address);
2207c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
2208c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
2209425d1371Smatthias.ringwald     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
22103a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2211c8e4258aSmatthias.ringwald }
2212c8e4258aSmatthias.ringwald 
22134f3229d8S[email protected] void hci_emit_le_connection_complete(hci_connection_t *conn, uint8_t status){
22144f3229d8S[email protected]     uint8_t event[21];
22154f3229d8S[email protected]     event[0] = HCI_EVENT_LE_META;
22164f3229d8S[email protected]     event[1] = sizeof(event) - 2;
22174f3229d8S[email protected]     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
22184f3229d8S[email protected]     event[3] = status;
22194f3229d8S[email protected]     bt_store_16(event, 4, conn->con_handle);
22204f3229d8S[email protected]     event[6] = 0; // TODO: role
22214f3229d8S[email protected]     event[7] = conn->address_type;
22224f3229d8S[email protected]     bt_flip_addr(&event[8], conn->address);
22234f3229d8S[email protected]     bt_store_16(event, 14, 0); // interval
22244f3229d8S[email protected]     bt_store_16(event, 16, 0); // latency
22254f3229d8S[email protected]     bt_store_16(event, 18, 0); // supervision timeout
22264f3229d8S[email protected]     event[20] = 0; // master clock accuracy
22274f3229d8S[email protected]     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
22284f3229d8S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
22294f3229d8S[email protected] }
22304f3229d8S[email protected] 
22313c4d4b90Smatthias.ringwald void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
2232425d1371Smatthias.ringwald     uint8_t event[6];
22333c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
2234e518c4b8Smatthias.ringwald     event[1] = sizeof(event) - 2;
22353c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
22363c4d4b90Smatthias.ringwald     bt_store_16(event, 3, handle);
22373c4d4b90Smatthias.ringwald     event[5] = reason;
2238425d1371Smatthias.ringwald     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
22393a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
22403c4d4b90Smatthias.ringwald }
22413c4d4b90Smatthias.ringwald 
2242ee091cf1Smatthias.ringwald void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
224366fb9560S[email protected]     if (disable_l2cap_timeouts) return;
2244e0abb8e7S[email protected]     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
2245425d1371Smatthias.ringwald     uint8_t event[4];
224680d52d6bSmatthias.ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
2247425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2248ee091cf1Smatthias.ringwald     bt_store_16(event, 2, conn->con_handle);
2249425d1371Smatthias.ringwald     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
22503a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2251ee091cf1Smatthias.ringwald }
225243bfb1bdSmatthias.ringwald 
225343bfb1bdSmatthias.ringwald void hci_emit_nr_connections_changed(){
2254e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
2255425d1371Smatthias.ringwald     uint8_t event[3];
225680d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
2257425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
225843bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
2259425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
22603a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
226143bfb1bdSmatthias.ringwald }
2262038bc64cSmatthias.ringwald 
2263038bc64cSmatthias.ringwald void hci_emit_hci_open_failed(){
2264e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
2265425d1371Smatthias.ringwald     uint8_t event[2];
226680d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
2267425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2268425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
22693a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2270038bc64cSmatthias.ringwald }
22711b0e3922Smatthias.ringwald 
227209ba8edeSmatthias.ringwald #ifndef EMBEDDED
22731b0e3922Smatthias.ringwald void hci_emit_btstack_version() {
2274e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
2275425d1371Smatthias.ringwald     uint8_t event[6];
22761b0e3922Smatthias.ringwald     event[0] = BTSTACK_EVENT_VERSION;
2277425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2278425d1371Smatthias.ringwald     event[2] = BTSTACK_MAJOR;
2279425d1371Smatthias.ringwald     event[3] = BTSTACK_MINOR;
2280425d1371Smatthias.ringwald     bt_store_16(event, 4, BTSTACK_REVISION);
2281425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
22823a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
22831b0e3922Smatthias.ringwald }
228409ba8edeSmatthias.ringwald #endif
22851b0e3922Smatthias.ringwald 
22862ed6235cSmatthias.ringwald void hci_emit_system_bluetooth_enabled(uint8_t enabled){
2287e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
2288425d1371Smatthias.ringwald     uint8_t event[3];
22892ed6235cSmatthias.ringwald     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
2290425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
22912ed6235cSmatthias.ringwald     event[2] = enabled;
2292425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
22933a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
22942ed6235cSmatthias.ringwald }
2295627c2f45Smatthias.ringwald 
2296627c2f45Smatthias.ringwald void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
2297e0abb8e7S[email protected]     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
2298627c2f45Smatthias.ringwald     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
2299e0abb8e7S[email protected]     event[1] = sizeof(event) - 2 - 1;
2300f653b6bdSmatthias.ringwald     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
23012f89d309Smatthias.ringwald     bt_flip_addr(&event[3], *addr);
2302f653b6bdSmatthias.ringwald     memcpy(&event[9], name, 248);
2303e0abb8e7S[email protected] 
2304e0abb8e7S[email protected]     event[9+248] = 0;   // assert \0 for log_info
2305e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2306e0abb8e7S[email protected] 
2307e0abb8e7S[email protected]     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
23083a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2309627c2f45Smatthias.ringwald }
2310381fbed8Smatthias.ringwald 
2311381fbed8Smatthias.ringwald void hci_emit_discoverable_enabled(uint8_t enabled){
2312e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2313425d1371Smatthias.ringwald     uint8_t event[3];
2314381fbed8Smatthias.ringwald     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2315425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2316381fbed8Smatthias.ringwald     event[2] = enabled;
2317425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23183a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2319381fbed8Smatthias.ringwald }
2320458bf4e8S[email protected] 
2321a00031e2S[email protected] void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2322df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2323a00031e2S[email protected]     uint8_t event[5];
2324e00caf9cS[email protected]     int pos = 0;
2325a00031e2S[email protected]     event[pos++] = GAP_SECURITY_LEVEL;
2326e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
2327a00031e2S[email protected]     bt_store_16(event, 2, con_handle);
2328e00caf9cS[email protected]     pos += 2;
2329e00caf9cS[email protected]     event[pos++] = level;
2330e00caf9cS[email protected]     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23313a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2332e00caf9cS[email protected] }
2333e00caf9cS[email protected] 
23341bd5283dS[email protected] void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
2335ad83dc6aS[email protected]     log_info("hci_emit_dedicated_bonding_result %u ", status);
2336ad83dc6aS[email protected]     uint8_t event[9];
2337ad83dc6aS[email protected]     int pos = 0;
2338ad83dc6aS[email protected]     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2339ad83dc6aS[email protected]     event[pos++] = sizeof(event) - 2;
2340ad83dc6aS[email protected]     event[pos++] = status;
23411bd5283dS[email protected]     bt_flip_addr( * (bd_addr_t *) &event[pos], address);
2342ad83dc6aS[email protected]     pos += 6;
2343ad83dc6aS[email protected]     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23443a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2345ad83dc6aS[email protected] }
2346ad83dc6aS[email protected] 
23472bd8b7e7S[email protected] // query if remote side supports SSP
23482bd8b7e7S[email protected] int hci_remote_ssp_supported(hci_con_handle_t con_handle){
23492bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
23502bd8b7e7S[email protected]     if (!connection) return 0;
23512bd8b7e7S[email protected]     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
23522bd8b7e7S[email protected] }
23532bd8b7e7S[email protected] 
2354df3354fcS[email protected] int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2355df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2356df3354fcS[email protected] }
2357df3354fcS[email protected] 
2358458bf4e8S[email protected] // GAP API
2359458bf4e8S[email protected] /**
2360458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
2361458bf4e8S[email protected]  * @praram enabled
2362458bf4e8S[email protected]  */
23634c57c146S[email protected] void gap_set_bondable_mode(int enable){
23643a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
2365458bf4e8S[email protected] }
2366cb230b9dS[email protected] 
2367cb230b9dS[email protected] /**
236834d2123cS[email protected]  * @brief map link keys to security levels
2369cb230b9dS[email protected]  */
237034d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
237134d2123cS[email protected]     switch (link_key_type){
23723c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
23733c68dfa9S[email protected]             return LEVEL_4;
23743c68dfa9S[email protected]         case COMBINATION_KEY:
23753c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
23763c68dfa9S[email protected]             return LEVEL_3;
23773c68dfa9S[email protected]         default:
23783c68dfa9S[email protected]             return LEVEL_2;
23793c68dfa9S[email protected]     }
2380cb230b9dS[email protected] }
2381cb230b9dS[email protected] 
2382a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
238334d2123cS[email protected]     if (!connection) return LEVEL_0;
238434d2123cS[email protected]     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
238534d2123cS[email protected]     return gap_security_level_for_link_key_type(connection->link_key_type);
238634d2123cS[email protected] }
238734d2123cS[email protected] 
238834d2123cS[email protected] 
2389106d6d11S[email protected] int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
23905127cc62S[email protected]     log_info("gap_mitm_protection_required_for_security_level %u", level);
2391106d6d11S[email protected]     return level > LEVEL_2;
2392106d6d11S[email protected] }
2393106d6d11S[email protected] 
239434d2123cS[email protected] /**
239534d2123cS[email protected]  * @brief get current security level
239634d2123cS[email protected]  */
239734d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
239834d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
239934d2123cS[email protected]     if (!connection) return LEVEL_0;
240034d2123cS[email protected]     return gap_security_level_for_connection(connection);
240134d2123cS[email protected] }
240234d2123cS[email protected] 
2403cb230b9dS[email protected] /**
2404cb230b9dS[email protected]  * @brief request connection to device to
2405cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
2406cb230b9dS[email protected]  */
240734d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
240834d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
240934d2123cS[email protected]     if (!connection){
2410a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
241134d2123cS[email protected]         return;
241234d2123cS[email protected]     }
241334d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
241434d2123cS[email protected]     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
241534d2123cS[email protected]     if (current_level >= requested_level){
2416a00031e2S[email protected]         hci_emit_security_level(con_handle, current_level);
241734d2123cS[email protected]         return;
241834d2123cS[email protected]     }
2419a00031e2S[email protected] 
242034d2123cS[email protected]     connection->requested_security_level = requested_level;
2421a00031e2S[email protected] 
2422fb8ba0dbS[email protected]     // would enabling ecnryption suffice (>= LEVEL_2)?
24233a9fb326S[email protected]     if (hci_stack->remote_device_db){
2424a00031e2S[email protected]         link_key_type_t link_key_type;
2425a00031e2S[email protected]         link_key_t      link_key;
24263a9fb326S[email protected]         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2427a00031e2S[email protected]             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2428a00031e2S[email protected]                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2429a00031e2S[email protected]                 return;
2430a00031e2S[email protected]             }
2431a00031e2S[email protected]         }
2432a00031e2S[email protected]     }
2433a00031e2S[email protected] 
24341eb2563eS[email protected]     // try to authenticate connection
24351eb2563eS[email protected]     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2436e80b2cf9S[email protected]     hci_run();
2437e00caf9cS[email protected] }
2438ad83dc6aS[email protected] 
2439ad83dc6aS[email protected] /**
2440ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
2441ad83dc6aS[email protected]  * @param device
2442ad83dc6aS[email protected]  * @param request MITM protection
2443ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
2444ad83dc6aS[email protected]  */
2445ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2446ad83dc6aS[email protected] 
2447ad83dc6aS[email protected]     // create connection state machine
244896a45072S[email protected]     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2449ad83dc6aS[email protected] 
2450ad83dc6aS[email protected]     if (!connection){
2451ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
2452ad83dc6aS[email protected]     }
2453ad83dc6aS[email protected] 
2454ad83dc6aS[email protected]     // delete linkn key
2455ad83dc6aS[email protected]     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2456ad83dc6aS[email protected] 
2457ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
2458ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
2459ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
24605127cc62S[email protected]     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
2461ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
2462ad83dc6aS[email protected] 
2463ad83dc6aS[email protected]     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2464ad83dc6aS[email protected] 
2465ad83dc6aS[email protected]     // handle: connnection failure (connection complete != ok)
2466ad83dc6aS[email protected]     // handle: authentication failure
2467ad83dc6aS[email protected]     // handle: disconnect on done
2468ad83dc6aS[email protected] 
2469ad83dc6aS[email protected]     hci_run();
2470ad83dc6aS[email protected] 
2471ad83dc6aS[email protected]     return 0;
2472ad83dc6aS[email protected] }
24738e618f72S[email protected] 
24748e618f72S[email protected] void gap_set_local_name(const char * local_name){
24758e618f72S[email protected]     hci_stack->local_name = local_name;
24768e618f72S[email protected] }
24778e618f72S[email protected] 
24787bdc6798S[email protected] le_command_status_t le_central_start_scan(){
247936af3e18S[email protected]     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
24807bdc6798S[email protected]     hci_stack->le_scanning_state = LE_START_SCAN;
24817bdc6798S[email protected]     hci_run();
24827bdc6798S[email protected]     return BLE_PERIPHERAL_OK;
24837bdc6798S[email protected] }
24848e618f72S[email protected] 
24857bdc6798S[email protected] le_command_status_t le_central_stop_scan(){
248636af3e18S[email protected]     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
24877bdc6798S[email protected]     hci_stack->le_scanning_state = LE_STOP_SCAN;
24887bdc6798S[email protected]     hci_run();
24897bdc6798S[email protected]     return BLE_PERIPHERAL_OK;
24907bdc6798S[email protected] }
24914f3229d8S[email protected] 
2492ef11999fSmatthias.ringwald void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
2493ef11999fSmatthias.ringwald     hci_stack->le_scan_type     = scan_type;
2494ef11999fSmatthias.ringwald     hci_stack->le_scan_interval = scan_interval;
2495ef11999fSmatthias.ringwald     hci_stack->le_scan_window   = scan_window;
2496ef11999fSmatthias.ringwald     hci_run();
2497ef11999fSmatthias.ringwald }
24984f3229d8S[email protected] 
24994f3229d8S[email protected] le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
25004f3229d8S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
25014f3229d8S[email protected]     if (!conn){
25021f479f8cS[email protected]         log_info("le_central_connect: no connection exists yet, creating context");
25034f3229d8S[email protected]         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
25044f3229d8S[email protected]         if (!conn){
25054f3229d8S[email protected]             // notify client that alloc failed
25064f3229d8S[email protected]             hci_emit_le_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
25071f479f8cS[email protected]             log_info("le_central_connect: failed to alloc context");
25084f3229d8S[email protected]             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
25094f3229d8S[email protected]         }
25104f3229d8S[email protected]         conn->state = SEND_CREATE_CONNECTION;
25111f479f8cS[email protected]         log_info("le_central_connect: send create connection next");
2512564fca32S[email protected]         hci_run();
25134f3229d8S[email protected]         return BLE_PERIPHERAL_OK;
25144f3229d8S[email protected]     }
25150bf6344aS[email protected] 
25160bf6344aS[email protected]     if (!hci_is_le_connection(conn) ||
25170bf6344aS[email protected]         conn->state == SEND_CREATE_CONNECTION ||
25180bf6344aS[email protected]         conn->state == SENT_CREATE_CONNECTION) {
25190bf6344aS[email protected]         hci_emit_le_connection_complete(conn, ERROR_CODE_COMMAND_DISALLOWED);
25201f479f8cS[email protected]         log_error("le_central_connect: classic connection or connect is already being created");
25210bf6344aS[email protected]         return BLE_PERIPHERAL_IN_WRONG_STATE;
25220bf6344aS[email protected]     }
25230bf6344aS[email protected] 
25241f479f8cS[email protected]     log_info("le_central_connect: context exists with state %u", conn->state);
25254f3229d8S[email protected]     hci_emit_le_connection_complete(conn, 0);
25264f3229d8S[email protected]     hci_run();
25274f3229d8S[email protected]     return BLE_PERIPHERAL_OK;
25284f3229d8S[email protected] }
25294f3229d8S[email protected] 
25307851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
25317851196eSmatthias.ringwald static hci_connection_t * le_central_get_outgoing_connection(){
25320bf6344aS[email protected]     linked_item_t *it;
25330bf6344aS[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
25340bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
25350bf6344aS[email protected]         if (!hci_is_le_connection(conn)) continue;
25360bf6344aS[email protected]         switch (conn->state){
2537a6725849S[email protected]             case SEND_CREATE_CONNECTION:
25387851196eSmatthias.ringwald             case SENT_CREATE_CONNECTION:
25397851196eSmatthias.ringwald                 return conn;
25407851196eSmatthias.ringwald             default:
25417851196eSmatthias.ringwald                 break;
25427851196eSmatthias.ringwald         };
25437851196eSmatthias.ringwald     }
25447851196eSmatthias.ringwald     return NULL;
25457851196eSmatthias.ringwald }
25467851196eSmatthias.ringwald 
25477851196eSmatthias.ringwald le_command_status_t le_central_connect_cancel(){
25487851196eSmatthias.ringwald     hci_connection_t * conn = le_central_get_outgoing_connection();
25497851196eSmatthias.ringwald     switch (conn->state){
25507851196eSmatthias.ringwald         case SEND_CREATE_CONNECTION:
25517851196eSmatthias.ringwald             // skip sending create connection and emit event instead
25520bf6344aS[email protected]             hci_emit_le_connection_complete(conn, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
25537851196eSmatthias.ringwald             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
25547851196eSmatthias.ringwald             btstack_memory_hci_connection_free( conn );
25550bf6344aS[email protected]             break;
2556a6725849S[email protected]         case SENT_CREATE_CONNECTION:
25577851196eSmatthias.ringwald             // request to send cancel connection
25580bf6344aS[email protected]             conn->state = SEND_CANCEL_CONNECTION;
25590bf6344aS[email protected]             hci_run();
25600bf6344aS[email protected]             break;
25610bf6344aS[email protected]         default:
25620bf6344aS[email protected]             break;
25630bf6344aS[email protected]     }
2564e31f89a7S[email protected]     return BLE_PERIPHERAL_OK;
2565e31f89a7S[email protected] }
25664f3229d8S[email protected] 
2567c37a3166S[email protected] /**
2568c37a3166S[email protected]  * @brief Updates the connection parameters for a given LE connection
2569c37a3166S[email protected]  * @param handle
2570c37a3166S[email protected]  * @param conn_interval_min (unit: 1.25ms)
2571c37a3166S[email protected]  * @param conn_interval_max (unit: 1.25ms)
2572c37a3166S[email protected]  * @param conn_latency
2573c37a3166S[email protected]  * @param supervision_timeout (unit: 10ms)
2574c37a3166S[email protected]  * @returns 0 if ok
2575c37a3166S[email protected]  */
2576c37a3166S[email protected] int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
2577c37a3166S[email protected]     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
2578c37a3166S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2579c37a3166S[email protected]     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2580c37a3166S[email protected]     connection->le_conn_interval_min = conn_interval_min;
2581c37a3166S[email protected]     connection->le_conn_interval_max = conn_interval_max;
2582c37a3166S[email protected]     connection->le_conn_latency = conn_latency;
2583c37a3166S[email protected]     connection->le_supervision_timeout = supervision_timeout;
2584c37a3166S[email protected]     return 0;
2585c37a3166S[email protected] }
2586c37a3166S[email protected] 
25875917a5c5S[email protected] le_command_status_t gap_disconnect(hci_con_handle_t handle){
25885917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
25895917a5c5S[email protected]     if (!conn){
25907851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
25915917a5c5S[email protected]         return BLE_PERIPHERAL_OK;
25925917a5c5S[email protected]     }
25935917a5c5S[email protected]     conn->state = SEND_DISCONNECT;
25945917a5c5S[email protected]     hci_run();
25954f3229d8S[email protected]     return BLE_PERIPHERAL_OK;
25964f3229d8S[email protected] }
259704a6ef8cSmatthias.ringwald 
259804a6ef8cSmatthias.ringwald void hci_disconnect_all(){
259904a6ef8cSmatthias.ringwald     linked_list_iterator_t it;
260004a6ef8cSmatthias.ringwald     linked_list_iterator_init(&it, &hci_stack->connections);
260104a6ef8cSmatthias.ringwald     while (linked_list_iterator_has_next(&it)){
260204a6ef8cSmatthias.ringwald         hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it);
260304a6ef8cSmatthias.ringwald         if (con->state == SENT_DISCONNECT) continue;
260404a6ef8cSmatthias.ringwald         con->state = SEND_DISCONNECT;
260504a6ef8cSmatthias.ringwald     }
2606d31fba26S[email protected]     hci_run();
260704a6ef8cSmatthias.ringwald }
2608