xref: /btstack/src/hci.c (revision 3ac2fe56674c9bbafa9a43ead832b2ab440e906d)
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 
62da886c03S[email protected] #include <btstack/linked_list.h>
63ae1fd9f3Smatthias.ringwald #include <btstack/hci_cmds.h>
641b0e3922Smatthias.ringwald 
65169f8b28Smatthias.ringwald #define HCI_CONNECTION_TIMEOUT_MS 10000
66ee091cf1Smatthias.ringwald 
67a45d6b9fS[email protected] #define HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP 11
68da5275c5S[email protected] 
6928171530Smatthias.ringwald #ifdef USE_BLUETOOL
703d7a3f67S[email protected] #include "../platforms/ios/src/bt_control_iphone.h"
7128171530Smatthias.ringwald #endif
7228171530Smatthias.ringwald 
73758b46ceSmatthias.ringwald static void hci_update_scan_enable(void);
74a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
7596a45072S[email protected] static void hci_connection_timeout_handler(timer_source_t *timer);
7696a45072S[email protected] static void hci_connection_timestamp(hci_connection_t *connection);
777586ee35S[email protected] static int  hci_power_control_on(void);
787586ee35S[email protected] static void hci_power_control_off(void);
796155b3d3S[email protected] static void hci_state_reset();
80758b46ceSmatthias.ringwald 
8106b35ec0Smatthias.ringwald // the STACK is here
823a9fb326S[email protected] #ifndef HAVE_MALLOC
833a9fb326S[email protected] static hci_stack_t   hci_stack_static;
843a9fb326S[email protected] #endif
853a9fb326S[email protected] static hci_stack_t * hci_stack = NULL;
8616833f0aSmatthias.ringwald 
8766fb9560S[email protected] // test helper
8866fb9560S[email protected] static uint8_t disable_l2cap_timeouts = 0;
8966fb9560S[email protected] 
9096a45072S[email protected] /**
9196a45072S[email protected]  * create connection for given address
9296a45072S[email protected]  *
9396a45072S[email protected]  * @return connection OR NULL, if no memory left
9496a45072S[email protected]  */
9596a45072S[email protected] static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
9696a45072S[email protected] 
975127cc62S[email protected]     log_info("create_connection_for_addr %s", bd_addr_to_str(addr));
98bb69aaaeS[email protected]     hci_connection_t * conn = btstack_memory_hci_connection_get();
9996a45072S[email protected]     if (!conn) return NULL;
10096a45072S[email protected]     BD_ADDR_COPY(conn->address, addr);
10196a45072S[email protected]     conn->address_type = addr_type;
10296a45072S[email protected]     conn->con_handle = 0xffff;
10396a45072S[email protected]     conn->authentication_flags = AUTH_FLAGS_NONE;
10496a45072S[email protected]     conn->bonding_flags = 0;
10596a45072S[email protected]     conn->requested_security_level = LEVEL_0;
10696a45072S[email protected]     linked_item_set_user(&conn->timeout.item, conn);
10796a45072S[email protected]     conn->timeout.process = hci_connection_timeout_handler;
10896a45072S[email protected]     hci_connection_timestamp(conn);
10996a45072S[email protected]     conn->acl_recombination_length = 0;
11096a45072S[email protected]     conn->acl_recombination_pos = 0;
11196a45072S[email protected]     conn->num_acl_packets_sent = 0;
112da886c03S[email protected]     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
11396a45072S[email protected]     linked_list_add(&hci_stack->connections, (linked_item_t *) conn);
11496a45072S[email protected]     return conn;
11596a45072S[email protected] }
11666fb9560S[email protected] 
117da886c03S[email protected] 
118da886c03S[email protected] /**
119da886c03S[email protected]  * get le connection parameter range
120da886c03S[email protected] *
121da886c03S[email protected]  * @return le connection parameter range struct
122da886c03S[email protected]  */
123da886c03S[email protected] le_connection_parameter_range_t gap_le_get_connection_parameter_range(){
124da886c03S[email protected]     return hci_stack->le_connection_parameter_range;
125da886c03S[email protected] }
126da886c03S[email protected] 
127da886c03S[email protected] /**
128da886c03S[email protected]  * set le connection parameter range
129da886c03S[email protected]  *
130da886c03S[email protected]  */
131da886c03S[email protected] 
132da886c03S[email protected] void gap_le_set_connection_parameter_range(le_connection_parameter_range_t range){
133da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_interval_min = range.le_conn_interval_min;
134da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_interval_max = range.le_conn_interval_max;
135da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_interval_min = range.le_conn_latency_min;
136da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_interval_max = range.le_conn_latency_max;
137da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = range.le_supervision_timeout_min;
138da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = range.le_supervision_timeout_max;
139da886c03S[email protected] }
140da886c03S[email protected] 
141da886c03S[email protected] /**
142da886c03S[email protected]  * get hci connections iterator
143da886c03S[email protected]  *
144da886c03S[email protected]  * @return hci connections iterator
145da886c03S[email protected]  */
146da886c03S[email protected] 
147da886c03S[email protected] void hci_connections_get_iterator(linked_list_iterator_t *it){
148da886c03S[email protected]     linked_list_iterator_init(it, &hci_stack->connections);
149da886c03S[email protected] }
150da886c03S[email protected] 
15197addcc5Smatthias.ringwald /**
152ee091cf1Smatthias.ringwald  * get connection for a given handle
153ee091cf1Smatthias.ringwald  *
154ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
155ee091cf1Smatthias.ringwald  */
1565061f3afS[email protected] hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
157da886c03S[email protected]     linked_list_iterator_t it;
158da886c03S[email protected]     linked_list_iterator_init(&it, &hci_stack->connections);
159da886c03S[email protected]     while (linked_list_iterator_has_next(&it)){
160da886c03S[email protected]         hci_connection_t * item = (hci_connection_t *) linked_list_iterator_next(&it);
161*3ac2fe56S[email protected]         if ( item->con_handle == con_handle ) {
162da886c03S[email protected]             return item;
163ee091cf1Smatthias.ringwald         }
164ee091cf1Smatthias.ringwald     }
165ee091cf1Smatthias.ringwald     return NULL;
166ee091cf1Smatthias.ringwald }
167ee091cf1Smatthias.ringwald 
16896a45072S[email protected] /**
16996a45072S[email protected]  * get connection for given address
17096a45072S[email protected]  *
17196a45072S[email protected]  * @return connection OR NULL, if not found
17296a45072S[email protected]  */
17396a45072S[email protected] hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t * addr, bd_addr_type_t addr_type){
174da886c03S[email protected]     linked_list_iterator_t it;
175da886c03S[email protected]     linked_list_iterator_init(&it, &hci_stack->connections);
176da886c03S[email protected]     while (linked_list_iterator_has_next(&it)){
177da886c03S[email protected]         hci_connection_t * connection = (hci_connection_t *) linked_list_iterator_next(&it);
17896a45072S[email protected]         if (connection->address_type != addr_type)  continue;
17996a45072S[email protected]         if (memcmp(addr, connection->address, 6) != 0) continue;
18062bda3fbS[email protected]         return connection;
18162bda3fbS[email protected]     }
18262bda3fbS[email protected]     return NULL;
18362bda3fbS[email protected] }
18462bda3fbS[email protected] 
1852b12a0b9Smatthias.ringwald static void hci_connection_timeout_handler(timer_source_t *timer){
18628ca2b46S[email protected]     hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item);
187c785ef68Smatthias.ringwald #ifdef HAVE_TIME
188ee091cf1Smatthias.ringwald     struct timeval tv;
189ee091cf1Smatthias.ringwald     gettimeofday(&tv, NULL);
190c21e6239Smatthias.ringwald     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
191ee091cf1Smatthias.ringwald         // connections might be timed out
192ee091cf1Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
193ee091cf1Smatthias.ringwald     }
1942b12a0b9Smatthias.ringwald #endif
195e5780900Smatthias.ringwald #ifdef HAVE_TICK
196c785ef68Smatthias.ringwald     if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
197c785ef68Smatthias.ringwald         // connections might be timed out
198c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
199c785ef68Smatthias.ringwald     }
200c785ef68Smatthias.ringwald #endif
201c785ef68Smatthias.ringwald     run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
202c785ef68Smatthias.ringwald     run_loop_add_timer(timer);
203c785ef68Smatthias.ringwald }
204ee091cf1Smatthias.ringwald 
205ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
206c7492964Smatthias.ringwald #ifdef HAVE_TIME
207ee091cf1Smatthias.ringwald     gettimeofday(&connection->timestamp, NULL);
208c7492964Smatthias.ringwald #endif
209e5780900Smatthias.ringwald #ifdef HAVE_TICK
210c785ef68Smatthias.ringwald     connection->timestamp = embedded_get_ticks();
211c785ef68Smatthias.ringwald #endif
212ee091cf1Smatthias.ringwald }
213ee091cf1Smatthias.ringwald 
21406b35ec0Smatthias.ringwald 
21528ca2b46S[email protected] inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
21628ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
21728ca2b46S[email protected] }
21828ca2b46S[email protected] 
21928ca2b46S[email protected] inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
22028ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
22128ca2b46S[email protected] }
22228ca2b46S[email protected] 
22328ca2b46S[email protected] 
22443bfb1bdSmatthias.ringwald /**
22580ca58a0Smatthias.ringwald  * add authentication flags and reset timer
22696a45072S[email protected]  * @note: assumes classic connection
2277fde4af9Smatthias.ringwald  */
2287fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
2297fde4af9Smatthias.ringwald     bd_addr_t addr;
2307fde4af9Smatthias.ringwald     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
23196a45072S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2327fde4af9Smatthias.ringwald     if (conn) {
23328ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
23480ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
2357fde4af9Smatthias.ringwald     }
2367fde4af9Smatthias.ringwald }
2377fde4af9Smatthias.ringwald 
23880ca58a0Smatthias.ringwald int  hci_authentication_active_for_handle(hci_con_handle_t handle){
2395061f3afS[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
24080ca58a0Smatthias.ringwald     if (!conn) return 0;
2416724cd9eS[email protected]     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
2426724cd9eS[email protected]     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
2436724cd9eS[email protected]     return 0;
24480ca58a0Smatthias.ringwald }
24580ca58a0Smatthias.ringwald 
246c12e46e7Smatthias.ringwald void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
2473a9fb326S[email protected]     if (hci_stack->remote_device_db) {
2483a9fb326S[email protected]         hci_stack->remote_device_db->delete_link_key(addr);
249c12e46e7Smatthias.ringwald     }
250c12e46e7Smatthias.ringwald }
251c12e46e7Smatthias.ringwald 
2520bf6344aS[email protected] int hci_is_le_connection(hci_connection_t * connection){
2530bf6344aS[email protected]     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
2540bf6344aS[email protected]     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
2550bf6344aS[email protected] }
2560bf6344aS[email protected] 
2577fde4af9Smatthias.ringwald 
2587fde4af9Smatthias.ringwald /**
25943bfb1bdSmatthias.ringwald  * count connections
26043bfb1bdSmatthias.ringwald  */
26140d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
26256c253c9Smatthias.ringwald     int count = 0;
26343bfb1bdSmatthias.ringwald     linked_item_t *it;
2643a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
26543bfb1bdSmatthias.ringwald     return count;
26643bfb1bdSmatthias.ringwald }
267c8e4258aSmatthias.ringwald 
26897addcc5Smatthias.ringwald /**
269ba681a6cSmatthias.ringwald  * Dummy handler called by HCI
27016833f0aSmatthias.ringwald  */
2712718e2e7Smatthias.ringwald static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
27216833f0aSmatthias.ringwald }
27316833f0aSmatthias.ringwald 
274998906cdSmatthias.ringwald uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
2755061f3afS[email protected]     hci_connection_t * connection = hci_connection_for_handle(handle);
276998906cdSmatthias.ringwald     if (!connection) {
2779da54300S[email protected]         log_error("hci_number_outgoing_packets: connection for handle %u does not exist!", handle);
278998906cdSmatthias.ringwald         return 0;
279998906cdSmatthias.ringwald     }
280998906cdSmatthias.ringwald     return connection->num_acl_packets_sent;
281998906cdSmatthias.ringwald }
282998906cdSmatthias.ringwald 
283e79abdd6S[email protected] uint8_t hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
284ee303eddS[email protected] 
285ee303eddS[email protected]     int num_packets_sent_classic = 0;
286ee303eddS[email protected]     int num_packets_sent_le = 0;
287ee303eddS[email protected] 
288ee303eddS[email protected]     bd_addr_type_t address_type = BD_ADDR_TYPE_UNKNOWN;
289ee303eddS[email protected] 
290998906cdSmatthias.ringwald     linked_item_t *it;
2913a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
292998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
293ee303eddS[email protected]         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
294ee303eddS[email protected]             num_packets_sent_classic += connection->num_acl_packets_sent;
295ee303eddS[email protected]         } else {
296ee303eddS[email protected]             num_packets_sent_le += connection->num_acl_packets_sent;
297ee303eddS[email protected]         }
298ee303eddS[email protected]         if (connection->con_handle == con_handle){
299ee303eddS[email protected]             address_type = connection->address_type;
300ee303eddS[email protected]         }
301ee303eddS[email protected]     }
302ee303eddS[email protected] 
303ee303eddS[email protected]     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
304ee303eddS[email protected]     int free_slots_le = 0;
305ee303eddS[email protected] 
306ee303eddS[email protected]     if (free_slots_classic < 0){
3079da54300S[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);
308998906cdSmatthias.ringwald         return 0;
309998906cdSmatthias.ringwald     }
310ee303eddS[email protected] 
311ee303eddS[email protected]     if (hci_stack->le_acl_packets_total_num){
312ee303eddS[email protected]         // if we have LE slots, they are used
313ee303eddS[email protected]         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
314ee303eddS[email protected]         if (free_slots_le < 0){
3159da54300S[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);
316ee303eddS[email protected]             return 0;
317998906cdSmatthias.ringwald         }
318ee303eddS[email protected]     } else {
319ee303eddS[email protected]         // otherwise, classic slots are used for LE, too
320ee303eddS[email protected]         free_slots_classic -= num_packets_sent_le;
321ee303eddS[email protected]         if (free_slots_classic < 0){
3229da54300S[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);
323ee303eddS[email protected]             return 0;
324ee303eddS[email protected]         }
325ee303eddS[email protected]     }
326ee303eddS[email protected] 
327ee303eddS[email protected]     switch (address_type){
328ee303eddS[email protected]         case BD_ADDR_TYPE_UNKNOWN:
3299da54300S[email protected]             log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
330ee303eddS[email protected]             return 0;
331ee303eddS[email protected] 
332ee303eddS[email protected]         case BD_ADDR_TYPE_CLASSIC:
333ee303eddS[email protected]             return free_slots_classic;
334ee303eddS[email protected] 
335ee303eddS[email protected]         default:
336cb00d3aaS[email protected]            if (hci_stack->le_acl_packets_total_num){
337ee303eddS[email protected]                return free_slots_le;
338ee303eddS[email protected]            }
339cb00d3aaS[email protected]            return free_slots_classic;
340cb00d3aaS[email protected]     }
341998906cdSmatthias.ringwald }
342998906cdSmatthias.ringwald 
343ac928cc2S[email protected] 
344ac928cc2S[email protected] // @deprecated
345c24735b1Smatthias.ringwald int hci_can_send_packet_now(uint8_t packet_type){
346c24735b1Smatthias.ringwald     switch (packet_type) {
347c24735b1Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
348ac928cc2S[email protected]             return hci_can_send_prepared_acl_packet_now(0);
349c24735b1Smatthias.ringwald         case HCI_COMMAND_DATA_PACKET:
350ac928cc2S[email protected]             return hci_can_send_command_packet_now();
351c24735b1Smatthias.ringwald         default:
352c24735b1Smatthias.ringwald             return 0;
353c24735b1Smatthias.ringwald     }
354c24735b1Smatthias.ringwald }
355c24735b1Smatthias.ringwald 
356ac928cc2S[email protected] // @deprecated
3576b4af23dS[email protected] // same as hci_can_send_packet_now, but also checks if packet buffer is free for use
3586b4af23dS[email protected] int hci_can_send_packet_now_using_packet_buffer(uint8_t packet_type){
359ac928cc2S[email protected] 
3606b4af23dS[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
361ac928cc2S[email protected] 
362ac928cc2S[email protected]     switch (packet_type) {
363ac928cc2S[email protected]         case HCI_ACL_DATA_PACKET:
364ac928cc2S[email protected]             return hci_can_send_acl_packet_now(0);
365ac928cc2S[email protected]         case HCI_COMMAND_DATA_PACKET:
366ac928cc2S[email protected]             return hci_can_send_command_packet_now();
367ac928cc2S[email protected]         default:
368ac928cc2S[email protected]             return 0;
369ac928cc2S[email protected]     }
370ac928cc2S[email protected] }
371ac928cc2S[email protected] 
372ac928cc2S[email protected] 
373ac928cc2S[email protected] // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
374ac928cc2S[email protected] int hci_can_send_command_packet_now(void){
375ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
376ac928cc2S[email protected] 
377ac928cc2S[email protected]     // check for async hci transport implementations
378ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
379ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
380ac928cc2S[email protected]             return 0;
381ac928cc2S[email protected]         }
382ac928cc2S[email protected]     }
383ac928cc2S[email protected] 
384ac928cc2S[email protected]     return hci_stack->num_cmd_packets > 0;
385ac928cc2S[email protected] }
386ac928cc2S[email protected] 
387ac928cc2S[email protected] int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
388ac928cc2S[email protected]     // check for async hci transport implementations
389ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
390ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_ACL_DATA_PACKET)){
391ac928cc2S[email protected]             return 0;
392ac928cc2S[email protected]         }
393ac928cc2S[email protected]     }
394e79abdd6S[email protected]     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
395ac928cc2S[email protected] }
396ac928cc2S[email protected] 
397ac928cc2S[email protected] int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
398ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
399ac928cc2S[email protected]     return hci_can_send_prepared_acl_packet_now(con_handle);
4006b4af23dS[email protected] }
4016b4af23dS[email protected] 
402c8b9416aS[email protected] // used for internal checks in l2cap[-le].c
403c8b9416aS[email protected] int hci_is_packet_buffer_reserved(void){
404c8b9416aS[email protected]     return hci_stack->hci_packet_buffer_reserved;
405c8b9416aS[email protected] }
406c8b9416aS[email protected] 
4076b4af23dS[email protected] // reserves outgoing packet buffer. @returns 1 if successful
4086b4af23dS[email protected] int hci_reserve_packet_buffer(void){
4099d14b626S[email protected]     if (hci_stack->hci_packet_buffer_reserved) {
4109d14b626S[email protected]         log_error("hci_reserve_packet_buffer called but buffer already reserved");
4119d14b626S[email protected]         return 0;
4129d14b626S[email protected]     }
4136b4af23dS[email protected]     hci_stack->hci_packet_buffer_reserved = 1;
4146b4af23dS[email protected]     return 1;
4156b4af23dS[email protected] }
4166b4af23dS[email protected] 
41768a0fcf7S[email protected] void hci_release_packet_buffer(void){
41868a0fcf7S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
41968a0fcf7S[email protected] }
42068a0fcf7S[email protected] 
4216b4af23dS[email protected] // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
4226b4af23dS[email protected] int hci_transport_synchronous(void){
4236b4af23dS[email protected]     return hci_stack->hci_transport->can_send_packet_now == NULL;
4246b4af23dS[email protected] }
4256b4af23dS[email protected] 
4266c26b087S[email protected] uint16_t hci_max_acl_le_data_packet_length(void){
4276c26b087S[email protected]     return hci_stack->le_data_packets_length > 0 ? hci_stack->le_data_packets_length : hci_stack->acl_data_packet_length;
4286c26b087S[email protected] }
4296c26b087S[email protected] 
430452cf3bbS[email protected] static int hci_send_acl_packet_fragments(hci_connection_t *connection){
431452cf3bbS[email protected] 
432452cf3bbS[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);
433452cf3bbS[email protected] 
434452cf3bbS[email protected]     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
435452cf3bbS[email protected]     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
436452cf3bbS[email protected]     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
437452cf3bbS[email protected]         max_acl_data_packet_length = hci_stack->le_data_packets_length;
438452cf3bbS[email protected]     }
439452cf3bbS[email protected] 
440452cf3bbS[email protected]     // testing: reduce buffer to minimum
441452cf3bbS[email protected]     // max_acl_data_packet_length = 52;
442452cf3bbS[email protected] 
443452cf3bbS[email protected]     int err;
444452cf3bbS[email protected]     // multiple packets could be send on a synchronous HCI transport
445452cf3bbS[email protected]     while (1){
446452cf3bbS[email protected] 
447452cf3bbS[email protected]         // get current data
448452cf3bbS[email protected]         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
449452cf3bbS[email protected]         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
450452cf3bbS[email protected]         int more_fragments = 0;
451452cf3bbS[email protected] 
452452cf3bbS[email protected]         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
453452cf3bbS[email protected]         if (current_acl_data_packet_length > max_acl_data_packet_length){
454452cf3bbS[email protected]             more_fragments = 1;
455452cf3bbS[email protected]             current_acl_data_packet_length = max_acl_data_packet_length;
456452cf3bbS[email protected]         }
457452cf3bbS[email protected] 
458452cf3bbS[email protected]         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
459452cf3bbS[email protected]         if (acl_header_pos > 0){
460452cf3bbS[email protected]             uint16_t handle_and_flags = READ_BT_16(hci_stack->hci_packet_buffer, 0);
461452cf3bbS[email protected]             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
462452cf3bbS[email protected]             bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
463452cf3bbS[email protected]         }
464452cf3bbS[email protected] 
465452cf3bbS[email protected]         // update header len
466452cf3bbS[email protected]         bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
467452cf3bbS[email protected] 
468452cf3bbS[email protected]         // count packet
469452cf3bbS[email protected]         connection->num_acl_packets_sent++;
470452cf3bbS[email protected] 
471452cf3bbS[email protected]         // send packet
472452cf3bbS[email protected]         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
473452cf3bbS[email protected]         const int size = current_acl_data_packet_length + 4;
474452cf3bbS[email protected]         // hexdump(packet, size);
475452cf3bbS[email protected]         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
476452cf3bbS[email protected] 
477452cf3bbS[email protected]         // done yet?
478452cf3bbS[email protected]         if (!more_fragments) break;
479452cf3bbS[email protected] 
480452cf3bbS[email protected]         // update start of next fragment to send
481452cf3bbS[email protected]         hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
482452cf3bbS[email protected] 
483452cf3bbS[email protected]         // can send more?
484452cf3bbS[email protected]         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
485452cf3bbS[email protected]     }
486452cf3bbS[email protected] 
487452cf3bbS[email protected]     // done
488452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 0;
489452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = 0;
490452cf3bbS[email protected] 
491452cf3bbS[email protected]     // free buffer now for synchronous transport
492452cf3bbS[email protected]     if (!hci_transport_synchronous()){
493452cf3bbS[email protected]         hci_release_packet_buffer();
494452cf3bbS[email protected]     }
495452cf3bbS[email protected] 
496452cf3bbS[email protected]     return err;
497452cf3bbS[email protected] }
498452cf3bbS[email protected] 
499826f7347S[email protected] // pre: caller has reserved the packet buffer
500826f7347S[email protected] int hci_send_acl_packet_buffer(int size){
5017856c818Smatthias.ringwald 
502452cf3bbS[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
503452cf3bbS[email protected] 
504826f7347S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
505826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
506826f7347S[email protected]         return 0;
507826f7347S[email protected]     }
508826f7347S[email protected] 
509d713a683S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
510d713a683S[email protected]     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
511d713a683S[email protected] 
512826f7347S[email protected]     // check for free places on Bluetooth module
513d713a683S[email protected]     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
514826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
51597b61c7bS[email protected]         hci_release_packet_buffer();
51697b61c7bS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
51797b61c7bS[email protected]     }
5186218e6f1Smatthias.ringwald 
5195061f3afS[email protected]     hci_connection_t *connection = hci_connection_for_handle( con_handle);
52097b61c7bS[email protected]     if (!connection) {
5215fa0b7cfS[email protected]         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
52297b61c7bS[email protected]         hci_release_packet_buffer();
52397b61c7bS[email protected]         return 0;
52497b61c7bS[email protected]     }
52556cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
52656cf178bSmatthias.ringwald 
527452cf3bbS[email protected]     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
5287856c818Smatthias.ringwald 
529452cf3bbS[email protected]     // setup data
530452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = size;
531452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
5326218e6f1Smatthias.ringwald 
533452cf3bbS[email protected]     return hci_send_acl_packet_fragments(connection);
534ee091cf1Smatthias.ringwald }
535ee091cf1Smatthias.ringwald 
53616833f0aSmatthias.ringwald static void acl_handler(uint8_t *packet, int size){
5377856c818Smatthias.ringwald 
538e76a89eeS[email protected]     // log_info("acl_handler: size %u", size);
539e76a89eeS[email protected] 
5407856c818Smatthias.ringwald     // get info
5417856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
5425061f3afS[email protected]     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
5437856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
5447856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
5457856c818Smatthias.ringwald 
5467856c818Smatthias.ringwald     // ignore non-registered handle
5477856c818Smatthias.ringwald     if (!conn){
5489da54300S[email protected]         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
5497856c818Smatthias.ringwald         return;
5507856c818Smatthias.ringwald     }
5517856c818Smatthias.ringwald 
552e76a89eeS[email protected]     // assert packet is complete
5539ecc3e17S[email protected]     if (acl_length + 4 != size){
554e76a89eeS[email protected]         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
555e76a89eeS[email protected]         return;
556e76a89eeS[email protected]     }
557e76a89eeS[email protected] 
5587856c818Smatthias.ringwald     // update idle timestamp
5597856c818Smatthias.ringwald     hci_connection_timestamp(conn);
5607856c818Smatthias.ringwald 
5617856c818Smatthias.ringwald     // handle different packet types
5627856c818Smatthias.ringwald     switch (acl_flags & 0x03) {
5637856c818Smatthias.ringwald 
5647856c818Smatthias.ringwald         case 0x01: // continuation fragment
5657856c818Smatthias.ringwald 
5667856c818Smatthias.ringwald             // sanity check
5677856c818Smatthias.ringwald             if (conn->acl_recombination_pos == 0) {
5689da54300S[email protected]                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
5697856c818Smatthias.ringwald                 return;
5707856c818Smatthias.ringwald             }
5717856c818Smatthias.ringwald 
5727856c818Smatthias.ringwald             // append fragment payload (header already stored)
5737856c818Smatthias.ringwald             memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length );
5747856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
5757856c818Smatthias.ringwald 
5769da54300S[email protected]             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
577decc01a8Smatthias.ringwald             //        conn->acl_recombination_pos, conn->acl_recombination_length);
5787856c818Smatthias.ringwald 
5797856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
5807856c818Smatthias.ringwald             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
5817856c818Smatthias.ringwald 
5823a9fb326S[email protected]                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos);
5837856c818Smatthias.ringwald                 // reset recombination buffer
5847856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
5857856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
5867856c818Smatthias.ringwald             }
5877856c818Smatthias.ringwald             break;
5887856c818Smatthias.ringwald 
5897856c818Smatthias.ringwald         case 0x02: { // first fragment
5907856c818Smatthias.ringwald 
5917856c818Smatthias.ringwald             // sanity check
5927856c818Smatthias.ringwald             if (conn->acl_recombination_pos) {
5939da54300S[email protected]                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x", con_handle);
5947856c818Smatthias.ringwald                 return;
5957856c818Smatthias.ringwald             }
5967856c818Smatthias.ringwald 
5977856c818Smatthias.ringwald             // peek into L2CAP packet!
5987856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
5997856c818Smatthias.ringwald 
6009da54300S[email protected]             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
601decc01a8Smatthias.ringwald 
6027856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
6037856c818Smatthias.ringwald             if (acl_length >= l2cap_length + 4){
6047856c818Smatthias.ringwald 
6057856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
6063a9fb326S[email protected]                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
6077856c818Smatthias.ringwald 
6087856c818Smatthias.ringwald             } else {
6097856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
6107856c818Smatthias.ringwald                 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4);
6117856c818Smatthias.ringwald                 conn->acl_recombination_pos    = acl_length + 4;
6127856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
613decc01a8Smatthias.ringwald                 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4);
6147856c818Smatthias.ringwald             }
6157856c818Smatthias.ringwald             break;
6167856c818Smatthias.ringwald 
6177856c818Smatthias.ringwald         }
6187856c818Smatthias.ringwald         default:
6199da54300S[email protected]             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
6207856c818Smatthias.ringwald             return;
6217856c818Smatthias.ringwald     }
62294ab26f8Smatthias.ringwald 
62394ab26f8Smatthias.ringwald     // execute main loop
62494ab26f8Smatthias.ringwald     hci_run();
62516833f0aSmatthias.ringwald }
62622909952Smatthias.ringwald 
62767a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
6289da54300S[email protected]     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
6293c4d4b90Smatthias.ringwald 
630c7e0c5f6Smatthias.ringwald     run_loop_remove_timer(&conn->timeout);
631c785ef68Smatthias.ringwald 
6323a9fb326S[email protected]     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
633a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
6343c4d4b90Smatthias.ringwald 
6353c4d4b90Smatthias.ringwald     // now it's gone
636c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
637c7e0c5f6Smatthias.ringwald }
638c7e0c5f6Smatthias.ringwald 
6390c042179S[email protected] static const uint16_t packet_type_sizes[] = {
6408f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
6418f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
6428f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
6438f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
6448f8108aaSmatthias.ringwald };
64565389bfcS[email protected] static const uint8_t  packet_type_feature_requirement_bit[] = {
64665389bfcS[email protected]      0, // 3 slot packets
64765389bfcS[email protected]      1, // 5 slot packets
64865389bfcS[email protected]     25, // EDR 2 mpbs
64965389bfcS[email protected]     26, // EDR 3 mbps
65065389bfcS[email protected]     39, // 3 slot EDR packts
65165389bfcS[email protected]     40, // 5 slot EDR packet
65265389bfcS[email protected] };
65365389bfcS[email protected] static const uint16_t packet_type_feature_packet_mask[] = {
65465389bfcS[email protected]     0x0f00, // 3 slot packets
65565389bfcS[email protected]     0xf000, // 5 slot packets
65665389bfcS[email protected]     0x1102, // EDR 2 mpbs
65765389bfcS[email protected]     0x2204, // EDR 3 mbps
65865389bfcS[email protected]     0x0300, // 3 slot EDR packts
65965389bfcS[email protected]     0x3000, // 5 slot EDR packet
66065389bfcS[email protected] };
6618f8108aaSmatthias.ringwald 
66265389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
66365389bfcS[email protected]     // enable packet types based on size
6648f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
6658f8108aaSmatthias.ringwald     int i;
6668f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
6678f8108aaSmatthias.ringwald         if (packet_type_sizes[i] == 0) continue;
6688f8108aaSmatthias.ringwald         if (packet_type_sizes[i] <= buffer_size){
6698f8108aaSmatthias.ringwald             packet_types |= 1 << i;
6708f8108aaSmatthias.ringwald         }
6718f8108aaSmatthias.ringwald     }
67265389bfcS[email protected]     // disable packet types due to missing local supported features
67365389bfcS[email protected]     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
67465389bfcS[email protected]         int bit_idx = packet_type_feature_requirement_bit[i];
67565389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
67665389bfcS[email protected]         if (feature_set) continue;
67765389bfcS[email protected]         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
67865389bfcS[email protected]         packet_types &= ~packet_type_feature_packet_mask[i];
67965389bfcS[email protected]     }
6808f8108aaSmatthias.ringwald     // flip bits for "may not be used"
6818f8108aaSmatthias.ringwald     packet_types ^= 0x3306;
6828f8108aaSmatthias.ringwald     return packet_types;
6838f8108aaSmatthias.ringwald }
6848f8108aaSmatthias.ringwald 
6858f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
6863a9fb326S[email protected]     return hci_stack->packet_types;
6878f8108aaSmatthias.ringwald }
6888f8108aaSmatthias.ringwald 
689facf93fdS[email protected] uint8_t* hci_get_outgoing_packet_buffer(void){
6907dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
6913a9fb326S[email protected]     return hci_stack->hci_packet_buffer;
6927dc17943Smatthias.ringwald }
6937dc17943Smatthias.ringwald 
694f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
6953a9fb326S[email protected]     return hci_stack->acl_data_packet_length;
6967dc17943Smatthias.ringwald }
6977dc17943Smatthias.ringwald 
6986ac9a97eS[email protected] int hci_non_flushable_packet_boundary_flag_supported(void){
6996ac9a97eS[email protected]     // No. 54, byte 6, bit 6
7006ac9a97eS[email protected]     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
7016ac9a97eS[email protected] }
7026ac9a97eS[email protected] 
703f5d8d141S[email protected] int hci_ssp_supported(void){
7046ac9a97eS[email protected]     // No. 51, byte 6, bit 3
7053a9fb326S[email protected]     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
706f5d8d141S[email protected] }
707f5d8d141S[email protected] 
708f5d8d141S[email protected] int hci_classic_supported(void){
7096ac9a97eS[email protected]     // No. 37, byte 4, bit 5, = No BR/EDR Support
7103a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
711f5d8d141S[email protected] }
712f5d8d141S[email protected] 
713f5d8d141S[email protected] int hci_le_supported(void){
714f5d8d141S[email protected] #ifdef HAVE_BLE
7156ac9a97eS[email protected]     // No. 37, byte 4, bit 6 = LE Supported (Controller)
7163a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
717f5d8d141S[email protected] #else
718f5d8d141S[email protected]     return 0;
719f5d8d141S[email protected] #endif
720f5d8d141S[email protected] }
721f5d8d141S[email protected] 
72269a97523S[email protected] // get addr type and address used in advertisement packets
72318904abdS[email protected] void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){
7243a9fb326S[email protected]     *addr_type = hci_stack->adv_addr_type;
7253a9fb326S[email protected]     if (hci_stack->adv_addr_type){
7263a9fb326S[email protected]         memcpy(addr, hci_stack->adv_address, 6);
72769a97523S[email protected]     } else {
7283a9fb326S[email protected]         memcpy(addr, hci_stack->local_bd_addr, 6);
72969a97523S[email protected]     }
73069a97523S[email protected] }
73169a97523S[email protected] 
732b2f949feS[email protected] #ifdef HAVE_BLE
733e01fe8b6S[email protected] void le_handle_advertisement_report(uint8_t *packet, int size){
734d1dc057bS[email protected]     int offset = 3;
735d1dc057bS[email protected]     int num_reports = packet[offset];
736d1dc057bS[email protected]     offset += 1;
737d1dc057bS[email protected] 
73857c9da5bS[email protected]     int i;
7394f4b43f3S[email protected]     log_info("HCI: handle adv report with num reports: %d", num_reports);
74057c9da5bS[email protected]     for (i=0; i<num_reports;i++){
741210c6774S[email protected]         uint8_t data_length = packet[offset + 8];
7422b552b23S[email protected]         uint8_t event_size = 10 + data_length;
7432b552b23S[email protected]         uint8_t event[2 + event_size ];
744d1dc057bS[email protected]         int pos = 0;
7452b552b23S[email protected]         event[pos++] = GAP_LE_ADVERTISING_REPORT;
74657c9da5bS[email protected]         event[pos++] = event_size;
747210c6774S[email protected]         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
748d1dc057bS[email protected]         offset += 8;
749d1dc057bS[email protected]         pos += 8;
750d1dc057bS[email protected]         event[pos++] = packet[offset + 1 + data_length]; // rssi
751d1dc057bS[email protected]         event[pos++] = packet[offset++]; //data_length;
752d1dc057bS[email protected]         memcpy(&event[pos], &packet[offset], data_length);
75357c9da5bS[email protected]         pos += data_length;
754d1dc057bS[email protected]         offset += data_length + 1; // rssi
7554f4b43f3S[email protected]         hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
75657c9da5bS[email protected]         hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
75757c9da5bS[email protected]     }
75857c9da5bS[email protected] }
759b2f949feS[email protected] #endif
76057c9da5bS[email protected] 
7616155b3d3S[email protected] static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
762a2481739S[email protected]     uint8_t command_completed = 0;
763a2481739S[email protected]     if ((hci_stack->substate % 2) == 0) return;
7646155b3d3S[email protected]     // odd: waiting for event
7656155b3d3S[email protected]     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
7666155b3d3S[email protected]         uint16_t opcode = READ_BT_16(packet,3);
7676155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
768a2481739S[email protected]             command_completed = 1;
7696155b3d3S[email protected]             log_info("Command complete for expected opcode %04x -> new substate %u", opcode, hci_stack->substate);
7706155b3d3S[email protected]         } else {
7716155b3d3S[email protected]             log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
7726155b3d3S[email protected]         }
7736155b3d3S[email protected]     }
7746155b3d3S[email protected]     if (packet[0] == HCI_EVENT_COMMAND_STATUS){
7756155b3d3S[email protected]         uint8_t  status = packet[2];
7766155b3d3S[email protected]         uint16_t opcode = READ_BT_16(packet,4);
7776155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
7786155b3d3S[email protected]             if (status){
779a2481739S[email protected]                 command_completed = 1;
7806155b3d3S[email protected]                 log_error("Command status error 0x%02x for expected opcode %04x -> new substate %u", status, opcode, hci_stack->substate);
7816155b3d3S[email protected]             } else {
7826155b3d3S[email protected]                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
7836155b3d3S[email protected]             }
7846155b3d3S[email protected]         } else {
7856155b3d3S[email protected]             log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
7866155b3d3S[email protected]         }
7876155b3d3S[email protected]     }
788a2481739S[email protected] 
789a2481739S[email protected]     if (!command_completed) return;
790a2481739S[email protected] 
791a2481739S[email protected]     switch(hci_stack->substate >> 1){
792a2481739S[email protected]         default:
793a2481739S[email protected]             hci_stack->substate++;
794a2481739S[email protected]             break;
7956155b3d3S[email protected]     }
7966155b3d3S[email protected] }
7976155b3d3S[email protected] 
7986155b3d3S[email protected] static void hci_initializing_state_machine(){
7999da54300S[email protected]         // log_info("hci_init: substate %u", hci_stack->substate);
8006155b3d3S[email protected]     if (hci_stack->substate % 2) {
8016155b3d3S[email protected]         // odd: waiting for command completion
8026155b3d3S[email protected]         return;
8036155b3d3S[email protected]     }
8046155b3d3S[email protected]     switch (hci_stack->substate >> 1){
8056155b3d3S[email protected]         case 0: // RESET
8066155b3d3S[email protected]             hci_state_reset();
8076155b3d3S[email protected] 
8086155b3d3S[email protected]             hci_send_cmd(&hci_reset);
8096155b3d3S[email protected]             if (hci_stack->config == NULL || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
8106155b3d3S[email protected]                 // skip baud change
8116155b3d3S[email protected]                 hci_stack->substate = 4; // >> 1 = 2
8126155b3d3S[email protected]             }
8136155b3d3S[email protected]             break;
8146155b3d3S[email protected]         case 1: // SEND BAUD CHANGE
8156155b3d3S[email protected]             hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
81688789c61Smatthias.ringwald             hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
8176155b3d3S[email protected]             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
8186155b3d3S[email protected]             break;
8196155b3d3S[email protected]         case 2: // LOCAL BAUD CHANGE
8206155b3d3S[email protected]             log_info("Local baud rate change");
8216155b3d3S[email protected]             hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
8226155b3d3S[email protected]             hci_stack->substate += 2;
8236155b3d3S[email protected]             // break missing here for fall through
8246155b3d3S[email protected] 
8256155b3d3S[email protected]         case 3:
8266155b3d3S[email protected]             log_info("Custom init");
8276155b3d3S[email protected]             // Custom initialization
8286155b3d3S[email protected]             if (hci_stack->control && hci_stack->control->next_cmd){
8296155b3d3S[email protected]                 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
8306155b3d3S[email protected]                 if (valid_cmd){
8316155b3d3S[email protected]                     int size = 3 + hci_stack->hci_packet_buffer[2];
8326155b3d3S[email protected]                     hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
8336155b3d3S[email protected]                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
8346155b3d3S[email protected]                     hci_stack->substate = 4; // more init commands
8356155b3d3S[email protected]                     break;
8366155b3d3S[email protected]                 }
8379da54300S[email protected]                 log_info("hci_run: init script done");
8386155b3d3S[email protected]             }
8396155b3d3S[email protected]             // otherwise continue
8406155b3d3S[email protected]             hci_send_cmd(&hci_read_bd_addr);
8416155b3d3S[email protected]             break;
8426155b3d3S[email protected]         case 4:
8436155b3d3S[email protected]             hci_send_cmd(&hci_read_buffer_size);
8446155b3d3S[email protected]             break;
8456155b3d3S[email protected]         case 5:
8466155b3d3S[email protected]             hci_send_cmd(&hci_read_local_supported_features);
8476155b3d3S[email protected]             break;
8486155b3d3S[email protected]         case 6:
8496155b3d3S[email protected]             if (hci_le_supported()){
8506155b3d3S[email protected]                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
8516155b3d3S[email protected]             } else {
8526155b3d3S[email protected]                 // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
8536155b3d3S[email protected]                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
8546155b3d3S[email protected]             }
8556155b3d3S[email protected] 
8566155b3d3S[email protected]             // skip Classic init commands for LE only chipsets
8576155b3d3S[email protected]             if (!hci_classic_supported()){
8586155b3d3S[email protected]                 if (hci_le_supported()){
8596155b3d3S[email protected]                     hci_stack->substate = 11 << 1;    // skip all classic command
8606155b3d3S[email protected]                 } else {
8616155b3d3S[email protected]                     log_error("Neither BR/EDR nor LE supported");
8626155b3d3S[email protected]                     hci_stack->substate = 14 << 1;    // skip all
8636155b3d3S[email protected]                 }
8646155b3d3S[email protected]             }
8656155b3d3S[email protected]             break;
8666155b3d3S[email protected]         case 7:
8676155b3d3S[email protected]             if (hci_ssp_supported()){
8686155b3d3S[email protected]                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
8696155b3d3S[email protected]                 break;
8706155b3d3S[email protected]             }
8716155b3d3S[email protected]             hci_stack->substate += 2;
8726155b3d3S[email protected]             // break missing here for fall through
8736155b3d3S[email protected] 
8746155b3d3S[email protected]         case 8:
8756155b3d3S[email protected]             // ca. 15 sec
8766155b3d3S[email protected]             hci_send_cmd(&hci_write_page_timeout, 0x6000);
8776155b3d3S[email protected]             break;
8786155b3d3S[email protected]         case 9:
8796155b3d3S[email protected]             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
8806155b3d3S[email protected]             break;
8816155b3d3S[email protected]         case 10:
8826155b3d3S[email protected]             if (hci_stack->local_name){
8836155b3d3S[email protected]                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
8846155b3d3S[email protected]             } else {
8856155b3d3S[email protected]                 char hostname[30];
8866155b3d3S[email protected] #ifdef EMBEDDED
8876155b3d3S[email protected]                 // BTstack-11:22:33:44:55:66
8886155b3d3S[email protected]                 strcpy(hostname, "BTstack ");
8896155b3d3S[email protected]                 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr));
8906155b3d3S[email protected]                 log_info("---> Name %s", hostname);
8916155b3d3S[email protected] #else
8926155b3d3S[email protected]                 // hostname for POSIX systems
8936155b3d3S[email protected]                 gethostname(hostname, 30);
8946155b3d3S[email protected]                 hostname[29] = '\0';
8956155b3d3S[email protected] #endif
8966155b3d3S[email protected]                 hci_send_cmd(&hci_write_local_name, hostname);
8976155b3d3S[email protected]             }
8986155b3d3S[email protected]             break;
8996155b3d3S[email protected]         case 11:
9006155b3d3S[email protected]             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
9016155b3d3S[email protected]             if (!hci_le_supported()){
9026155b3d3S[email protected]                 // SKIP LE init for Classic only configuration
9036155b3d3S[email protected]                 hci_stack->substate = 14 << 1;
9046155b3d3S[email protected]             }
9056155b3d3S[email protected]             break;
9066155b3d3S[email protected] 
9076155b3d3S[email protected] #ifdef HAVE_BLE
9086155b3d3S[email protected]         // LE INIT
9096155b3d3S[email protected]         case 12:
9106155b3d3S[email protected]             hci_send_cmd(&hci_le_read_buffer_size);
9116155b3d3S[email protected]             break;
9126155b3d3S[email protected]         case 13:
9136155b3d3S[email protected]             // LE Supported Host = 1, Simultaneous Host = 0
9146155b3d3S[email protected]             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
9156155b3d3S[email protected]             break;
9166155b3d3S[email protected]         case 14:
9176155b3d3S[email protected]             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs
9186155b3d3S[email protected]             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0);
9196155b3d3S[email protected]             break;
9206155b3d3S[email protected] #endif
9216155b3d3S[email protected] 
9226155b3d3S[email protected]         // DONE
9236155b3d3S[email protected]         case 15:
9246155b3d3S[email protected]             // done.
9256155b3d3S[email protected]             hci_stack->state = HCI_STATE_WORKING;
9266155b3d3S[email protected]             hci_emit_state();
9276155b3d3S[email protected]             break;
9286155b3d3S[email protected]         default:
9296155b3d3S[email protected]             break;
9306155b3d3S[email protected]     }
9316155b3d3S[email protected]     hci_stack->substate++;
9326155b3d3S[email protected] }
9336155b3d3S[email protected] 
93474ec757aSmatthias.ringwald // avoid huge local variables
935223aafc1Smatthias.ringwald #ifndef EMBEDDED
93674ec757aSmatthias.ringwald static device_name_t device_name;
937223aafc1Smatthias.ringwald #endif
93816833f0aSmatthias.ringwald static void event_handler(uint8_t *packet, int size){
939e76a89eeS[email protected] 
940e76a89eeS[email protected]     uint16_t event_length = packet[1];
941e76a89eeS[email protected] 
942e76a89eeS[email protected]     // assert packet is complete
943e76a89eeS[email protected]     if (size != event_length + 2){
944e76a89eeS[email protected]         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
945e76a89eeS[email protected]         return;
946e76a89eeS[email protected]     }
947e76a89eeS[email protected] 
9481281a47eSmatthias.ringwald     bd_addr_t addr;
94996a45072S[email protected]     bd_addr_type_t addr_type;
9502d00edd4Smatthias.ringwald     uint8_t link_type;
951fe1ed1b8Smatthias.ringwald     hci_con_handle_t handle;
9521f7b95a1Smatthias.ringwald     hci_connection_t * conn;
95356cf178bSmatthias.ringwald     int i;
95422909952Smatthias.ringwald 
9559da54300S[email protected]     // log_info("HCI:EVENT:%02x", packet[0]);
9565909f7f2Smatthias.ringwald 
9576772a24cSmatthias.ringwald     switch (packet[0]) {
95822909952Smatthias.ringwald 
9596772a24cSmatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
9607ec5eeaaSmatthias.ringwald             // get num cmd packets
9619da54300S[email protected]             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]);
9623a9fb326S[email protected]             hci_stack->num_cmd_packets = packet[2];
9637ec5eeaaSmatthias.ringwald 
964e2edc0c3Smatthias.ringwald             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
965e2edc0c3Smatthias.ringwald                 // from offset 5
966e2edc0c3Smatthias.ringwald                 // status
9671d279b20Smatthias.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"
9683a9fb326S[email protected]                 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6);
96956cf178bSmatthias.ringwald                 // ignore: SCO data packet len (8)
970ee303eddS[email protected]                 hci_stack->acl_packets_total_num  = packet[9];
97156cf178bSmatthias.ringwald                 // ignore: total num SCO packets
9723a9fb326S[email protected]                 if (hci_stack->state == HCI_STATE_INITIALIZING){
973a7a04bd9Smatthias.ringwald                     // determine usable ACL payload size
9743a9fb326S[email protected]                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
9753a9fb326S[email protected]                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
9768f8108aaSmatthias.ringwald                     }
9779da54300S[email protected]                     log_info("hci_read_buffer_size: used size %u, count %u",
978ee303eddS[email protected]                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num);
979e2edc0c3Smatthias.ringwald                 }
98056cf178bSmatthias.ringwald             }
98165a46ef3S[email protected] #ifdef HAVE_BLE
98265a46ef3S[email protected]             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){
983219eea5fS[email protected]                 hci_stack->le_data_packets_length = READ_BT_16(packet, 6);
984ee303eddS[email protected]                 hci_stack->le_acl_packets_total_num  = packet[8];
9856c26b087S[email protected]                     // determine usable ACL payload size
9866c26b087S[email protected]                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
9876c26b087S[email protected]                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
9886c26b087S[email protected]                     }
9899da54300S[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);
99065a46ef3S[email protected]             }
99165a46ef3S[email protected] #endif
992188981d2Smatthias.ringwald             // Dump local address
993188981d2Smatthias.ringwald             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
9943a9fb326S[email protected]                 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
9959da54300S[email protected]                 log_info("Local Address, Status: 0x%02x: Addr: %s",
9963a9fb326S[email protected]                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
997188981d2Smatthias.ringwald             }
998381fbed8Smatthias.ringwald             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
9993a9fb326S[email protected]                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1000381fbed8Smatthias.ringwald             }
100165389bfcS[email protected]             // Note: HCI init checks
1002559e517eS[email protected]             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
10033a9fb326S[email protected]                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1004559e517eS[email protected]                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
10053a9fb326S[email protected]                     hci_stack->local_supported_features[0], hci_stack->local_supported_features[1],
10063a9fb326S[email protected]                     hci_stack->local_supported_features[2], hci_stack->local_supported_features[3],
10073a9fb326S[email protected]                     hci_stack->local_supported_features[4], hci_stack->local_supported_features[5],
10083a9fb326S[email protected]                     hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]);
100965389bfcS[email protected] 
101065389bfcS[email protected]                 // determine usable ACL packet types based buffer size and supported features
10113a9fb326S[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]);
10123a9fb326S[email protected]                 log_info("packet types %04x", hci_stack->packet_types);
1013f5d8d141S[email protected] 
1014f5d8d141S[email protected]                 // Classic/LE
1015f5d8d141S[email protected]                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1016559e517eS[email protected]             }
101756cf178bSmatthias.ringwald             break;
101856cf178bSmatthias.ringwald 
10197ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
10207ec5eeaaSmatthias.ringwald             // get num cmd packets
10219da54300S[email protected]             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]);
10223a9fb326S[email protected]             hci_stack->num_cmd_packets = packet[3];
10237ec5eeaaSmatthias.ringwald             break;
10247ec5eeaaSmatthias.ringwald 
10252e440c8aS[email protected]         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
10262e440c8aS[email protected]             int offset = 3;
102756cf178bSmatthias.ringwald             for (i=0; i<packet[2];i++){
10282e440c8aS[email protected]                 handle = READ_BT_16(packet, offset);
10292e440c8aS[email protected]                 offset += 2;
10302e440c8aS[email protected]                 uint16_t num_packets = READ_BT_16(packet, offset);
10312e440c8aS[email protected]                 offset += 2;
10322e440c8aS[email protected] 
10335061f3afS[email protected]                 conn = hci_connection_for_handle(handle);
103456cf178bSmatthias.ringwald                 if (!conn){
10359da54300S[email protected]                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
103656cf178bSmatthias.ringwald                     continue;
103756cf178bSmatthias.ringwald                 }
103823bed257S[email protected] 
103923bed257S[email protected]                 if (conn->num_acl_packets_sent >= num_packets){
104056cf178bSmatthias.ringwald                     conn->num_acl_packets_sent -= num_packets;
104123bed257S[email protected]                 } else {
104223bed257S[email protected]                     log_error("hci_number_completed_packets, more slots freed then sent.");
104323bed257S[email protected]                     conn->num_acl_packets_sent = 0;
104423bed257S[email protected]                 }
10459da54300S[email protected]                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
104656cf178bSmatthias.ringwald             }
10476772a24cSmatthias.ringwald             break;
10482e440c8aS[email protected]         }
10491f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
105037eaa4cfSmatthias.ringwald             bt_flip_addr(addr, &packet[2]);
105137eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
10522d00edd4Smatthias.ringwald             link_type = packet[11];
10539da54300S[email protected]             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
105437eaa4cfSmatthias.ringwald             if (link_type == 1) { // ACL
105596a45072S[email protected]                 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
10561f7b95a1Smatthias.ringwald                 if (!conn) {
105796a45072S[email protected]                     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
10581f7b95a1Smatthias.ringwald                 }
1059ce4c8fabSmatthias.ringwald                 if (!conn) {
1060ce4c8fabSmatthias.ringwald                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
10613a9fb326S[email protected]                     hci_stack->decline_reason = 0x0d;
10623a9fb326S[email protected]                     BD_ADDR_COPY(hci_stack->decline_addr, addr);
1063ce4c8fabSmatthias.ringwald                     break;
1064ce4c8fabSmatthias.ringwald                 }
106532ab9390Smatthias.ringwald                 conn->state = RECEIVED_CONNECTION_REQUEST;
106632ab9390Smatthias.ringwald                 hci_run();
106737eaa4cfSmatthias.ringwald             } else {
1068ce4c8fabSmatthias.ringwald                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
10693a9fb326S[email protected]                 hci_stack->decline_reason = 0x0a;
10703a9fb326S[email protected]                 BD_ADDR_COPY(hci_stack->decline_addr, addr);
107137eaa4cfSmatthias.ringwald             }
10721f7b95a1Smatthias.ringwald             break;
10731f7b95a1Smatthias.ringwald 
10746772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1075fe1ed1b8Smatthias.ringwald             // Connection management
1076fe1ed1b8Smatthias.ringwald             bt_flip_addr(addr, &packet[5]);
10779da54300S[email protected]             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
107896a45072S[email protected]             addr_type = BD_ADDR_TYPE_CLASSIC;
107996a45072S[email protected]             conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1080fe1ed1b8Smatthias.ringwald             if (conn) {
1081b448a0e7Smatthias.ringwald                 if (!packet[2]){
1082c8e4258aSmatthias.ringwald                     conn->state = OPEN;
1083fe1ed1b8Smatthias.ringwald                     conn->con_handle = READ_BT_16(packet, 3);
1084ad83dc6aS[email protected]                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1085ee091cf1Smatthias.ringwald 
1086c785ef68Smatthias.ringwald                     // restart timer
1087c21e6239Smatthias.ringwald                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1088ee091cf1Smatthias.ringwald                     run_loop_add_timer(&conn->timeout);
1089c785ef68Smatthias.ringwald 
10909da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
109143bfb1bdSmatthias.ringwald 
109243bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
1093b448a0e7Smatthias.ringwald                 } else {
10941bd5283dS[email protected]                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
10951bd5283dS[email protected]                     uint8_t status = packet[2];
10961bd5283dS[email protected]                     bd_addr_t bd_address;
10971bd5283dS[email protected]                     memcpy(&bd_address, conn->address, 6);
1098ad83dc6aS[email protected] 
1099b448a0e7Smatthias.ringwald                     // connection failed, remove entry
11003a9fb326S[email protected]                     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1101a3b02b71Smatthias.ringwald                     btstack_memory_hci_connection_free( conn );
1102c12e46e7Smatthias.ringwald 
11031bd5283dS[email protected]                     // notify client if dedicated bonding
11041bd5283dS[email protected]                     if (notify_dedicated_bonding_failed){
11051bd5283dS[email protected]                         log_info("hci notify_dedicated_bonding_failed");
11061bd5283dS[email protected]                         hci_emit_dedicated_bonding_result(bd_address, status);
11071bd5283dS[email protected]                     }
11081bd5283dS[email protected] 
1109c12e46e7Smatthias.ringwald                     // if authentication error, also delete link key
1110c12e46e7Smatthias.ringwald                     if (packet[2] == 0x05) {
1111c12e46e7Smatthias.ringwald                         hci_drop_link_key_for_bd_addr(&addr);
1112c12e46e7Smatthias.ringwald                     }
1113fe1ed1b8Smatthias.ringwald                 }
1114fe1ed1b8Smatthias.ringwald             }
11156772a24cSmatthias.ringwald             break;
1116fe1ed1b8Smatthias.ringwald 
1117afd4e962S[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1118afd4e962S[email protected]             handle = READ_BT_16(packet, 3);
1119afd4e962S[email protected]             conn = hci_connection_for_handle(handle);
1120afd4e962S[email protected]             if (!conn) break;
1121afd4e962S[email protected]             if (!packet[2]){
1122afd4e962S[email protected]                 uint8_t * features = &packet[5];
1123afd4e962S[email protected]                 if (features[6] & (1 << 3)){
1124afd4e962S[email protected]                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1125afd4e962S[email protected]                 }
1126afd4e962S[email protected]             }
1127afd4e962S[email protected]             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1128ad83dc6aS[email protected]             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags);
1129ad83dc6aS[email protected]             if (conn->bonding_flags & BONDING_DEDICATED){
1130ad83dc6aS[email protected]                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1131ad83dc6aS[email protected]             }
1132afd4e962S[email protected]             break;
1133afd4e962S[email protected] 
11347fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
11359da54300S[email protected]             log_info("HCI_EVENT_LINK_KEY_REQUEST");
11367fde4af9Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
113774d716b5S[email protected]             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
11383a9fb326S[email protected]             if (hci_stack->bondable && !hci_stack->remote_device_db) break;
113932ab9390Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
114064472d52Smatthias.ringwald             hci_run();
1141d9a327f9Smatthias.ringwald             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
114229d53098Smatthias.ringwald             return;
11437fde4af9Smatthias.ringwald 
11449ab95c90S[email protected]         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
114529d53098Smatthias.ringwald             bt_flip_addr(addr, &packet[2]);
114696a45072S[email protected]             conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
11479ab95c90S[email protected]             if (!conn) break;
11489ab95c90S[email protected]             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
11497bdc6798S[email protected]             link_key_type_t link_key_type = (link_key_type_t)packet[24];
11509ab95c90S[email protected]             // Change Connection Encryption keeps link key type
11519ab95c90S[email protected]             if (link_key_type != CHANGED_COMBINATION_KEY){
11529ab95c90S[email protected]                 conn->link_key_type = link_key_type;
11539ab95c90S[email protected]             }
11543a9fb326S[email protected]             if (!hci_stack->remote_device_db) break;
11553a9fb326S[email protected]             hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type);
115629d53098Smatthias.ringwald             // still forward event to allow dismiss of pairing dialog
11577fde4af9Smatthias.ringwald             break;
11589ab95c90S[email protected]         }
11597fde4af9Smatthias.ringwald 
11607fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
11616724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
11624c57c146S[email protected]             // non-bondable mode: pin code negative reply will be sent
11633a9fb326S[email protected]             if (!hci_stack->bondable){
1164899283eaS[email protected]                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1165f8fb5f6eS[email protected]                 hci_run();
1166f8fb5f6eS[email protected]                 return;
11674c57c146S[email protected]             }
1168d9a327f9Smatthias.ringwald             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
11693a9fb326S[email protected]             if (!hci_stack->remote_device_db) break;
1170d9a327f9Smatthias.ringwald             bt_flip_addr(addr, &packet[2]);
11713a9fb326S[email protected]             hci_stack->remote_device_db->delete_link_key(&addr);
11727fde4af9Smatthias.ringwald             break;
11737fde4af9Smatthias.ringwald 
11741d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
11751d6b20aeS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1176dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1177dbe1a790S[email protected]             break;
1178dbe1a790S[email protected] 
1179dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
11806724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
11813a9fb326S[email protected]             if (!hci_stack->ssp_auto_accept) break;
1182dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1183dbe1a790S[email protected]             break;
1184dbe1a790S[email protected] 
1185dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
11866724cd9eS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
11873a9fb326S[email protected]             if (!hci_stack->ssp_auto_accept) break;
1188dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
11891d6b20aeS[email protected]             break;
11901d6b20aeS[email protected] 
1191f0944df2S[email protected]         case HCI_EVENT_ENCRYPTION_CHANGE:
1192f0944df2S[email protected]             handle = READ_BT_16(packet, 3);
1193f0944df2S[email protected]             conn = hci_connection_for_handle(handle);
1194f0944df2S[email protected]             if (!conn) break;
1195ad83dc6aS[email protected]             if (packet[2] == 0) {
1196f0944df2S[email protected]                 if (packet[5]){
1197f0944df2S[email protected]                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1198f0944df2S[email protected]                 } else {
1199536f9994S[email protected]                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1200f0944df2S[email protected]                 }
1201ad83dc6aS[email protected]             }
1202a00031e2S[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1203f0944df2S[email protected]             break;
1204f0944df2S[email protected] 
12051eb2563eS[email protected]         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
12061eb2563eS[email protected]             handle = READ_BT_16(packet, 3);
12071eb2563eS[email protected]             conn = hci_connection_for_handle(handle);
12081eb2563eS[email protected]             if (!conn) break;
1209ad83dc6aS[email protected] 
1210ad83dc6aS[email protected]             // dedicated bonding: send result and disconnect
1211ad83dc6aS[email protected]             if (conn->bonding_flags & BONDING_DEDICATED){
1212ad83dc6aS[email protected]                 conn->bonding_flags &= ~BONDING_DEDICATED;
1213ad83dc6aS[email protected]                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
12141bd5283dS[email protected]                 conn->bonding_status = packet[2];
1215ad83dc6aS[email protected]                 break;
1216ad83dc6aS[email protected]             }
1217ad83dc6aS[email protected] 
1218b5cb6874S[email protected]             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
12191eb2563eS[email protected]                 // link key sufficient for requested security
12201eb2563eS[email protected]                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1221ad83dc6aS[email protected]                 break;
1222ad83dc6aS[email protected]             }
12231eb2563eS[email protected]             // not enough
12241eb2563eS[email protected]             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
12251eb2563eS[email protected]             break;
122634d2123cS[email protected] 
1227223aafc1Smatthias.ringwald #ifndef EMBEDDED
122874ec757aSmatthias.ringwald         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
12293a9fb326S[email protected]             if (!hci_stack->remote_device_db) break;
123074ec757aSmatthias.ringwald             if (packet[2]) break; // status not ok
123174ec757aSmatthias.ringwald             bt_flip_addr(addr, &packet[3]);
12325a06394aSmatthias.ringwald             // fix for invalid remote names - terminate on 0xff
12335a06394aSmatthias.ringwald             for (i=0; i<248;i++){
12345a06394aSmatthias.ringwald                 if (packet[9+i] == 0xff){
12355a06394aSmatthias.ringwald                     packet[9+i] = 0;
12365a06394aSmatthias.ringwald                     break;
1237cdc9101dSmatthias.ringwald                 }
12385a06394aSmatthias.ringwald             }
1239d2fe945cS[email protected]             memset(&device_name, 0, sizeof(device_name_t));
124074ec757aSmatthias.ringwald             strncpy((char*) device_name, (char*) &packet[9], 248);
12413a9fb326S[email protected]             hci_stack->remote_device_db->put_name(&addr, &device_name);
124274ec757aSmatthias.ringwald             break;
124374ec757aSmatthias.ringwald 
124474ec757aSmatthias.ringwald         case HCI_EVENT_INQUIRY_RESULT:
1245206a9031S[email protected]         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{
12463a9fb326S[email protected]             if (!hci_stack->remote_device_db) break;
124774ec757aSmatthias.ringwald             // first send inq result packet
12483a9fb326S[email protected]             hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
124974ec757aSmatthias.ringwald             // then send cached remote names
1250206a9031S[email protected]             int offset = 3;
125174ec757aSmatthias.ringwald             for (i=0; i<packet[2];i++){
1252206a9031S[email protected]                 bt_flip_addr(addr, &packet[offset]);
1253206a9031S[email protected]                 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2;
12543a9fb326S[email protected]                 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){
125574ec757aSmatthias.ringwald                     hci_emit_remote_name_cached(&addr, &device_name);
125674ec757aSmatthias.ringwald                 }
125774ec757aSmatthias.ringwald             }
125874ec757aSmatthias.ringwald             return;
1259206a9031S[email protected]         }
1260223aafc1Smatthias.ringwald #endif
126174ec757aSmatthias.ringwald 
126286805605S[email protected]         // HCI_EVENT_DISCONNECTION_COMPLETE
126386805605S[email protected]         // has been moved down, to first notify stack before shutting connection down
12646772a24cSmatthias.ringwald 
1265c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
12663a9fb326S[email protected]             if(hci_stack->control && hci_stack->control->hw_error){
12673a9fb326S[email protected]                 (*hci_stack->control->hw_error)();
12687586ee35S[email protected]             } else {
12697586ee35S[email protected]                 // if no special requests, just reboot stack
12707586ee35S[email protected]                 hci_power_control_off();
12717586ee35S[email protected]                 hci_power_control_on();
1272c68bdf90Smatthias.ringwald             }
1273c68bdf90Smatthias.ringwald             break;
1274c68bdf90Smatthias.ringwald 
12756b4af23dS[email protected]         case DAEMON_EVENT_HCI_PACKET_SENT:
12766b4af23dS[email protected]             // free packet buffer for asynchronous transport
12776b4af23dS[email protected]             if (hci_transport_synchronous()) break;
12786b4af23dS[email protected]             hci_stack->hci_packet_buffer_reserved = 0;
12796b4af23dS[email protected]             break;
12806b4af23dS[email protected] 
12815909f7f2Smatthias.ringwald #ifdef HAVE_BLE
12825909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
12835909f7f2Smatthias.ringwald             switch (packet[2]){
128457c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
12859da54300S[email protected]                     log_info("advertising report received");
12867bdc6798S[email protected]                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
128757c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
12887bdc6798S[email protected]                     break;
12895909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
12905909f7f2Smatthias.ringwald                     // Connection management
12915909f7f2Smatthias.ringwald                     bt_flip_addr(addr, &packet[8]);
12927bdc6798S[email protected]                     addr_type = (bd_addr_type_t)packet[7];
12939da54300S[email protected]                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
12945909f7f2Smatthias.ringwald                     // LE connections are auto-accepted, so just create a connection if there isn't one already
129596a45072S[email protected]                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
12965909f7f2Smatthias.ringwald                     if (packet[3]){
12975909f7f2Smatthias.ringwald                         if (conn){
12985909f7f2Smatthias.ringwald                             // outgoing connection failed, remove entry
12993a9fb326S[email protected]                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
13005909f7f2Smatthias.ringwald                             btstack_memory_hci_connection_free( conn );
13015909f7f2Smatthias.ringwald                         }
13025909f7f2Smatthias.ringwald                         // if authentication error, also delete link key
13035909f7f2Smatthias.ringwald                         if (packet[3] == 0x05) {
13045909f7f2Smatthias.ringwald                             hci_drop_link_key_for_bd_addr(&addr);
13055909f7f2Smatthias.ringwald                         }
13065909f7f2Smatthias.ringwald                         break;
13075909f7f2Smatthias.ringwald                     }
13085909f7f2Smatthias.ringwald                     if (!conn){
130996a45072S[email protected]                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
13105909f7f2Smatthias.ringwald                     }
13115909f7f2Smatthias.ringwald                     if (!conn){
13125909f7f2Smatthias.ringwald                         // no memory
13135909f7f2Smatthias.ringwald                         break;
13145909f7f2Smatthias.ringwald                     }
13155909f7f2Smatthias.ringwald 
13165909f7f2Smatthias.ringwald                     conn->state = OPEN;
13175909f7f2Smatthias.ringwald                     conn->con_handle = READ_BT_16(packet, 4);
13185909f7f2Smatthias.ringwald 
13195909f7f2Smatthias.ringwald                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
13205909f7f2Smatthias.ringwald 
13215909f7f2Smatthias.ringwald                     // restart timer
13225909f7f2Smatthias.ringwald                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
13235909f7f2Smatthias.ringwald                     // run_loop_add_timer(&conn->timeout);
13245909f7f2Smatthias.ringwald 
13259da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
13265909f7f2Smatthias.ringwald 
13275909f7f2Smatthias.ringwald                     hci_emit_nr_connections_changed();
13285909f7f2Smatthias.ringwald                     break;
13295909f7f2Smatthias.ringwald 
13309da54300S[email protected]             // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]);
133165a46ef3S[email protected] 
13325909f7f2Smatthias.ringwald                 default:
13335909f7f2Smatthias.ringwald                     break;
13345909f7f2Smatthias.ringwald             }
13355909f7f2Smatthias.ringwald             break;
13365909f7f2Smatthias.ringwald #endif
13376772a24cSmatthias.ringwald         default:
13386772a24cSmatthias.ringwald             break;
1339fe1ed1b8Smatthias.ringwald     }
1340fe1ed1b8Smatthias.ringwald 
13413429f56bSmatthias.ringwald     // handle BT initialization
13423a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_INITIALIZING){
13436155b3d3S[email protected]         hci_initializing_event_handler(packet, size);
1344c9af4d3fS[email protected]     }
134522909952Smatthias.ringwald 
134689db417bSmatthias.ringwald     // help with BT sleep
13473a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
13483a9fb326S[email protected]         && hci_stack->substate == 1
134989db417bSmatthias.ringwald         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
13503a9fb326S[email protected]         hci_stack->substate++;
135189db417bSmatthias.ringwald     }
135289db417bSmatthias.ringwald 
135386805605S[email protected]     // notify upper stack
13543a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
135594ab26f8Smatthias.ringwald 
135686805605S[email protected]     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
135786805605S[email protected]     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
135886805605S[email protected]         if (!packet[2]){
135986805605S[email protected]             handle = READ_BT_16(packet, 3);
136086805605S[email protected]             hci_connection_t * conn = hci_connection_for_handle(handle);
136186805605S[email protected]             if (conn) {
136286805605S[email protected]                 uint8_t status = conn->bonding_status;
136386805605S[email protected]                 bd_addr_t bd_address;
136486805605S[email protected]                 memcpy(&bd_address, conn->address, 6);
136586805605S[email protected]                 hci_shutdown_connection(conn);
136686805605S[email protected]                 if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
136786805605S[email protected]                     hci_emit_dedicated_bonding_result(bd_address, status);
136886805605S[email protected]                 }
136986805605S[email protected]             }
137086805605S[email protected]         }
137186805605S[email protected]     }
137286805605S[email protected] 
137394ab26f8Smatthias.ringwald 	// execute main loop
137494ab26f8Smatthias.ringwald 	hci_run();
137516833f0aSmatthias.ringwald }
137616833f0aSmatthias.ringwald 
13770a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
137810e830c9Smatthias.ringwald     switch (packet_type) {
137910e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
138010e830c9Smatthias.ringwald             event_handler(packet, size);
138110e830c9Smatthias.ringwald             break;
138210e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
138310e830c9Smatthias.ringwald             acl_handler(packet, size);
138410e830c9Smatthias.ringwald             break;
138510e830c9Smatthias.ringwald         default:
138610e830c9Smatthias.ringwald             break;
138710e830c9Smatthias.ringwald     }
138810e830c9Smatthias.ringwald }
138910e830c9Smatthias.ringwald 
1390fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
13912718e2e7Smatthias.ringwald void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
13923a9fb326S[email protected]     hci_stack->packet_handler = handler;
139316833f0aSmatthias.ringwald }
139416833f0aSmatthias.ringwald 
13956155b3d3S[email protected] static void hci_state_reset(){
1396595bdbfbS[email protected]     // no connections yet
1397595bdbfbS[email protected]     hci_stack->connections = NULL;
139874308b23Smatthias.ringwald 
139974308b23Smatthias.ringwald     // keep discoverable/connectable as this has been requested by the client(s)
140074308b23Smatthias.ringwald     // hci_stack->discoverable = 0;
140174308b23Smatthias.ringwald     // hci_stack->connectable = 0;
140274308b23Smatthias.ringwald     // hci_stack->bondable = 1;
1403595bdbfbS[email protected] 
140444935e40S[email protected]     // buffer is free
140544935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
140644935e40S[email protected] 
1407595bdbfbS[email protected]     // no pending cmds
1408595bdbfbS[email protected]     hci_stack->decline_reason = 0;
1409595bdbfbS[email protected]     hci_stack->new_scan_enable_value = 0xff;
1410595bdbfbS[email protected] 
1411595bdbfbS[email protected]     // LE
1412595bdbfbS[email protected]     hci_stack->adv_addr_type = 0;
1413595bdbfbS[email protected]     memset(hci_stack->adv_address, 0, 6);
1414595bdbfbS[email protected]     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1415e2602ea2Smatthias.ringwald     hci_stack->le_scan_type = 0xff;
1416da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_interval_min = 0x0006;
1417da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_interval_max = 0x0C80;
1418da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_latency_min = 0x0000;
1419da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_latency_max = 0x03E8;
1420da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = 0x000A;
1421da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 0x0C80;
1422595bdbfbS[email protected] }
1423595bdbfbS[email protected] 
14244f4fc1dfSmatthias.ringwald void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
1425475c8125Smatthias.ringwald 
14263a9fb326S[email protected] #ifdef HAVE_MALLOC
14273a9fb326S[email protected]     if (!hci_stack) {
14283a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
14293a9fb326S[email protected]     }
14303a9fb326S[email protected] #else
14313a9fb326S[email protected]     hci_stack = &hci_stack_static;
14323a9fb326S[email protected] #endif
143366fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
14343a9fb326S[email protected] 
1435475c8125Smatthias.ringwald     // reference to use transport layer implementation
14363a9fb326S[email protected]     hci_stack->hci_transport = transport;
1437475c8125Smatthias.ringwald 
143811e23e5fSmatthias.ringwald     // references to used control implementation
14393a9fb326S[email protected]     hci_stack->control = control;
144011e23e5fSmatthias.ringwald 
144111e23e5fSmatthias.ringwald     // reference to used config
14423a9fb326S[email protected]     hci_stack->config = config;
144311e23e5fSmatthias.ringwald 
144416833f0aSmatthias.ringwald     // higher level handler
14453a9fb326S[email protected]     hci_stack->packet_handler = dummy_handler;
144616833f0aSmatthias.ringwald 
1447404843c1Smatthias.ringwald     // store and open remote device db
14483a9fb326S[email protected]     hci_stack->remote_device_db = remote_device_db;
14493a9fb326S[email protected]     if (hci_stack->remote_device_db) {
14503a9fb326S[email protected]         hci_stack->remote_device_db->open();
1451404843c1Smatthias.ringwald     }
145229d53098Smatthias.ringwald 
14538fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
14543a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
14558fcba05dSmatthias.ringwald 
145616833f0aSmatthias.ringwald     // register packet handlers with transport
145710e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
1458f5454fc6Smatthias.ringwald 
14593a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
1460e2386ba1S[email protected] 
1461e2386ba1S[email protected]     // class of device
14623a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
1463a45d6b9fS[email protected] 
1464f20168b8Smatthias.ringwald     // bondable by default
1465f20168b8Smatthias.ringwald     hci_stack->bondable = 1;
1466f20168b8Smatthias.ringwald 
146763048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
14683a9fb326S[email protected]     hci_stack->ssp_enable = 1;
14693a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
14703a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
14713a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
147269a97523S[email protected] 
1473595bdbfbS[email protected]     hci_state_reset();
1474475c8125Smatthias.ringwald }
1475475c8125Smatthias.ringwald 
1476404843c1Smatthias.ringwald void hci_close(){
1477404843c1Smatthias.ringwald     // close remote device db
14783a9fb326S[email protected]     if (hci_stack->remote_device_db) {
14793a9fb326S[email protected]         hci_stack->remote_device_db->close();
1480404843c1Smatthias.ringwald     }
14813a9fb326S[email protected]     while (hci_stack->connections) {
1482bc68afe2S[email protected]         // cancel all l2cap connections
1483bc68afe2S[email protected]         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
14843a9fb326S[email protected]         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1485f5454fc6Smatthias.ringwald     }
1486f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
14873a9fb326S[email protected] 
14883a9fb326S[email protected] #ifdef HAVE_MALLOC
14893a9fb326S[email protected]     free(hci_stack);
14903a9fb326S[email protected] #endif
14913a9fb326S[email protected]     hci_stack = NULL;
1492404843c1Smatthias.ringwald }
1493404843c1Smatthias.ringwald 
14949e61646fS[email protected] void hci_set_class_of_device(uint32_t class_of_device){
14959e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
14969e61646fS[email protected] }
14979e61646fS[email protected] 
149866fb9560S[email protected] void hci_disable_l2cap_timeout_check(){
149966fb9560S[email protected]     disable_l2cap_timeouts = 1;
150066fb9560S[email protected] }
15018d213e1aSmatthias.ringwald // State-Module-Driver overview
15028d213e1aSmatthias.ringwald // state                    module  low-level
15038d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
15048d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
15058d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
15068d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
1507d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
1508d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
1509c7e0c5f6Smatthias.ringwald 
151040d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
15117301ad89Smatthias.ringwald 
1512038bc64cSmatthias.ringwald     // power on
1513f9a30166Smatthias.ringwald     int err = 0;
15143a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
15153a9fb326S[email protected]         err = (*hci_stack->control->on)(hci_stack->config);
1516f9a30166Smatthias.ringwald     }
1517038bc64cSmatthias.ringwald     if (err){
15189da54300S[email protected]         log_error( "POWER_ON failed");
1519038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
1520038bc64cSmatthias.ringwald         return err;
1521038bc64cSmatthias.ringwald     }
1522038bc64cSmatthias.ringwald 
1523038bc64cSmatthias.ringwald     // open low-level device
15243a9fb326S[email protected]     err = hci_stack->hci_transport->open(hci_stack->config);
1525038bc64cSmatthias.ringwald     if (err){
15269da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
15273a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
15283a9fb326S[email protected]             (*hci_stack->control->off)(hci_stack->config);
1529f9a30166Smatthias.ringwald         }
1530038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
1531038bc64cSmatthias.ringwald         return err;
1532038bc64cSmatthias.ringwald     }
15338d213e1aSmatthias.ringwald     return 0;
15348d213e1aSmatthias.ringwald }
1535038bc64cSmatthias.ringwald 
153640d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
15378d213e1aSmatthias.ringwald 
15389da54300S[email protected]     log_info("hci_power_control_off");
15399418f9c9Smatthias.ringwald 
15408d213e1aSmatthias.ringwald     // close low-level device
15413a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
15428d213e1aSmatthias.ringwald 
15439da54300S[email protected]     log_info("hci_power_control_off - hci_transport closed");
15449418f9c9Smatthias.ringwald 
15458d213e1aSmatthias.ringwald     // power off
15463a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
15473a9fb326S[email protected]         (*hci_stack->control->off)(hci_stack->config);
15488d213e1aSmatthias.ringwald     }
15499418f9c9Smatthias.ringwald 
15509da54300S[email protected]     log_info("hci_power_control_off - control closed");
15519418f9c9Smatthias.ringwald 
15523a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
155372ea5239Smatthias.ringwald }
155472ea5239Smatthias.ringwald 
155540d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
155672ea5239Smatthias.ringwald 
15579da54300S[email protected]     log_info("hci_power_control_sleep");
15583144bce4Smatthias.ringwald 
1559b429b9b7Smatthias.ringwald #if 0
1560b429b9b7Smatthias.ringwald     // don't close serial port during sleep
1561b429b9b7Smatthias.ringwald 
156272ea5239Smatthias.ringwald     // close low-level device
15633a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
1564b429b9b7Smatthias.ringwald #endif
156572ea5239Smatthias.ringwald 
156672ea5239Smatthias.ringwald     // sleep mode
15673a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
15683a9fb326S[email protected]         (*hci_stack->control->sleep)(hci_stack->config);
156972ea5239Smatthias.ringwald     }
1570b429b9b7Smatthias.ringwald 
15713a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
15728d213e1aSmatthias.ringwald }
15738d213e1aSmatthias.ringwald 
157440d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
1575b429b9b7Smatthias.ringwald 
15769da54300S[email protected]     log_info("hci_power_control_wake");
1577b429b9b7Smatthias.ringwald 
1578b429b9b7Smatthias.ringwald     // wake on
15793a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
15803a9fb326S[email protected]         (*hci_stack->control->wake)(hci_stack->config);
1581b429b9b7Smatthias.ringwald     }
1582b429b9b7Smatthias.ringwald 
1583b429b9b7Smatthias.ringwald #if 0
1584b429b9b7Smatthias.ringwald     // open low-level device
15853a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
1586b429b9b7Smatthias.ringwald     if (err){
15879da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
15883a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
15893a9fb326S[email protected]             (*hci_stack->control->off)(hci_stack->config);
1590b429b9b7Smatthias.ringwald         }
1591b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
1592b429b9b7Smatthias.ringwald         return err;
1593b429b9b7Smatthias.ringwald     }
1594b429b9b7Smatthias.ringwald #endif
1595b429b9b7Smatthias.ringwald 
1596b429b9b7Smatthias.ringwald     return 0;
1597b429b9b7Smatthias.ringwald }
1598b429b9b7Smatthias.ringwald 
159944935e40S[email protected] static void hci_power_transition_to_initializing(void){
160044935e40S[email protected]     // set up state machine
160144935e40S[email protected]     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
160244935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
160344935e40S[email protected]     hci_stack->state = HCI_STATE_INITIALIZING;
160444935e40S[email protected]     hci_stack->substate = 0;
160544935e40S[email protected] }
1606b429b9b7Smatthias.ringwald 
16078d213e1aSmatthias.ringwald int hci_power_control(HCI_POWER_MODE power_mode){
1608d661ed19Smatthias.ringwald 
16099da54300S[email protected]     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
1610d661ed19Smatthias.ringwald 
16118d213e1aSmatthias.ringwald     int err = 0;
16123a9fb326S[email protected]     switch (hci_stack->state){
16138d213e1aSmatthias.ringwald 
16148d213e1aSmatthias.ringwald         case HCI_STATE_OFF:
16158d213e1aSmatthias.ringwald             switch (power_mode){
16168d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
16178d213e1aSmatthias.ringwald                     err = hci_power_control_on();
161897b61c7bS[email protected]                     if (err) {
161997b61c7bS[email protected]                         log_error("hci_power_control_on() error %u", err);
162097b61c7bS[email protected]                         return err;
162197b61c7bS[email protected]                     }
162244935e40S[email protected]                     hci_power_transition_to_initializing();
16238d213e1aSmatthias.ringwald                     break;
16248d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
16258d213e1aSmatthias.ringwald                     // do nothing
16268d213e1aSmatthias.ringwald                     break;
16278d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1628b546ac54Smatthias.ringwald                     // do nothing (with SLEEP == OFF)
16298d213e1aSmatthias.ringwald                     break;
16308d213e1aSmatthias.ringwald             }
16318d213e1aSmatthias.ringwald             break;
16327301ad89Smatthias.ringwald 
16338d213e1aSmatthias.ringwald         case HCI_STATE_INITIALIZING:
16348d213e1aSmatthias.ringwald             switch (power_mode){
16358d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
16368d213e1aSmatthias.ringwald                     // do nothing
16378d213e1aSmatthias.ringwald                     break;
16388d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
16398d213e1aSmatthias.ringwald                     // no connections yet, just turn it off
16408d213e1aSmatthias.ringwald                     hci_power_control_off();
16418d213e1aSmatthias.ringwald                     break;
16428d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1643b546ac54Smatthias.ringwald                     // no connections yet, just turn it off
164472ea5239Smatthias.ringwald                     hci_power_control_sleep();
16458d213e1aSmatthias.ringwald                     break;
16468d213e1aSmatthias.ringwald             }
16478d213e1aSmatthias.ringwald             break;
16487301ad89Smatthias.ringwald 
16498d213e1aSmatthias.ringwald         case HCI_STATE_WORKING:
16508d213e1aSmatthias.ringwald             switch (power_mode){
16518d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
16528d213e1aSmatthias.ringwald                     // do nothing
16538d213e1aSmatthias.ringwald                     break;
16548d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
1655c7e0c5f6Smatthias.ringwald                     // see hci_run
16563a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
16578d213e1aSmatthias.ringwald                     break;
16588d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1659b546ac54Smatthias.ringwald                     // see hci_run
16603a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
16613a9fb326S[email protected]                     hci_stack->substate = 0;
16628d213e1aSmatthias.ringwald                     break;
16638d213e1aSmatthias.ringwald             }
16648d213e1aSmatthias.ringwald             break;
16657301ad89Smatthias.ringwald 
16668d213e1aSmatthias.ringwald         case HCI_STATE_HALTING:
16678d213e1aSmatthias.ringwald             switch (power_mode){
16688d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
166944935e40S[email protected]                     hci_power_transition_to_initializing();
16708d213e1aSmatthias.ringwald                     break;
16718d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
16728d213e1aSmatthias.ringwald                     // do nothing
16738d213e1aSmatthias.ringwald                     break;
16748d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1675b546ac54Smatthias.ringwald                     // see hci_run
16763a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
16773a9fb326S[email protected]                     hci_stack->substate = 0;
16788d213e1aSmatthias.ringwald                     break;
16798d213e1aSmatthias.ringwald             }
16808d213e1aSmatthias.ringwald             break;
16818d213e1aSmatthias.ringwald 
16828d213e1aSmatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
16838d213e1aSmatthias.ringwald             switch (power_mode){
16848d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
168528171530Smatthias.ringwald 
168628171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
168728171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
168828171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
16893a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
16903a9fb326S[email protected]                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
169128171530Smatthias.ringwald                         break;
169228171530Smatthias.ringwald                     }
169328171530Smatthias.ringwald #endif
169444935e40S[email protected]                     hci_power_transition_to_initializing();
16958d213e1aSmatthias.ringwald                     break;
16968d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
1697b546ac54Smatthias.ringwald                     // see hci_run
16983a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
16998d213e1aSmatthias.ringwald                     break;
17008d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1701b546ac54Smatthias.ringwald                     // do nothing
17028d213e1aSmatthias.ringwald                     break;
17038d213e1aSmatthias.ringwald             }
17048d213e1aSmatthias.ringwald             break;
17058d213e1aSmatthias.ringwald 
17068d213e1aSmatthias.ringwald         case HCI_STATE_SLEEPING:
17078d213e1aSmatthias.ringwald             switch (power_mode){
17088d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
170928171530Smatthias.ringwald 
171028171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
171128171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
171228171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
17133a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
17143a9fb326S[email protected]                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1715758b46ceSmatthias.ringwald                         hci_update_scan_enable();
171628171530Smatthias.ringwald                         break;
171728171530Smatthias.ringwald                     }
171828171530Smatthias.ringwald #endif
17193144bce4Smatthias.ringwald                     err = hci_power_control_wake();
17203144bce4Smatthias.ringwald                     if (err) return err;
172144935e40S[email protected]                     hci_power_transition_to_initializing();
17228d213e1aSmatthias.ringwald                     break;
17238d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
17243a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
17258d213e1aSmatthias.ringwald                     break;
17268d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1727b546ac54Smatthias.ringwald                     // do nothing
17288d213e1aSmatthias.ringwald                     break;
17298d213e1aSmatthias.ringwald             }
17308d213e1aSmatthias.ringwald             break;
173111e23e5fSmatthias.ringwald     }
173268d92d03Smatthias.ringwald 
1733038bc64cSmatthias.ringwald     // create internal event
1734ee8bf225Smatthias.ringwald 	hci_emit_state();
1735ee8bf225Smatthias.ringwald 
173668d92d03Smatthias.ringwald 	// trigger next/first action
173768d92d03Smatthias.ringwald 	hci_run();
173868d92d03Smatthias.ringwald 
1739475c8125Smatthias.ringwald     return 0;
1740475c8125Smatthias.ringwald }
1741475c8125Smatthias.ringwald 
1742758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
1743758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
17443a9fb326S[email protected]     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1745758b46ceSmatthias.ringwald     hci_run();
1746758b46ceSmatthias.ringwald }
1747758b46ceSmatthias.ringwald 
1748381fbed8Smatthias.ringwald void hci_discoverable_control(uint8_t enable){
1749381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
1750381fbed8Smatthias.ringwald 
17513a9fb326S[email protected]     if (hci_stack->discoverable == enable){
17523a9fb326S[email protected]         hci_emit_discoverable_enabled(hci_stack->discoverable);
1753381fbed8Smatthias.ringwald         return;
1754381fbed8Smatthias.ringwald     }
1755381fbed8Smatthias.ringwald 
17563a9fb326S[email protected]     hci_stack->discoverable = enable;
1757758b46ceSmatthias.ringwald     hci_update_scan_enable();
1758758b46ceSmatthias.ringwald }
1759b031bebbSmatthias.ringwald 
1760758b46ceSmatthias.ringwald void hci_connectable_control(uint8_t enable){
1761758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
1762758b46ceSmatthias.ringwald 
1763758b46ceSmatthias.ringwald     // don't emit event
17643a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
1765758b46ceSmatthias.ringwald 
17663a9fb326S[email protected]     hci_stack->connectable = enable;
1767758b46ceSmatthias.ringwald     hci_update_scan_enable();
1768381fbed8Smatthias.ringwald }
1769381fbed8Smatthias.ringwald 
17705061f3afS[email protected] bd_addr_t * hci_local_bd_addr(void){
17713a9fb326S[email protected]     return &hci_stack->local_bd_addr;
17725061f3afS[email protected] }
17735061f3afS[email protected] 
177406b35ec0Smatthias.ringwald void hci_run(){
17758a485f27Smatthias.ringwald 
177632ab9390Smatthias.ringwald     hci_connection_t * connection;
177732ab9390Smatthias.ringwald     linked_item_t * it;
177832ab9390Smatthias.ringwald 
1779d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()) return;
1780ce4c8fabSmatthias.ringwald 
1781b031bebbSmatthias.ringwald     // global/non-connection oriented commands
1782b031bebbSmatthias.ringwald 
1783b031bebbSmatthias.ringwald     // decline incoming connections
17843a9fb326S[email protected]     if (hci_stack->decline_reason){
17853a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
17863a9fb326S[email protected]         hci_stack->decline_reason = 0;
17873a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1788dbe1a790S[email protected]         return;
1789ce4c8fabSmatthias.ringwald     }
1790ce4c8fabSmatthias.ringwald 
1791b031bebbSmatthias.ringwald     // send scan enable
17923a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
17933a9fb326S[email protected]         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
17943a9fb326S[email protected]         hci_stack->new_scan_enable_value = 0xff;
1795dbe1a790S[email protected]         return;
1796b031bebbSmatthias.ringwald     }
1797b031bebbSmatthias.ringwald 
1798b2f949feS[email protected] #ifdef HAVE_BLE
17997bdc6798S[email protected]     // handle le scan
18007bdc6798S[email protected]     if (hci_stack->state == HCI_STATE_WORKING){
18017bdc6798S[email protected]         switch(hci_stack->le_scanning_state){
18027bdc6798S[email protected]             case LE_START_SCAN:
18037bdc6798S[email protected]                 hci_stack->le_scanning_state = LE_SCANNING;
18047bdc6798S[email protected]                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
18057bdc6798S[email protected]                 return;
18067bdc6798S[email protected] 
18077bdc6798S[email protected]             case LE_STOP_SCAN:
18087bdc6798S[email protected]                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
18097bdc6798S[email protected]                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
18107bdc6798S[email protected]                 return;
18117bdc6798S[email protected]             default:
18127bdc6798S[email protected]                 break;
18137bdc6798S[email protected]         }
1814e2602ea2Smatthias.ringwald         if (hci_stack->le_scan_type != 0xff){
1815e2602ea2Smatthias.ringwald             // defaults: active scanning, accept all advertisement packets
1816e2602ea2Smatthias.ringwald             int scan_type = hci_stack->le_scan_type;
1817e2602ea2Smatthias.ringwald             hci_stack->le_scan_type = 0xff;
1818e2602ea2Smatthias.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);
1819e2602ea2Smatthias.ringwald             return;
1820e2602ea2Smatthias.ringwald         }
18217bdc6798S[email protected]     }
1822b2f949feS[email protected] #endif
18237bdc6798S[email protected] 
182432ab9390Smatthias.ringwald     // send pending HCI commands
18253a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1826b031bebbSmatthias.ringwald         connection = (hci_connection_t *) it;
182732ab9390Smatthias.ringwald 
18280bf6344aS[email protected]         switch(connection->state){
18290bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
18304f3229d8S[email protected]                 switch(connection->address_type){
18314f3229d8S[email protected]                     case BD_ADDR_TYPE_CLASSIC:
18329da54300S[email protected]                         log_info("sending hci_create_connection");
1833ad83dc6aS[email protected]                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
18344f3229d8S[email protected]                         break;
18354f3229d8S[email protected]                     default:
1836b2f949feS[email protected] #ifdef HAVE_BLE
18379da54300S[email protected]                         log_info("sending hci_le_create_connection");
18384f3229d8S[email protected]                         hci_send_cmd(&hci_le_create_connection,
1839b2571179Smatthias.ringwald                                      0x0060,    // scan interval: 60 ms
1840b2571179Smatthias.ringwald                                      0x0030,    // scan interval: 30 ms
18414f3229d8S[email protected]                                      0,         // don't use whitelist
18424f3229d8S[email protected]                                      connection->address_type, // peer address type
18434f3229d8S[email protected]                                      connection->address,      // peer bd addr
1844b2571179Smatthias.ringwald                                      hci_stack->adv_addr_type, // our addr type:
1845b2571179Smatthias.ringwald                                      0x0008,    // conn interval min
1846b2571179Smatthias.ringwald                                      0x0018,    // conn interval max
18474f3229d8S[email protected]                                      0,         // conn latency
1848b2571179Smatthias.ringwald                                      0x0048,    // supervision timeout
1849b2571179Smatthias.ringwald                                      0x0001,    // min ce length
1850b2571179Smatthias.ringwald                                      0x0001     // max ce length
18514f3229d8S[email protected]                                      );
18524f3229d8S[email protected] 
18534f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
1854b2f949feS[email protected] #endif
18554f3229d8S[email protected]                         break;
18564f3229d8S[email protected]                 }
1857ad83dc6aS[email protected]                 return;
1858ad83dc6aS[email protected] 
18590bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
18609da54300S[email protected]                 log_info("sending hci_accept_connection_request");
186132ab9390Smatthias.ringwald                 connection->state = ACCEPTED_CONNECTION_REQUEST;
186234d2123cS[email protected]                 hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1863dbe1a790S[email protected]                 return;
18640bf6344aS[email protected] 
1865a6725849S[email protected] #ifdef HAVE_BLE
18660bf6344aS[email protected]             case SEND_CANCEL_CONNECTION:
18670bf6344aS[email protected]                 connection->state = SENT_CANCEL_CONNECTION;
18680bf6344aS[email protected]                 hci_send_cmd(&hci_le_create_connection_cancel);
18690bf6344aS[email protected]                 return;
1870a6725849S[email protected] #endif
18710bf6344aS[email protected]             case SEND_DISCONNECT:
18720bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
18737851196eSmatthias.ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
18740bf6344aS[email protected]                 return;
18750bf6344aS[email protected] 
18760bf6344aS[email protected]             default:
18770bf6344aS[email protected]                 break;
1878c7e0c5f6Smatthias.ringwald         }
1879c7e0c5f6Smatthias.ringwald 
188032ab9390Smatthias.ringwald         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
18819da54300S[email protected]             log_info("responding to link key request");
188234d2123cS[email protected]             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
188332ab9390Smatthias.ringwald             link_key_t link_key;
1884c77e8838S[email protected]             link_key_type_t link_key_type;
18853a9fb326S[email protected]             if ( hci_stack->remote_device_db
18863a9fb326S[email protected]               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
188734d2123cS[email protected]               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
18889ab95c90S[email protected]                connection->link_key_type = link_key_type;
188932ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
189032ab9390Smatthias.ringwald             } else {
189132ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
189232ab9390Smatthias.ringwald             }
1893dbe1a790S[email protected]             return;
189432ab9390Smatthias.ringwald         }
18951d6b20aeS[email protected] 
1896899283eaS[email protected]         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
18979da54300S[email protected]             log_info("denying to pin request");
1898899283eaS[email protected]             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
189934d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
19004c57c146S[email protected]             return;
19014c57c146S[email protected]         }
19024c57c146S[email protected] 
1903dbe1a790S[email protected]         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
190434d2123cS[email protected]             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
190582d8f825S[email protected]             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
190682d8f825S[email protected]             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1907106d6d11S[email protected]                 // tweak authentication requirements
19083a9fb326S[email protected]                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1909106d6d11S[email protected]                 if (connection->bonding_flags & BONDING_DEDICATED){
19109faad3abS[email protected]                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
19119faad3abS[email protected]                 }
19129faad3abS[email protected]                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
19139faad3abS[email protected]                     authreq |= 1;
1914106d6d11S[email protected]                 }
19153a9fb326S[email protected]                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1916f8fb5f6eS[email protected]             } else {
1917f8fb5f6eS[email protected]                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1918f8fb5f6eS[email protected]             }
1919dbe1a790S[email protected]             return;
192032ab9390Smatthias.ringwald         }
192132ab9390Smatthias.ringwald 
1922dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1923dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
192434d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1925dbe1a790S[email protected]             return;
1926dbe1a790S[email protected]         }
1927dbe1a790S[email protected] 
1928dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1929dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
193034d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1931dbe1a790S[email protected]             return;
1932dbe1a790S[email protected]         }
1933afd4e962S[email protected] 
1934afd4e962S[email protected]         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1935afd4e962S[email protected]             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
193634d2123cS[email protected]             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
19372bd8b7e7S[email protected]             return;
19382bd8b7e7S[email protected]         }
19392bd8b7e7S[email protected] 
19402bd8b7e7S[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
19412bd8b7e7S[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
194234d2123cS[email protected]             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
194334d2123cS[email protected]             return;
194434d2123cS[email protected]         }
1945ad83dc6aS[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1946ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
19471bd5283dS[email protected]             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
194852d34f98S[email protected]             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1949ad83dc6aS[email protected]             return;
1950ad83dc6aS[email protected]         }
195134d2123cS[email protected]         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
195234d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
195334d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
19542bd8b7e7S[email protected]             return;
1955afd4e962S[email protected]         }
1956dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1957dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1958dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1959dce78009S[email protected]             return;
1960dce78009S[email protected]         }
1961da886c03S[email protected] 
1962c37a3166S[email protected] #ifdef HAVE_BLE
1963da886c03S[email protected]         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
1964da886c03S[email protected]             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1965da886c03S[email protected] 
1966c37a3166S[email protected]             uint16_t connection_interval_min = connection->le_conn_interval_min;
1967c37a3166S[email protected]             connection->le_conn_interval_min = 0;
1968c37a3166S[email protected]             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
1969c37a3166S[email protected]                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
1970c37a3166S[email protected]                 0x0000, 0xffff);
1971c37a3166S[email protected]         }
1972c37a3166S[email protected] #endif
1973dbe1a790S[email protected]     }
1974c7e0c5f6Smatthias.ringwald 
1975452cf3bbS[email protected]     // send continuation fragments
1976452cf3bbS[email protected]     if (hci_stack->acl_fragmentation_total_size > 0) {
1977452cf3bbS[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
1978452cf3bbS[email protected]         if (hci_can_send_prepared_acl_packet_now(con_handle)){
1979452cf3bbS[email protected]             hci_connection_t *connection = hci_connection_for_handle(con_handle);
1980452cf3bbS[email protected]             if (connection) {
1981452cf3bbS[email protected]                 hci_send_acl_packet_fragments(connection);
1982452cf3bbS[email protected]                 return;
1983452cf3bbS[email protected]             }
1984452cf3bbS[email protected]             // connection gone -> discard further fragments
1985452cf3bbS[email protected]             hci_stack->acl_fragmentation_total_size = 0;
1986452cf3bbS[email protected]             hci_stack->acl_fragmentation_pos = 0;
1987452cf3bbS[email protected]         }
1988452cf3bbS[email protected]     }
1989452cf3bbS[email protected] 
19903a9fb326S[email protected]     switch (hci_stack->state){
19913429f56bSmatthias.ringwald         case HCI_STATE_INITIALIZING:
1992bd88fde9S[email protected]             hci_initializing_state_machine();
19933429f56bSmatthias.ringwald             break;
1994c7e0c5f6Smatthias.ringwald 
1995c7e0c5f6Smatthias.ringwald         case HCI_STATE_HALTING:
1996c7e0c5f6Smatthias.ringwald 
19979da54300S[email protected]             log_info("HCI_STATE_HALTING");
1998c7e0c5f6Smatthias.ringwald             // close all open connections
19993a9fb326S[email protected]             connection =  (hci_connection_t *) hci_stack->connections;
2000c7e0c5f6Smatthias.ringwald             if (connection){
200132ab9390Smatthias.ringwald 
2002c7e0c5f6Smatthias.ringwald                 // send disconnect
2003d94d3cafS[email protected]                 if (!hci_can_send_command_packet_now()) return;
200432ab9390Smatthias.ringwald 
20059da54300S[email protected]                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
20066ad890d3Smatthias.ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2007c7e0c5f6Smatthias.ringwald 
2008c7e0c5f6Smatthias.ringwald                 // send disconnected event right away - causes higher layer connections to get closed, too.
2009c7e0c5f6Smatthias.ringwald                 hci_shutdown_connection(connection);
2010c7e0c5f6Smatthias.ringwald                 return;
2011c7e0c5f6Smatthias.ringwald             }
20129da54300S[email protected]             log_info("HCI_STATE_HALTING, calling off");
2013c7e0c5f6Smatthias.ringwald 
201472ea5239Smatthias.ringwald             // switch mode
2015c7e0c5f6Smatthias.ringwald             hci_power_control_off();
20169418f9c9Smatthias.ringwald 
20179da54300S[email protected]             log_info("HCI_STATE_HALTING, emitting state");
201872ea5239Smatthias.ringwald             hci_emit_state();
20199da54300S[email protected]             log_info("HCI_STATE_HALTING, done");
202072ea5239Smatthias.ringwald             break;
2021c7e0c5f6Smatthias.ringwald 
202272ea5239Smatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
20233a9fb326S[email protected]             switch(hci_stack->substate) {
202489db417bSmatthias.ringwald                 case 0:
20259da54300S[email protected]                     log_info("HCI_STATE_FALLING_ASLEEP");
202672ea5239Smatthias.ringwald                     // close all open connections
20273a9fb326S[email protected]                     connection =  (hci_connection_t *) hci_stack->connections;
202866da7044Smatthias.ringwald 
202928171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
203066da7044Smatthias.ringwald                     // don't close connections, if H4 supports power management
203166da7044Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
203266da7044Smatthias.ringwald                         connection = NULL;
203366da7044Smatthias.ringwald                     }
203466da7044Smatthias.ringwald #endif
203572ea5239Smatthias.ringwald                     if (connection){
203632ab9390Smatthias.ringwald 
203772ea5239Smatthias.ringwald                         // send disconnect
2038d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
203932ab9390Smatthias.ringwald 
20409da54300S[email protected]                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
20416ad890d3Smatthias.ringwald                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
204272ea5239Smatthias.ringwald 
204372ea5239Smatthias.ringwald                         // send disconnected event right away - causes higher layer connections to get closed, too.
204472ea5239Smatthias.ringwald                         hci_shutdown_connection(connection);
204572ea5239Smatthias.ringwald                         return;
204672ea5239Smatthias.ringwald                     }
204772ea5239Smatthias.ringwald 
204892368cd3S[email protected]                     if (hci_classic_supported()){
204989db417bSmatthias.ringwald                         // disable page and inquiry scan
2050d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
205132ab9390Smatthias.ringwald 
20529da54300S[email protected]                         log_info("HCI_STATE_HALTING, disabling inq scans");
20533a9fb326S[email protected]                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
205489db417bSmatthias.ringwald 
205589db417bSmatthias.ringwald                         // continue in next sub state
20563a9fb326S[email protected]                         hci_stack->substate++;
205789db417bSmatthias.ringwald                         break;
205892368cd3S[email protected]                     }
205992368cd3S[email protected]                     // fall through for ble-only chips
206092368cd3S[email protected] 
206189db417bSmatthias.ringwald                 case 2:
20629da54300S[email protected]                     log_info("HCI_STATE_HALTING, calling sleep");
206328171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
206428171530Smatthias.ringwald                     // don't actually go to sleep, if H4 supports power management
206528171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
206628171530Smatthias.ringwald                         // SLEEP MODE reached
20673a9fb326S[email protected]                         hci_stack->state = HCI_STATE_SLEEPING;
206828171530Smatthias.ringwald                         hci_emit_state();
206928171530Smatthias.ringwald                         break;
207028171530Smatthias.ringwald                     }
207128171530Smatthias.ringwald #endif
207272ea5239Smatthias.ringwald                     // switch mode
20733a9fb326S[email protected]                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
2074c7e0c5f6Smatthias.ringwald                     hci_emit_state();
207528171530Smatthias.ringwald                     break;
207628171530Smatthias.ringwald 
207789db417bSmatthias.ringwald                 default:
207889db417bSmatthias.ringwald                     break;
207989db417bSmatthias.ringwald             }
2080c7e0c5f6Smatthias.ringwald             break;
2081c7e0c5f6Smatthias.ringwald 
20823429f56bSmatthias.ringwald         default:
20833429f56bSmatthias.ringwald             break;
20841f504dbdSmatthias.ringwald     }
20853429f56bSmatthias.ringwald }
208616833f0aSmatthias.ringwald 
208731452debSmatthias.ringwald int hci_send_cmd_packet(uint8_t *packet, int size){
2088c8e4258aSmatthias.ringwald     bd_addr_t addr;
2089c8e4258aSmatthias.ringwald     hci_connection_t * conn;
2090c8e4258aSmatthias.ringwald     // house-keeping
2091c8e4258aSmatthias.ringwald 
2092c8e4258aSmatthias.ringwald     // create_connection?
2093c8e4258aSmatthias.ringwald     if (IS_COMMAND(packet, hci_create_connection)){
2094c8e4258aSmatthias.ringwald         bt_flip_addr(addr, &packet[3]);
20959da54300S[email protected]         log_info("Create_connection to %s", bd_addr_to_str(addr));
2096c8e4258aSmatthias.ringwald 
209796a45072S[email protected]         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2098ad83dc6aS[email protected]         if (!conn){
209996a45072S[email protected]             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
210017f1ba2aSmatthias.ringwald             if (!conn){
210117f1ba2aSmatthias.ringwald                 // notify client that alloc failed
210217f1ba2aSmatthias.ringwald                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
210317f1ba2aSmatthias.ringwald                 return 0; // don't sent packet to controller
210417f1ba2aSmatthias.ringwald             }
2105ad83dc6aS[email protected]             conn->state = SEND_CREATE_CONNECTION;
2106ad83dc6aS[email protected]         }
2107ad83dc6aS[email protected]         log_info("conn state %u", conn->state);
2108ad83dc6aS[email protected]         switch (conn->state){
2109ad83dc6aS[email protected]             // if connection active exists
2110ad83dc6aS[email protected]             case OPEN:
211162bda3fbS[email protected]                 // and OPEN, emit connection complete command, don't send to controller
2112ad83dc6aS[email protected]                 hci_emit_connection_complete(conn, 0);
211362bda3fbS[email protected]                 return 0;
2114ad83dc6aS[email protected]             case SEND_CREATE_CONNECTION:
2115ad83dc6aS[email protected]                 // connection created by hci, e.g. dedicated bonding
2116ad83dc6aS[email protected]                 break;
2117ad83dc6aS[email protected]             default:
2118ad83dc6aS[email protected]                 // otherwise, just ignore as it is already in the open process
2119ad83dc6aS[email protected]                 return 0;
2120ad83dc6aS[email protected]         }
2121c8e4258aSmatthias.ringwald         conn->state = SENT_CREATE_CONNECTION;
2122c8e4258aSmatthias.ringwald     }
2123c8e4258aSmatthias.ringwald 
21247fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_reply)){
21257fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
21267fde4af9Smatthias.ringwald     }
21277fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
21287fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
21297fde4af9Smatthias.ringwald     }
21307fde4af9Smatthias.ringwald 
21318ef73945Smatthias.ringwald     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
21323a9fb326S[email protected]         if (hci_stack->remote_device_db){
21338ef73945Smatthias.ringwald             bt_flip_addr(addr, &packet[3]);
21343a9fb326S[email protected]             hci_stack->remote_device_db->delete_link_key(&addr);
21358ef73945Smatthias.ringwald         }
21368ef73945Smatthias.ringwald     }
2137c8e4258aSmatthias.ringwald 
21386724cd9eS[email protected]     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
21396724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
21406724cd9eS[email protected]         bt_flip_addr(addr, &packet[3]);
214196a45072S[email protected]         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
21426724cd9eS[email protected]         if (conn){
21436724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
21446724cd9eS[email protected]         }
21456724cd9eS[email protected]     }
21466724cd9eS[email protected] 
21476724cd9eS[email protected]     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
21486724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
21496724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
21506724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
21516724cd9eS[email protected]         bt_flip_addr(addr, &packet[3]);
215296a45072S[email protected]         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
21536724cd9eS[email protected]         if (conn){
21546724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
21556724cd9eS[email protected]         }
21566724cd9eS[email protected]     }
21576724cd9eS[email protected] 
215869a97523S[email protected] #ifdef HAVE_BLE
215969a97523S[email protected]     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
21603a9fb326S[email protected]         hci_stack->adv_addr_type = packet[8];
216169a97523S[email protected]     }
216269a97523S[email protected]     if (IS_COMMAND(packet, hci_le_set_random_address)){
21633a9fb326S[email protected]         bt_flip_addr(hci_stack->adv_address, &packet[3]);
216469a97523S[email protected]     }
216569a97523S[email protected] #endif
216669a97523S[email protected] 
21673a9fb326S[email protected]     hci_stack->num_cmd_packets--;
21686b4af23dS[email protected]     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
21696b4af23dS[email protected] 
21706b4af23dS[email protected]     // free packet buffer for synchronous transport implementations
2171c8b9416aS[email protected]     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
21726b4af23dS[email protected]         hci_stack->hci_packet_buffer_reserved = 0;
21736b4af23dS[email protected]     }
21746b4af23dS[email protected] 
21756b4af23dS[email protected]     return err;
217631452debSmatthias.ringwald }
21778adf0ddaSmatthias.ringwald 
21782bd8b7e7S[email protected] // disconnect because of security block
21792bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
21802bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
21812bd8b7e7S[email protected]     if (!connection) return;
21822bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
21832bd8b7e7S[email protected] }
21842bd8b7e7S[email protected] 
21852bd8b7e7S[email protected] 
2186dbe1a790S[email protected] // Configure Secure Simple Pairing
2187dbe1a790S[email protected] 
2188dbe1a790S[email protected] // enable will enable SSP during init
2189dbe1a790S[email protected] void hci_ssp_set_enable(int enable){
21903a9fb326S[email protected]     hci_stack->ssp_enable = enable;
2191dbe1a790S[email protected] }
2192dbe1a790S[email protected] 
21932bd8b7e7S[email protected] int hci_local_ssp_activated(){
21943a9fb326S[email protected]     return hci_ssp_supported() && hci_stack->ssp_enable;
21952bd8b7e7S[email protected] }
21962bd8b7e7S[email protected] 
2197dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
2198dbe1a790S[email protected] void hci_ssp_set_io_capability(int io_capability){
21993a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
2200dbe1a790S[email protected] }
2201dbe1a790S[email protected] void hci_ssp_set_authentication_requirement(int authentication_requirement){
22023a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
2203dbe1a790S[email protected] }
2204dbe1a790S[email protected] 
2205dbe1a790S[email protected] // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2206dbe1a790S[email protected] void hci_ssp_set_auto_accept(int auto_accept){
22073a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
2208dbe1a790S[email protected] }
2209dbe1a790S[email protected] 
22101cd208adSmatthias.ringwald /**
22111cd208adSmatthias.ringwald  * pre: numcmds >= 0 - it's allowed to send a command to the controller
22121cd208adSmatthias.ringwald  */
2213fe35119dSmatthias.ringwald int hci_send_cmd(const hci_cmd_t *cmd, ...){
22145127cc62S[email protected] 
2215d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()){
22169d14b626S[email protected]         log_error("hci_send_cmd called but cannot send packet now");
22179d14b626S[email protected]         return 0;
22189d14b626S[email protected]     }
22199d14b626S[email protected] 
22205127cc62S[email protected]     // for HCI INITIALIZATION
22219da54300S[email protected]     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
22225127cc62S[email protected]     hci_stack->last_cmd_opcode = cmd->opcode;
22235127cc62S[email protected] 
22249d14b626S[email protected]     hci_reserve_packet_buffer();
22259d14b626S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
22269d14b626S[email protected] 
22271cd208adSmatthias.ringwald     va_list argptr;
22281cd208adSmatthias.ringwald     va_start(argptr, cmd);
22299d14b626S[email protected]     uint16_t size = hci_create_cmd_internal(packet, cmd, argptr);
22301cd208adSmatthias.ringwald     va_end(argptr);
22319d14b626S[email protected] 
22329d14b626S[email protected]     return hci_send_cmd_packet(packet, size);
223393b8dc03Smatthias.ringwald }
2234c8e4258aSmatthias.ringwald 
2235ee091cf1Smatthias.ringwald // Create various non-HCI events.
2236ee091cf1Smatthias.ringwald // TODO: generalize, use table similar to hci_create_command
2237ee091cf1Smatthias.ringwald 
2238c8e4258aSmatthias.ringwald void hci_emit_state(){
22393a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2240425d1371Smatthias.ringwald     uint8_t event[3];
224180d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
2242425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
22433a9fb326S[email protected]     event[2] = hci_stack->state;
2244425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
22453a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2246c8e4258aSmatthias.ringwald }
2247c8e4258aSmatthias.ringwald 
224817f1ba2aSmatthias.ringwald void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
2249425d1371Smatthias.ringwald     uint8_t event[13];
2250c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
2251425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
225217f1ba2aSmatthias.ringwald     event[2] = status;
2253c8e4258aSmatthias.ringwald     bt_store_16(event, 3, conn->con_handle);
2254c8e4258aSmatthias.ringwald     bt_flip_addr(&event[5], conn->address);
2255c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
2256c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
2257425d1371Smatthias.ringwald     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
22583a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2259c8e4258aSmatthias.ringwald }
2260c8e4258aSmatthias.ringwald 
22614f3229d8S[email protected] void hci_emit_le_connection_complete(hci_connection_t *conn, uint8_t status){
22624f3229d8S[email protected]     uint8_t event[21];
22634f3229d8S[email protected]     event[0] = HCI_EVENT_LE_META;
22644f3229d8S[email protected]     event[1] = sizeof(event) - 2;
22654f3229d8S[email protected]     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
22664f3229d8S[email protected]     event[3] = status;
22674f3229d8S[email protected]     bt_store_16(event, 4, conn->con_handle);
22684f3229d8S[email protected]     event[6] = 0; // TODO: role
22694f3229d8S[email protected]     event[7] = conn->address_type;
22704f3229d8S[email protected]     bt_flip_addr(&event[8], conn->address);
22714f3229d8S[email protected]     bt_store_16(event, 14, 0); // interval
22724f3229d8S[email protected]     bt_store_16(event, 16, 0); // latency
22734f3229d8S[email protected]     bt_store_16(event, 18, 0); // supervision timeout
22744f3229d8S[email protected]     event[20] = 0; // master clock accuracy
22754f3229d8S[email protected]     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
22764f3229d8S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
22774f3229d8S[email protected] }
22784f3229d8S[email protected] 
22793c4d4b90Smatthias.ringwald void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
2280425d1371Smatthias.ringwald     uint8_t event[6];
22813c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
2282e518c4b8Smatthias.ringwald     event[1] = sizeof(event) - 2;
22833c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
22843c4d4b90Smatthias.ringwald     bt_store_16(event, 3, handle);
22853c4d4b90Smatthias.ringwald     event[5] = reason;
2286425d1371Smatthias.ringwald     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
22873a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
22883c4d4b90Smatthias.ringwald }
22893c4d4b90Smatthias.ringwald 
2290ee091cf1Smatthias.ringwald void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
229166fb9560S[email protected]     if (disable_l2cap_timeouts) return;
2292e0abb8e7S[email protected]     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
2293425d1371Smatthias.ringwald     uint8_t event[4];
229480d52d6bSmatthias.ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
2295425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2296ee091cf1Smatthias.ringwald     bt_store_16(event, 2, conn->con_handle);
2297425d1371Smatthias.ringwald     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
22983a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2299ee091cf1Smatthias.ringwald }
230043bfb1bdSmatthias.ringwald 
230143bfb1bdSmatthias.ringwald void hci_emit_nr_connections_changed(){
2302e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
2303425d1371Smatthias.ringwald     uint8_t event[3];
230480d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
2305425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
230643bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
2307425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23083a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
230943bfb1bdSmatthias.ringwald }
2310038bc64cSmatthias.ringwald 
2311038bc64cSmatthias.ringwald void hci_emit_hci_open_failed(){
2312e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
2313425d1371Smatthias.ringwald     uint8_t event[2];
231480d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
2315425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2316425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23173a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2318038bc64cSmatthias.ringwald }
23191b0e3922Smatthias.ringwald 
232009ba8edeSmatthias.ringwald #ifndef EMBEDDED
23211b0e3922Smatthias.ringwald void hci_emit_btstack_version() {
2322e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
2323425d1371Smatthias.ringwald     uint8_t event[6];
23241b0e3922Smatthias.ringwald     event[0] = BTSTACK_EVENT_VERSION;
2325425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2326425d1371Smatthias.ringwald     event[2] = BTSTACK_MAJOR;
2327425d1371Smatthias.ringwald     event[3] = BTSTACK_MINOR;
2328425d1371Smatthias.ringwald     bt_store_16(event, 4, BTSTACK_REVISION);
2329425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23303a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
23311b0e3922Smatthias.ringwald }
233209ba8edeSmatthias.ringwald #endif
23331b0e3922Smatthias.ringwald 
23342ed6235cSmatthias.ringwald void hci_emit_system_bluetooth_enabled(uint8_t enabled){
2335e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
2336425d1371Smatthias.ringwald     uint8_t event[3];
23372ed6235cSmatthias.ringwald     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
2338425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
23392ed6235cSmatthias.ringwald     event[2] = enabled;
2340425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23413a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
23422ed6235cSmatthias.ringwald }
2343627c2f45Smatthias.ringwald 
2344627c2f45Smatthias.ringwald void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
2345e0abb8e7S[email protected]     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
2346627c2f45Smatthias.ringwald     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
2347e0abb8e7S[email protected]     event[1] = sizeof(event) - 2 - 1;
2348f653b6bdSmatthias.ringwald     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
23492f89d309Smatthias.ringwald     bt_flip_addr(&event[3], *addr);
2350f653b6bdSmatthias.ringwald     memcpy(&event[9], name, 248);
2351e0abb8e7S[email protected] 
2352e0abb8e7S[email protected]     event[9+248] = 0;   // assert \0 for log_info
2353e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2354e0abb8e7S[email protected] 
2355e0abb8e7S[email protected]     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
23563a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2357627c2f45Smatthias.ringwald }
2358381fbed8Smatthias.ringwald 
2359381fbed8Smatthias.ringwald void hci_emit_discoverable_enabled(uint8_t enabled){
2360e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2361425d1371Smatthias.ringwald     uint8_t event[3];
2362381fbed8Smatthias.ringwald     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2363425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2364381fbed8Smatthias.ringwald     event[2] = enabled;
2365425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23663a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2367381fbed8Smatthias.ringwald }
2368458bf4e8S[email protected] 
2369a00031e2S[email protected] void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2370df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2371a00031e2S[email protected]     uint8_t event[5];
2372e00caf9cS[email protected]     int pos = 0;
2373a00031e2S[email protected]     event[pos++] = GAP_SECURITY_LEVEL;
2374e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
2375a00031e2S[email protected]     bt_store_16(event, 2, con_handle);
2376e00caf9cS[email protected]     pos += 2;
2377e00caf9cS[email protected]     event[pos++] = level;
2378e00caf9cS[email protected]     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23793a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2380e00caf9cS[email protected] }
2381e00caf9cS[email protected] 
23821bd5283dS[email protected] void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
2383ad83dc6aS[email protected]     log_info("hci_emit_dedicated_bonding_result %u ", status);
2384ad83dc6aS[email protected]     uint8_t event[9];
2385ad83dc6aS[email protected]     int pos = 0;
2386ad83dc6aS[email protected]     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2387ad83dc6aS[email protected]     event[pos++] = sizeof(event) - 2;
2388ad83dc6aS[email protected]     event[pos++] = status;
23891bd5283dS[email protected]     bt_flip_addr( * (bd_addr_t *) &event[pos], address);
2390ad83dc6aS[email protected]     pos += 6;
2391ad83dc6aS[email protected]     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23923a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2393ad83dc6aS[email protected] }
2394ad83dc6aS[email protected] 
23952bd8b7e7S[email protected] // query if remote side supports SSP
23962bd8b7e7S[email protected] int hci_remote_ssp_supported(hci_con_handle_t con_handle){
23972bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
23982bd8b7e7S[email protected]     if (!connection) return 0;
23992bd8b7e7S[email protected]     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
24002bd8b7e7S[email protected] }
24012bd8b7e7S[email protected] 
2402df3354fcS[email protected] int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2403df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2404df3354fcS[email protected] }
2405df3354fcS[email protected] 
2406458bf4e8S[email protected] // GAP API
2407458bf4e8S[email protected] /**
2408458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
2409458bf4e8S[email protected]  * @praram enabled
2410458bf4e8S[email protected]  */
24114c57c146S[email protected] void gap_set_bondable_mode(int enable){
24123a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
2413458bf4e8S[email protected] }
2414cb230b9dS[email protected] 
2415cb230b9dS[email protected] /**
241634d2123cS[email protected]  * @brief map link keys to security levels
2417cb230b9dS[email protected]  */
241834d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
241934d2123cS[email protected]     switch (link_key_type){
24203c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
24213c68dfa9S[email protected]             return LEVEL_4;
24223c68dfa9S[email protected]         case COMBINATION_KEY:
24233c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
24243c68dfa9S[email protected]             return LEVEL_3;
24253c68dfa9S[email protected]         default:
24263c68dfa9S[email protected]             return LEVEL_2;
24273c68dfa9S[email protected]     }
2428cb230b9dS[email protected] }
2429cb230b9dS[email protected] 
2430a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
243134d2123cS[email protected]     if (!connection) return LEVEL_0;
243234d2123cS[email protected]     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
243334d2123cS[email protected]     return gap_security_level_for_link_key_type(connection->link_key_type);
243434d2123cS[email protected] }
243534d2123cS[email protected] 
243634d2123cS[email protected] 
2437106d6d11S[email protected] int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
24385127cc62S[email protected]     log_info("gap_mitm_protection_required_for_security_level %u", level);
2439106d6d11S[email protected]     return level > LEVEL_2;
2440106d6d11S[email protected] }
2441106d6d11S[email protected] 
244234d2123cS[email protected] /**
244334d2123cS[email protected]  * @brief get current security level
244434d2123cS[email protected]  */
244534d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
244634d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
244734d2123cS[email protected]     if (!connection) return LEVEL_0;
244834d2123cS[email protected]     return gap_security_level_for_connection(connection);
244934d2123cS[email protected] }
245034d2123cS[email protected] 
2451cb230b9dS[email protected] /**
2452cb230b9dS[email protected]  * @brief request connection to device to
2453cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
2454cb230b9dS[email protected]  */
245534d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
245634d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
245734d2123cS[email protected]     if (!connection){
2458a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
245934d2123cS[email protected]         return;
246034d2123cS[email protected]     }
246134d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
246234d2123cS[email protected]     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
246334d2123cS[email protected]     if (current_level >= requested_level){
2464a00031e2S[email protected]         hci_emit_security_level(con_handle, current_level);
246534d2123cS[email protected]         return;
246634d2123cS[email protected]     }
2467a00031e2S[email protected] 
246834d2123cS[email protected]     connection->requested_security_level = requested_level;
2469a00031e2S[email protected] 
2470fb8ba0dbS[email protected]     // would enabling ecnryption suffice (>= LEVEL_2)?
24713a9fb326S[email protected]     if (hci_stack->remote_device_db){
2472a00031e2S[email protected]         link_key_type_t link_key_type;
2473a00031e2S[email protected]         link_key_t      link_key;
24743a9fb326S[email protected]         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2475a00031e2S[email protected]             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2476a00031e2S[email protected]                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2477a00031e2S[email protected]                 return;
2478a00031e2S[email protected]             }
2479a00031e2S[email protected]         }
2480a00031e2S[email protected]     }
2481a00031e2S[email protected] 
24821eb2563eS[email protected]     // try to authenticate connection
24831eb2563eS[email protected]     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2484e80b2cf9S[email protected]     hci_run();
2485e00caf9cS[email protected] }
2486ad83dc6aS[email protected] 
2487ad83dc6aS[email protected] /**
2488ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
2489ad83dc6aS[email protected]  * @param device
2490ad83dc6aS[email protected]  * @param request MITM protection
2491ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
2492ad83dc6aS[email protected]  */
2493ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2494ad83dc6aS[email protected] 
2495ad83dc6aS[email protected]     // create connection state machine
249696a45072S[email protected]     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2497ad83dc6aS[email protected] 
2498ad83dc6aS[email protected]     if (!connection){
2499ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
2500ad83dc6aS[email protected]     }
2501ad83dc6aS[email protected] 
2502ad83dc6aS[email protected]     // delete linkn key
2503ad83dc6aS[email protected]     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2504ad83dc6aS[email protected] 
2505ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
2506ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
2507ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
25085127cc62S[email protected]     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
2509ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
2510ad83dc6aS[email protected] 
2511ad83dc6aS[email protected]     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2512ad83dc6aS[email protected] 
2513ad83dc6aS[email protected]     // handle: connnection failure (connection complete != ok)
2514ad83dc6aS[email protected]     // handle: authentication failure
2515ad83dc6aS[email protected]     // handle: disconnect on done
2516ad83dc6aS[email protected] 
2517ad83dc6aS[email protected]     hci_run();
2518ad83dc6aS[email protected] 
2519ad83dc6aS[email protected]     return 0;
2520ad83dc6aS[email protected] }
25218e618f72S[email protected] 
25228e618f72S[email protected] void gap_set_local_name(const char * local_name){
25238e618f72S[email protected]     hci_stack->local_name = local_name;
25248e618f72S[email protected] }
25258e618f72S[email protected] 
25267bdc6798S[email protected] le_command_status_t le_central_start_scan(){
252736af3e18S[email protected]     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
25287bdc6798S[email protected]     hci_stack->le_scanning_state = LE_START_SCAN;
25297bdc6798S[email protected]     hci_run();
25307bdc6798S[email protected]     return BLE_PERIPHERAL_OK;
25317bdc6798S[email protected] }
25328e618f72S[email protected] 
25337bdc6798S[email protected] le_command_status_t le_central_stop_scan(){
253436af3e18S[email protected]     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
25357bdc6798S[email protected]     hci_stack->le_scanning_state = LE_STOP_SCAN;
25367bdc6798S[email protected]     hci_run();
25377bdc6798S[email protected]     return BLE_PERIPHERAL_OK;
25387bdc6798S[email protected] }
25394f3229d8S[email protected] 
2540ef11999fSmatthias.ringwald void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
2541ef11999fSmatthias.ringwald     hci_stack->le_scan_type     = scan_type;
2542ef11999fSmatthias.ringwald     hci_stack->le_scan_interval = scan_interval;
2543ef11999fSmatthias.ringwald     hci_stack->le_scan_window   = scan_window;
2544ef11999fSmatthias.ringwald     hci_run();
2545ef11999fSmatthias.ringwald }
25464f3229d8S[email protected] 
25474f3229d8S[email protected] le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
25484f3229d8S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
25494f3229d8S[email protected]     if (!conn){
25501f479f8cS[email protected]         log_info("le_central_connect: no connection exists yet, creating context");
25514f3229d8S[email protected]         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
25524f3229d8S[email protected]         if (!conn){
25534f3229d8S[email protected]             // notify client that alloc failed
25544f3229d8S[email protected]             hci_emit_le_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
25551f479f8cS[email protected]             log_info("le_central_connect: failed to alloc context");
25564f3229d8S[email protected]             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
25574f3229d8S[email protected]         }
25584f3229d8S[email protected]         conn->state = SEND_CREATE_CONNECTION;
25591f479f8cS[email protected]         log_info("le_central_connect: send create connection next");
2560564fca32S[email protected]         hci_run();
25614f3229d8S[email protected]         return BLE_PERIPHERAL_OK;
25624f3229d8S[email protected]     }
25630bf6344aS[email protected] 
25640bf6344aS[email protected]     if (!hci_is_le_connection(conn) ||
25650bf6344aS[email protected]         conn->state == SEND_CREATE_CONNECTION ||
25660bf6344aS[email protected]         conn->state == SENT_CREATE_CONNECTION) {
25670bf6344aS[email protected]         hci_emit_le_connection_complete(conn, ERROR_CODE_COMMAND_DISALLOWED);
25681f479f8cS[email protected]         log_error("le_central_connect: classic connection or connect is already being created");
25690bf6344aS[email protected]         return BLE_PERIPHERAL_IN_WRONG_STATE;
25700bf6344aS[email protected]     }
25710bf6344aS[email protected] 
25721f479f8cS[email protected]     log_info("le_central_connect: context exists with state %u", conn->state);
25734f3229d8S[email protected]     hci_emit_le_connection_complete(conn, 0);
25744f3229d8S[email protected]     hci_run();
25754f3229d8S[email protected]     return BLE_PERIPHERAL_OK;
25764f3229d8S[email protected] }
25774f3229d8S[email protected] 
25787851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
25797851196eSmatthias.ringwald static hci_connection_t * le_central_get_outgoing_connection(){
25800bf6344aS[email protected]     linked_item_t *it;
25810bf6344aS[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
25820bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
25830bf6344aS[email protected]         if (!hci_is_le_connection(conn)) continue;
25840bf6344aS[email protected]         switch (conn->state){
2585a6725849S[email protected]             case SEND_CREATE_CONNECTION:
25867851196eSmatthias.ringwald             case SENT_CREATE_CONNECTION:
25877851196eSmatthias.ringwald                 return conn;
25887851196eSmatthias.ringwald             default:
25897851196eSmatthias.ringwald                 break;
25907851196eSmatthias.ringwald         };
25917851196eSmatthias.ringwald     }
25927851196eSmatthias.ringwald     return NULL;
25937851196eSmatthias.ringwald }
25947851196eSmatthias.ringwald 
25957851196eSmatthias.ringwald le_command_status_t le_central_connect_cancel(){
25967851196eSmatthias.ringwald     hci_connection_t * conn = le_central_get_outgoing_connection();
25977851196eSmatthias.ringwald     switch (conn->state){
25987851196eSmatthias.ringwald         case SEND_CREATE_CONNECTION:
25997851196eSmatthias.ringwald             // skip sending create connection and emit event instead
26000bf6344aS[email protected]             hci_emit_le_connection_complete(conn, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
26017851196eSmatthias.ringwald             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
26027851196eSmatthias.ringwald             btstack_memory_hci_connection_free( conn );
26030bf6344aS[email protected]             break;
2604a6725849S[email protected]         case SENT_CREATE_CONNECTION:
26057851196eSmatthias.ringwald             // request to send cancel connection
26060bf6344aS[email protected]             conn->state = SEND_CANCEL_CONNECTION;
26070bf6344aS[email protected]             hci_run();
26080bf6344aS[email protected]             break;
26090bf6344aS[email protected]         default:
26100bf6344aS[email protected]             break;
26110bf6344aS[email protected]     }
2612e31f89a7S[email protected]     return BLE_PERIPHERAL_OK;
2613e31f89a7S[email protected] }
26144f3229d8S[email protected] 
2615c37a3166S[email protected] /**
2616c37a3166S[email protected]  * @brief Updates the connection parameters for a given LE connection
2617c37a3166S[email protected]  * @param handle
2618c37a3166S[email protected]  * @param conn_interval_min (unit: 1.25ms)
2619c37a3166S[email protected]  * @param conn_interval_max (unit: 1.25ms)
2620c37a3166S[email protected]  * @param conn_latency
2621c37a3166S[email protected]  * @param supervision_timeout (unit: 10ms)
2622c37a3166S[email protected]  * @returns 0 if ok
2623c37a3166S[email protected]  */
2624c37a3166S[email protected] int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
2625c37a3166S[email protected]     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
2626c37a3166S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2627c37a3166S[email protected]     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2628c37a3166S[email protected]     connection->le_conn_interval_min = conn_interval_min;
2629c37a3166S[email protected]     connection->le_conn_interval_max = conn_interval_max;
2630c37a3166S[email protected]     connection->le_conn_latency = conn_latency;
2631c37a3166S[email protected]     connection->le_supervision_timeout = supervision_timeout;
2632c37a3166S[email protected]     return 0;
2633c37a3166S[email protected] }
2634c37a3166S[email protected] 
26355917a5c5S[email protected] le_command_status_t gap_disconnect(hci_con_handle_t handle){
26365917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
26375917a5c5S[email protected]     if (!conn){
26387851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
26395917a5c5S[email protected]         return BLE_PERIPHERAL_OK;
26405917a5c5S[email protected]     }
26415917a5c5S[email protected]     conn->state = SEND_DISCONNECT;
26425917a5c5S[email protected]     hci_run();
26434f3229d8S[email protected]     return BLE_PERIPHERAL_OK;
26444f3229d8S[email protected] }
264504a6ef8cSmatthias.ringwald 
264604a6ef8cSmatthias.ringwald void hci_disconnect_all(){
264704a6ef8cSmatthias.ringwald     linked_list_iterator_t it;
264804a6ef8cSmatthias.ringwald     linked_list_iterator_init(&it, &hci_stack->connections);
264904a6ef8cSmatthias.ringwald     while (linked_list_iterator_has_next(&it)){
265004a6ef8cSmatthias.ringwald         hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it);
265104a6ef8cSmatthias.ringwald         if (con->state == SENT_DISCONNECT) continue;
265204a6ef8cSmatthias.ringwald         con->state = SEND_DISCONNECT;
265304a6ef8cSmatthias.ringwald     }
2654d31fba26S[email protected]     hci_run();
265504a6ef8cSmatthias.ringwald }
2656