xref: /btstack/src/hci.c (revision bc01039d264b9db91da01e9eb60129821f891c86)
11f504dbdSmatthias.ringwald /*
2a0c35809S[email protected]  * Copyright (C) 2014 BlueKitchen GmbH
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  *
20a0c35809S[email protected]  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH 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  *
33a0c35809S[email protected]  * Please inquire about commercial licensing options at
34a0c35809S[email protected]  * [email protected]
356b64433eSmatthias.ringwald  *
361713bceaSmatthias.ringwald  */
371713bceaSmatthias.ringwald 
381713bceaSmatthias.ringwald /*
391f504dbdSmatthias.ringwald  *  hci.c
401f504dbdSmatthias.ringwald  *
411f504dbdSmatthias.ringwald  *  Created by Matthias Ringwald on 4/29/09.
421f504dbdSmatthias.ringwald  *
431f504dbdSmatthias.ringwald  */
441f504dbdSmatthias.ringwald 
45bde315ceS[email protected] #include "btstack-config.h"
4628171530Smatthias.ringwald 
477f2435e6Smatthias.ringwald #include "hci.h"
484c57c146S[email protected] #include "gap.h"
497f2435e6Smatthias.ringwald 
5093b8dc03Smatthias.ringwald #include <stdarg.h>
5193b8dc03Smatthias.ringwald #include <string.h>
5256fe0872Smatthias.ringwald #include <stdio.h>
537f2435e6Smatthias.ringwald 
54549e6ebeSmatthias.ringwald #ifndef EMBEDDED
55fe475138S[email protected] #ifdef _WIN32
56fe475138S[email protected] #include "Winsock2.h"
57fe475138S[email protected] #else
58549e6ebeSmatthias.ringwald #include <unistd.h> // gethostbyname
59fe475138S[email protected] #endif
6009ba8edeSmatthias.ringwald #include <btstack/version.h>
61549e6ebeSmatthias.ringwald #endif
62549e6ebeSmatthias.ringwald 
63a3b02b71Smatthias.ringwald #include "btstack_memory.h"
647f2435e6Smatthias.ringwald #include "debug.h"
65d8905019Smatthias.ringwald #include "hci_dump.h"
6693b8dc03Smatthias.ringwald 
67da886c03S[email protected] #include <btstack/linked_list.h>
68ae1fd9f3Smatthias.ringwald #include <btstack/hci_cmds.h>
691b0e3922Smatthias.ringwald 
70169f8b28Smatthias.ringwald #define HCI_CONNECTION_TIMEOUT_MS 10000
71ee091cf1Smatthias.ringwald 
72a45d6b9fS[email protected] #define HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP 11
73da5275c5S[email protected] 
7428171530Smatthias.ringwald #ifdef USE_BLUETOOL
753d7a3f67S[email protected] #include "../platforms/ios/src/bt_control_iphone.h"
7628171530Smatthias.ringwald #endif
7728171530Smatthias.ringwald 
78758b46ceSmatthias.ringwald static void hci_update_scan_enable(void);
79a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
8096a45072S[email protected] static void hci_connection_timeout_handler(timer_source_t *timer);
8196a45072S[email protected] static void hci_connection_timestamp(hci_connection_t *connection);
827586ee35S[email protected] static int  hci_power_control_on(void);
837586ee35S[email protected] static void hci_power_control_off(void);
846155b3d3S[email protected] static void hci_state_reset();
85758b46ceSmatthias.ringwald 
8606b35ec0Smatthias.ringwald // the STACK is here
873a9fb326S[email protected] #ifndef HAVE_MALLOC
883a9fb326S[email protected] static hci_stack_t   hci_stack_static;
893a9fb326S[email protected] #endif
903a9fb326S[email protected] static hci_stack_t * hci_stack = NULL;
9116833f0aSmatthias.ringwald 
9266fb9560S[email protected] // test helper
9366fb9560S[email protected] static uint8_t disable_l2cap_timeouts = 0;
9466fb9560S[email protected] 
9596a45072S[email protected] /**
9696a45072S[email protected]  * create connection for given address
9796a45072S[email protected]  *
9896a45072S[email protected]  * @return connection OR NULL, if no memory left
9996a45072S[email protected]  */
10096a45072S[email protected] static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
1015127cc62S[email protected]     log_info("create_connection_for_addr %s", bd_addr_to_str(addr));
102bb69aaaeS[email protected]     hci_connection_t * conn = btstack_memory_hci_connection_get();
10396a45072S[email protected]     if (!conn) return NULL;
10496a45072S[email protected]     BD_ADDR_COPY(conn->address, addr);
10596a45072S[email protected]     conn->address_type = addr_type;
10696a45072S[email protected]     conn->con_handle = 0xffff;
10796a45072S[email protected]     conn->authentication_flags = AUTH_FLAGS_NONE;
10896a45072S[email protected]     conn->bonding_flags = 0;
10996a45072S[email protected]     conn->requested_security_level = LEVEL_0;
11096a45072S[email protected]     linked_item_set_user(&conn->timeout.item, conn);
11196a45072S[email protected]     conn->timeout.process = hci_connection_timeout_handler;
11296a45072S[email protected]     hci_connection_timestamp(conn);
11396a45072S[email protected]     conn->acl_recombination_length = 0;
11496a45072S[email protected]     conn->acl_recombination_pos = 0;
11596a45072S[email protected]     conn->num_acl_packets_sent = 0;
116da886c03S[email protected]     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
11796a45072S[email protected]     linked_list_add(&hci_stack->connections, (linked_item_t *) conn);
11896a45072S[email protected]     return conn;
11996a45072S[email protected] }
12066fb9560S[email protected] 
121da886c03S[email protected] 
122da886c03S[email protected] /**
123da886c03S[email protected]  * get le connection parameter range
124da886c03S[email protected] *
125da886c03S[email protected]  * @return le connection parameter range struct
126da886c03S[email protected]  */
127da886c03S[email protected] le_connection_parameter_range_t gap_le_get_connection_parameter_range(){
128da886c03S[email protected]     return hci_stack->le_connection_parameter_range;
129da886c03S[email protected] }
130da886c03S[email protected] 
131da886c03S[email protected] /**
132da886c03S[email protected]  * set le connection parameter range
133da886c03S[email protected]  *
134da886c03S[email protected]  */
135da886c03S[email protected] 
136da886c03S[email protected] void gap_le_set_connection_parameter_range(le_connection_parameter_range_t range){
137da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_interval_min = range.le_conn_interval_min;
138da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_interval_max = range.le_conn_interval_max;
139da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_interval_min = range.le_conn_latency_min;
140da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_interval_max = range.le_conn_latency_max;
141da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = range.le_supervision_timeout_min;
142da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = range.le_supervision_timeout_max;
143da886c03S[email protected] }
144da886c03S[email protected] 
145da886c03S[email protected] /**
146da886c03S[email protected]  * get hci connections iterator
147da886c03S[email protected]  *
148da886c03S[email protected]  * @return hci connections iterator
149da886c03S[email protected]  */
150da886c03S[email protected] 
151da886c03S[email protected] void hci_connections_get_iterator(linked_list_iterator_t *it){
152da886c03S[email protected]     linked_list_iterator_init(it, &hci_stack->connections);
153da886c03S[email protected] }
154da886c03S[email protected] 
15597addcc5Smatthias.ringwald /**
156ee091cf1Smatthias.ringwald  * get connection for a given handle
157ee091cf1Smatthias.ringwald  *
158ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
159ee091cf1Smatthias.ringwald  */
1605061f3afS[email protected] hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
161da886c03S[email protected]     linked_list_iterator_t it;
162da886c03S[email protected]     linked_list_iterator_init(&it, &hci_stack->connections);
163da886c03S[email protected]     while (linked_list_iterator_has_next(&it)){
164da886c03S[email protected]         hci_connection_t * item = (hci_connection_t *) linked_list_iterator_next(&it);
1653ac2fe56S[email protected]         if ( item->con_handle == con_handle ) {
166da886c03S[email protected]             return item;
167ee091cf1Smatthias.ringwald         }
168ee091cf1Smatthias.ringwald     }
169ee091cf1Smatthias.ringwald     return NULL;
170ee091cf1Smatthias.ringwald }
171ee091cf1Smatthias.ringwald 
17296a45072S[email protected] /**
17396a45072S[email protected]  * get connection for given address
17496a45072S[email protected]  *
17596a45072S[email protected]  * @return connection OR NULL, if not found
17696a45072S[email protected]  */
17796a45072S[email protected] hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t * addr, bd_addr_type_t addr_type){
178da886c03S[email protected]     linked_list_iterator_t it;
179da886c03S[email protected]     linked_list_iterator_init(&it, &hci_stack->connections);
180da886c03S[email protected]     while (linked_list_iterator_has_next(&it)){
181da886c03S[email protected]         hci_connection_t * connection = (hci_connection_t *) linked_list_iterator_next(&it);
18296a45072S[email protected]         if (connection->address_type != addr_type)  continue;
18396a45072S[email protected]         if (memcmp(addr, connection->address, 6) != 0) continue;
18462bda3fbS[email protected]         return connection;
18562bda3fbS[email protected]     }
18662bda3fbS[email protected]     return NULL;
18762bda3fbS[email protected] }
18862bda3fbS[email protected] 
1892b12a0b9Smatthias.ringwald static void hci_connection_timeout_handler(timer_source_t *timer){
19028ca2b46S[email protected]     hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item);
191c785ef68Smatthias.ringwald #ifdef HAVE_TIME
192ee091cf1Smatthias.ringwald     struct timeval tv;
193ee091cf1Smatthias.ringwald     gettimeofday(&tv, NULL);
194c21e6239Smatthias.ringwald     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
195ee091cf1Smatthias.ringwald         // connections might be timed out
196ee091cf1Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
197ee091cf1Smatthias.ringwald     }
1982b12a0b9Smatthias.ringwald #endif
199e5780900Smatthias.ringwald #ifdef HAVE_TICK
200c785ef68Smatthias.ringwald     if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
201c785ef68Smatthias.ringwald         // connections might be timed out
202c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
203c785ef68Smatthias.ringwald     }
204c785ef68Smatthias.ringwald #endif
205c785ef68Smatthias.ringwald     run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
206c785ef68Smatthias.ringwald     run_loop_add_timer(timer);
207c785ef68Smatthias.ringwald }
208ee091cf1Smatthias.ringwald 
209ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
210c7492964Smatthias.ringwald #ifdef HAVE_TIME
211ee091cf1Smatthias.ringwald     gettimeofday(&connection->timestamp, NULL);
212c7492964Smatthias.ringwald #endif
213e5780900Smatthias.ringwald #ifdef HAVE_TICK
214c785ef68Smatthias.ringwald     connection->timestamp = embedded_get_ticks();
215c785ef68Smatthias.ringwald #endif
216ee091cf1Smatthias.ringwald }
217ee091cf1Smatthias.ringwald 
21806b35ec0Smatthias.ringwald 
21928ca2b46S[email protected] inline static void connectionSetAuthenticationFlags(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] inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
22428ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
22528ca2b46S[email protected] }
22628ca2b46S[email protected] 
22728ca2b46S[email protected] 
22843bfb1bdSmatthias.ringwald /**
22980ca58a0Smatthias.ringwald  * add authentication flags and reset timer
23096a45072S[email protected]  * @note: assumes classic connection
2317fde4af9Smatthias.ringwald  */
2327fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
2337fde4af9Smatthias.ringwald     bd_addr_t addr;
2347fde4af9Smatthias.ringwald     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
23596a45072S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2367fde4af9Smatthias.ringwald     if (conn) {
23728ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
23880ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
2397fde4af9Smatthias.ringwald     }
2407fde4af9Smatthias.ringwald }
2417fde4af9Smatthias.ringwald 
24280ca58a0Smatthias.ringwald int  hci_authentication_active_for_handle(hci_con_handle_t handle){
2435061f3afS[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
24480ca58a0Smatthias.ringwald     if (!conn) return 0;
2456724cd9eS[email protected]     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
2466724cd9eS[email protected]     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
2476724cd9eS[email protected]     return 0;
24880ca58a0Smatthias.ringwald }
24980ca58a0Smatthias.ringwald 
250c12e46e7Smatthias.ringwald void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
2513a9fb326S[email protected]     if (hci_stack->remote_device_db) {
2523a9fb326S[email protected]         hci_stack->remote_device_db->delete_link_key(addr);
253c12e46e7Smatthias.ringwald     }
254c12e46e7Smatthias.ringwald }
255c12e46e7Smatthias.ringwald 
2560bf6344aS[email protected] int hci_is_le_connection(hci_connection_t * connection){
2570bf6344aS[email protected]     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
2580bf6344aS[email protected]     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
2590bf6344aS[email protected] }
2600bf6344aS[email protected] 
2617fde4af9Smatthias.ringwald 
2627fde4af9Smatthias.ringwald /**
26343bfb1bdSmatthias.ringwald  * count connections
26443bfb1bdSmatthias.ringwald  */
26540d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
26656c253c9Smatthias.ringwald     int count = 0;
26743bfb1bdSmatthias.ringwald     linked_item_t *it;
2683a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
26943bfb1bdSmatthias.ringwald     return count;
27043bfb1bdSmatthias.ringwald }
271c8e4258aSmatthias.ringwald 
27297addcc5Smatthias.ringwald /**
273ba681a6cSmatthias.ringwald  * Dummy handler called by HCI
27416833f0aSmatthias.ringwald  */
2752718e2e7Smatthias.ringwald static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
27616833f0aSmatthias.ringwald }
27716833f0aSmatthias.ringwald 
278998906cdSmatthias.ringwald uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
2795061f3afS[email protected]     hci_connection_t * connection = hci_connection_for_handle(handle);
280998906cdSmatthias.ringwald     if (!connection) {
2819da54300S[email protected]         log_error("hci_number_outgoing_packets: connection for handle %u does not exist!", handle);
282998906cdSmatthias.ringwald         return 0;
283998906cdSmatthias.ringwald     }
284998906cdSmatthias.ringwald     return connection->num_acl_packets_sent;
285998906cdSmatthias.ringwald }
286998906cdSmatthias.ringwald 
287e79abdd6S[email protected] uint8_t hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
288ee303eddS[email protected] 
289ee303eddS[email protected]     int num_packets_sent_classic = 0;
290ee303eddS[email protected]     int num_packets_sent_le = 0;
291ee303eddS[email protected] 
292ee303eddS[email protected]     bd_addr_type_t address_type = BD_ADDR_TYPE_UNKNOWN;
293ee303eddS[email protected] 
294998906cdSmatthias.ringwald     linked_item_t *it;
2953a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
296998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
297ee303eddS[email protected]         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
298ee303eddS[email protected]             num_packets_sent_classic += connection->num_acl_packets_sent;
299ee303eddS[email protected]         } else {
300ee303eddS[email protected]             num_packets_sent_le += connection->num_acl_packets_sent;
301ee303eddS[email protected]         }
302ccda6e14S[email protected]         // ignore connections that are not open, e.g., in state RECEIVED_DISCONNECTION_COMPLETE
303ccda6e14S[email protected]         if (connection->con_handle == con_handle && connection->state == OPEN){
304ee303eddS[email protected]             address_type = connection->address_type;
305ee303eddS[email protected]         }
306ee303eddS[email protected]     }
307ee303eddS[email protected] 
308ee303eddS[email protected]     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
309ee303eddS[email protected]     int free_slots_le = 0;
310ee303eddS[email protected] 
311ee303eddS[email protected]     if (free_slots_classic < 0){
3129da54300S[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);
313998906cdSmatthias.ringwald         return 0;
314998906cdSmatthias.ringwald     }
315ee303eddS[email protected] 
316ee303eddS[email protected]     if (hci_stack->le_acl_packets_total_num){
317ee303eddS[email protected]         // if we have LE slots, they are used
318ee303eddS[email protected]         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
319ee303eddS[email protected]         if (free_slots_le < 0){
3209da54300S[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);
321ee303eddS[email protected]             return 0;
322998906cdSmatthias.ringwald         }
323ee303eddS[email protected]     } else {
324ee303eddS[email protected]         // otherwise, classic slots are used for LE, too
325ee303eddS[email protected]         free_slots_classic -= num_packets_sent_le;
326ee303eddS[email protected]         if (free_slots_classic < 0){
3279da54300S[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);
328ee303eddS[email protected]             return 0;
329ee303eddS[email protected]         }
330ee303eddS[email protected]     }
331ee303eddS[email protected] 
332ee303eddS[email protected]     switch (address_type){
333ee303eddS[email protected]         case BD_ADDR_TYPE_UNKNOWN:
3349da54300S[email protected]             log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
335ee303eddS[email protected]             return 0;
336ee303eddS[email protected] 
337ee303eddS[email protected]         case BD_ADDR_TYPE_CLASSIC:
338ee303eddS[email protected]             return free_slots_classic;
339ee303eddS[email protected] 
340ee303eddS[email protected]         default:
341cb00d3aaS[email protected]            if (hci_stack->le_acl_packets_total_num){
342ee303eddS[email protected]                return free_slots_le;
343ee303eddS[email protected]            }
344cb00d3aaS[email protected]            return free_slots_classic;
345cb00d3aaS[email protected]     }
346998906cdSmatthias.ringwald }
347998906cdSmatthias.ringwald 
348ac928cc2S[email protected] // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
349ac928cc2S[email protected] int hci_can_send_command_packet_now(void){
350ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
351ac928cc2S[email protected] 
352ac928cc2S[email protected]     // check for async hci transport implementations
353ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
354ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
355ac928cc2S[email protected]             return 0;
356ac928cc2S[email protected]         }
357ac928cc2S[email protected]     }
358ac928cc2S[email protected] 
359ac928cc2S[email protected]     return hci_stack->num_cmd_packets > 0;
360ac928cc2S[email protected] }
361ac928cc2S[email protected] 
362ac928cc2S[email protected] int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
363ac928cc2S[email protected]     // check for async hci transport implementations
364ac928cc2S[email protected]     if (hci_stack->hci_transport->can_send_packet_now){
365ac928cc2S[email protected]         if (!hci_stack->hci_transport->can_send_packet_now(HCI_ACL_DATA_PACKET)){
366ac928cc2S[email protected]             return 0;
367ac928cc2S[email protected]         }
368ac928cc2S[email protected]     }
369e79abdd6S[email protected]     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
370ac928cc2S[email protected] }
371ac928cc2S[email protected] 
372ac928cc2S[email protected] int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
373ac928cc2S[email protected]     if (hci_stack->hci_packet_buffer_reserved) return 0;
374ac928cc2S[email protected]     return hci_can_send_prepared_acl_packet_now(con_handle);
3756b4af23dS[email protected] }
3766b4af23dS[email protected] 
377c8b9416aS[email protected] // used for internal checks in l2cap[-le].c
378c8b9416aS[email protected] int hci_is_packet_buffer_reserved(void){
379c8b9416aS[email protected]     return hci_stack->hci_packet_buffer_reserved;
380c8b9416aS[email protected] }
381c8b9416aS[email protected] 
3826b4af23dS[email protected] // reserves outgoing packet buffer. @returns 1 if successful
3836b4af23dS[email protected] int hci_reserve_packet_buffer(void){
3849d14b626S[email protected]     if (hci_stack->hci_packet_buffer_reserved) {
3859d14b626S[email protected]         log_error("hci_reserve_packet_buffer called but buffer already reserved");
3869d14b626S[email protected]         return 0;
3879d14b626S[email protected]     }
3886b4af23dS[email protected]     hci_stack->hci_packet_buffer_reserved = 1;
3896b4af23dS[email protected]     return 1;
3906b4af23dS[email protected] }
3916b4af23dS[email protected] 
39268a0fcf7S[email protected] void hci_release_packet_buffer(void){
39368a0fcf7S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
39468a0fcf7S[email protected] }
39568a0fcf7S[email protected] 
3966b4af23dS[email protected] // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
3976b4af23dS[email protected] int hci_transport_synchronous(void){
3986b4af23dS[email protected]     return hci_stack->hci_transport->can_send_packet_now == NULL;
3996b4af23dS[email protected] }
4006b4af23dS[email protected] 
4016c26b087S[email protected] uint16_t hci_max_acl_le_data_packet_length(void){
4026c26b087S[email protected]     return hci_stack->le_data_packets_length > 0 ? hci_stack->le_data_packets_length : hci_stack->acl_data_packet_length;
4036c26b087S[email protected] }
4046c26b087S[email protected] 
405452cf3bbS[email protected] static int hci_send_acl_packet_fragments(hci_connection_t *connection){
406452cf3bbS[email protected] 
407452cf3bbS[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);
408452cf3bbS[email protected] 
409452cf3bbS[email protected]     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
410452cf3bbS[email protected]     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
411452cf3bbS[email protected]     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
412452cf3bbS[email protected]         max_acl_data_packet_length = hci_stack->le_data_packets_length;
413452cf3bbS[email protected]     }
414452cf3bbS[email protected] 
415452cf3bbS[email protected]     // testing: reduce buffer to minimum
416452cf3bbS[email protected]     // max_acl_data_packet_length = 52;
417452cf3bbS[email protected] 
418452cf3bbS[email protected]     int err;
419452cf3bbS[email protected]     // multiple packets could be send on a synchronous HCI transport
420452cf3bbS[email protected]     while (1){
421452cf3bbS[email protected] 
422452cf3bbS[email protected]         // get current data
423452cf3bbS[email protected]         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
424452cf3bbS[email protected]         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
425452cf3bbS[email protected]         int more_fragments = 0;
426452cf3bbS[email protected] 
427452cf3bbS[email protected]         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
428452cf3bbS[email protected]         if (current_acl_data_packet_length > max_acl_data_packet_length){
429452cf3bbS[email protected]             more_fragments = 1;
430452cf3bbS[email protected]             current_acl_data_packet_length = max_acl_data_packet_length;
431452cf3bbS[email protected]         }
432452cf3bbS[email protected] 
433452cf3bbS[email protected]         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
434452cf3bbS[email protected]         if (acl_header_pos > 0){
435452cf3bbS[email protected]             uint16_t handle_and_flags = READ_BT_16(hci_stack->hci_packet_buffer, 0);
436452cf3bbS[email protected]             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
437452cf3bbS[email protected]             bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
438452cf3bbS[email protected]         }
439452cf3bbS[email protected] 
440452cf3bbS[email protected]         // update header len
441452cf3bbS[email protected]         bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
442452cf3bbS[email protected] 
443452cf3bbS[email protected]         // count packet
444452cf3bbS[email protected]         connection->num_acl_packets_sent++;
445452cf3bbS[email protected] 
446452cf3bbS[email protected]         // send packet
447452cf3bbS[email protected]         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
448452cf3bbS[email protected]         const int size = current_acl_data_packet_length + 4;
4495bb5bc3eS[email protected]         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
450452cf3bbS[email protected]         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
451452cf3bbS[email protected] 
452452cf3bbS[email protected]         // done yet?
453452cf3bbS[email protected]         if (!more_fragments) break;
454452cf3bbS[email protected] 
455452cf3bbS[email protected]         // update start of next fragment to send
456452cf3bbS[email protected]         hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
457452cf3bbS[email protected] 
458452cf3bbS[email protected]         // can send more?
459452cf3bbS[email protected]         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
460452cf3bbS[email protected]     }
461452cf3bbS[email protected] 
462452cf3bbS[email protected]     // done
463452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 0;
464452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = 0;
465452cf3bbS[email protected] 
466d051460cS[email protected]     // release buffer now for synchronous transport
467203bace6S[email protected]     if (hci_transport_synchronous()){
468452cf3bbS[email protected]         hci_release_packet_buffer();
469452cf3bbS[email protected]     }
470452cf3bbS[email protected] 
471452cf3bbS[email protected]     return err;
472452cf3bbS[email protected] }
473452cf3bbS[email protected] 
474826f7347S[email protected] // pre: caller has reserved the packet buffer
475826f7347S[email protected] int hci_send_acl_packet_buffer(int size){
4767856c818Smatthias.ringwald 
477452cf3bbS[email protected]     // log_info("hci_send_acl_packet_buffer size %u", size);
478452cf3bbS[email protected] 
479826f7347S[email protected]     if (!hci_stack->hci_packet_buffer_reserved) {
480826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
481826f7347S[email protected]         return 0;
482826f7347S[email protected]     }
483826f7347S[email protected] 
484d713a683S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
485d713a683S[email protected]     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
486d713a683S[email protected] 
487826f7347S[email protected]     // check for free places on Bluetooth module
488d713a683S[email protected]     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
489826f7347S[email protected]         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
49097b61c7bS[email protected]         hci_release_packet_buffer();
49197b61c7bS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
49297b61c7bS[email protected]     }
4936218e6f1Smatthias.ringwald 
4945061f3afS[email protected]     hci_connection_t *connection = hci_connection_for_handle( con_handle);
49597b61c7bS[email protected]     if (!connection) {
4965fa0b7cfS[email protected]         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
49797b61c7bS[email protected]         hci_release_packet_buffer();
49897b61c7bS[email protected]         return 0;
49997b61c7bS[email protected]     }
50056cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
50156cf178bSmatthias.ringwald 
502452cf3bbS[email protected]     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
5037856c818Smatthias.ringwald 
504452cf3bbS[email protected]     // setup data
505452cf3bbS[email protected]     hci_stack->acl_fragmentation_total_size = size;
506452cf3bbS[email protected]     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
5076218e6f1Smatthias.ringwald 
508452cf3bbS[email protected]     return hci_send_acl_packet_fragments(connection);
509ee091cf1Smatthias.ringwald }
510ee091cf1Smatthias.ringwald 
51116833f0aSmatthias.ringwald static void acl_handler(uint8_t *packet, int size){
5127856c818Smatthias.ringwald 
513e76a89eeS[email protected]     // log_info("acl_handler: size %u", size);
514e76a89eeS[email protected] 
5157856c818Smatthias.ringwald     // get info
5167856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
5175061f3afS[email protected]     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
5187856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
5197856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
5207856c818Smatthias.ringwald 
5217856c818Smatthias.ringwald     // ignore non-registered handle
5227856c818Smatthias.ringwald     if (!conn){
5239da54300S[email protected]         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
5247856c818Smatthias.ringwald         return;
5257856c818Smatthias.ringwald     }
5267856c818Smatthias.ringwald 
527e76a89eeS[email protected]     // assert packet is complete
5289ecc3e17S[email protected]     if (acl_length + 4 != size){
529e76a89eeS[email protected]         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
530e76a89eeS[email protected]         return;
531e76a89eeS[email protected]     }
532e76a89eeS[email protected] 
5337856c818Smatthias.ringwald     // update idle timestamp
5347856c818Smatthias.ringwald     hci_connection_timestamp(conn);
5357856c818Smatthias.ringwald 
5367856c818Smatthias.ringwald     // handle different packet types
5377856c818Smatthias.ringwald     switch (acl_flags & 0x03) {
5387856c818Smatthias.ringwald 
5397856c818Smatthias.ringwald         case 0x01: // continuation fragment
5407856c818Smatthias.ringwald 
5410ca847afS[email protected]             // sanity checks
5427856c818Smatthias.ringwald             if (conn->acl_recombination_pos == 0) {
5439da54300S[email protected]                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
5447856c818Smatthias.ringwald                 return;
5457856c818Smatthias.ringwald             }
5460ca847afS[email protected]             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
5470ca847afS[email protected]                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
5480ca847afS[email protected]                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
5490ca847afS[email protected]                 conn->acl_recombination_pos = 0;
5500ca847afS[email protected]                 return;
5510ca847afS[email protected]             }
5527856c818Smatthias.ringwald 
5537856c818Smatthias.ringwald             // append fragment payload (header already stored)
554ec6321eeS[email protected]             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
5557856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
5567856c818Smatthias.ringwald 
5579da54300S[email protected]             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
558decc01a8Smatthias.ringwald             //        conn->acl_recombination_pos, conn->acl_recombination_length);
5597856c818Smatthias.ringwald 
5607856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
5617856c818Smatthias.ringwald             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
5627856c818Smatthias.ringwald 
563ec6321eeS[email protected]                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, &conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
5647856c818Smatthias.ringwald                 // reset recombination buffer
5657856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
5667856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
5677856c818Smatthias.ringwald             }
5687856c818Smatthias.ringwald             break;
5697856c818Smatthias.ringwald 
5707856c818Smatthias.ringwald         case 0x02: { // first fragment
5717856c818Smatthias.ringwald 
57223a77e1aS[email protected]             // sanity check
57323a77e1aS[email protected]             if (conn->acl_recombination_pos) {
57423a77e1aS[email protected]                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
57523a77e1aS[email protected]                 conn->acl_recombination_pos = 0;
57623a77e1aS[email protected]             }
57723a77e1aS[email protected] 
5787856c818Smatthias.ringwald             // peek into L2CAP packet!
5797856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
5807856c818Smatthias.ringwald 
5819da54300S[email protected]             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
582decc01a8Smatthias.ringwald 
5837856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
5847856c818Smatthias.ringwald             if (acl_length >= l2cap_length + 4){
5857856c818Smatthias.ringwald 
5867856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
5873a9fb326S[email protected]                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
5887856c818Smatthias.ringwald 
5897856c818Smatthias.ringwald             } else {
5900ca847afS[email protected] 
5910ca847afS[email protected]                 if (acl_length > HCI_ACL_BUFFER_SIZE){
5920ca847afS[email protected]                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
5930ca847afS[email protected]                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
5940ca847afS[email protected]                     return;
5950ca847afS[email protected]                 }
5960ca847afS[email protected] 
5977856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
598ec6321eeS[email protected]                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
5997856c818Smatthias.ringwald                 conn->acl_recombination_pos    = acl_length + 4;
6007856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
601ec6321eeS[email protected]                 bt_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
6027856c818Smatthias.ringwald             }
6037856c818Smatthias.ringwald             break;
6047856c818Smatthias.ringwald 
6057856c818Smatthias.ringwald         }
6067856c818Smatthias.ringwald         default:
6079da54300S[email protected]             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
6087856c818Smatthias.ringwald             return;
6097856c818Smatthias.ringwald     }
61094ab26f8Smatthias.ringwald 
61194ab26f8Smatthias.ringwald     // execute main loop
61294ab26f8Smatthias.ringwald     hci_run();
61316833f0aSmatthias.ringwald }
61422909952Smatthias.ringwald 
61567a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
6169da54300S[email protected]     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
6173c4d4b90Smatthias.ringwald 
618c7e0c5f6Smatthias.ringwald     run_loop_remove_timer(&conn->timeout);
619c785ef68Smatthias.ringwald 
6203a9fb326S[email protected]     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
621a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
6223c4d4b90Smatthias.ringwald 
6233c4d4b90Smatthias.ringwald     // now it's gone
624c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
625c7e0c5f6Smatthias.ringwald }
626c7e0c5f6Smatthias.ringwald 
6270c042179S[email protected] static const uint16_t packet_type_sizes[] = {
6288f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
6298f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
6308f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
6318f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
6328f8108aaSmatthias.ringwald };
63365389bfcS[email protected] static const uint8_t  packet_type_feature_requirement_bit[] = {
63465389bfcS[email protected]      0, // 3 slot packets
63565389bfcS[email protected]      1, // 5 slot packets
63665389bfcS[email protected]     25, // EDR 2 mpbs
63765389bfcS[email protected]     26, // EDR 3 mbps
63865389bfcS[email protected]     39, // 3 slot EDR packts
63965389bfcS[email protected]     40, // 5 slot EDR packet
64065389bfcS[email protected] };
64165389bfcS[email protected] static const uint16_t packet_type_feature_packet_mask[] = {
64265389bfcS[email protected]     0x0f00, // 3 slot packets
64365389bfcS[email protected]     0xf000, // 5 slot packets
64465389bfcS[email protected]     0x1102, // EDR 2 mpbs
64565389bfcS[email protected]     0x2204, // EDR 3 mbps
64665389bfcS[email protected]     0x0300, // 3 slot EDR packts
64765389bfcS[email protected]     0x3000, // 5 slot EDR packet
64865389bfcS[email protected] };
6498f8108aaSmatthias.ringwald 
65065389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
65165389bfcS[email protected]     // enable packet types based on size
6528f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
653f16a69bbS[email protected]     unsigned int i;
6548f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
6558f8108aaSmatthias.ringwald         if (packet_type_sizes[i] == 0) continue;
6568f8108aaSmatthias.ringwald         if (packet_type_sizes[i] <= buffer_size){
6578f8108aaSmatthias.ringwald             packet_types |= 1 << i;
6588f8108aaSmatthias.ringwald         }
6598f8108aaSmatthias.ringwald     }
66065389bfcS[email protected]     // disable packet types due to missing local supported features
66165389bfcS[email protected]     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
66265389bfcS[email protected]         int bit_idx = packet_type_feature_requirement_bit[i];
66365389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
66465389bfcS[email protected]         if (feature_set) continue;
66565389bfcS[email protected]         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
66665389bfcS[email protected]         packet_types &= ~packet_type_feature_packet_mask[i];
66765389bfcS[email protected]     }
6688f8108aaSmatthias.ringwald     // flip bits for "may not be used"
6698f8108aaSmatthias.ringwald     packet_types ^= 0x3306;
6708f8108aaSmatthias.ringwald     return packet_types;
6718f8108aaSmatthias.ringwald }
6728f8108aaSmatthias.ringwald 
6738f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
6743a9fb326S[email protected]     return hci_stack->packet_types;
6758f8108aaSmatthias.ringwald }
6768f8108aaSmatthias.ringwald 
677facf93fdS[email protected] uint8_t* hci_get_outgoing_packet_buffer(void){
6787dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
6793a9fb326S[email protected]     return hci_stack->hci_packet_buffer;
6807dc17943Smatthias.ringwald }
6817dc17943Smatthias.ringwald 
682f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
6833a9fb326S[email protected]     return hci_stack->acl_data_packet_length;
6847dc17943Smatthias.ringwald }
6857dc17943Smatthias.ringwald 
6866ac9a97eS[email protected] int hci_non_flushable_packet_boundary_flag_supported(void){
6876ac9a97eS[email protected]     // No. 54, byte 6, bit 6
6886ac9a97eS[email protected]     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
6896ac9a97eS[email protected] }
6906ac9a97eS[email protected] 
691f5d8d141S[email protected] int hci_ssp_supported(void){
6926ac9a97eS[email protected]     // No. 51, byte 6, bit 3
6933a9fb326S[email protected]     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
694f5d8d141S[email protected] }
695f5d8d141S[email protected] 
696f5d8d141S[email protected] int hci_classic_supported(void){
6976ac9a97eS[email protected]     // No. 37, byte 4, bit 5, = No BR/EDR Support
6983a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
699f5d8d141S[email protected] }
700f5d8d141S[email protected] 
701f5d8d141S[email protected] int hci_le_supported(void){
702f5d8d141S[email protected] #ifdef HAVE_BLE
7036ac9a97eS[email protected]     // No. 37, byte 4, bit 6 = LE Supported (Controller)
7043a9fb326S[email protected]     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
705f5d8d141S[email protected] #else
706f5d8d141S[email protected]     return 0;
707f5d8d141S[email protected] #endif
708f5d8d141S[email protected] }
709f5d8d141S[email protected] 
71069a97523S[email protected] // get addr type and address used in advertisement packets
71118904abdS[email protected] void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){
7123a9fb326S[email protected]     *addr_type = hci_stack->adv_addr_type;
7133a9fb326S[email protected]     if (hci_stack->adv_addr_type){
7143a9fb326S[email protected]         memcpy(addr, hci_stack->adv_address, 6);
71569a97523S[email protected]     } else {
7163a9fb326S[email protected]         memcpy(addr, hci_stack->local_bd_addr, 6);
71769a97523S[email protected]     }
71869a97523S[email protected] }
71969a97523S[email protected] 
720b2f949feS[email protected] #ifdef HAVE_BLE
721e01fe8b6S[email protected] void le_handle_advertisement_report(uint8_t *packet, int size){
722d1dc057bS[email protected]     int offset = 3;
723d1dc057bS[email protected]     int num_reports = packet[offset];
724d1dc057bS[email protected]     offset += 1;
725d1dc057bS[email protected] 
72657c9da5bS[email protected]     int i;
7274f4b43f3S[email protected]     log_info("HCI: handle adv report with num reports: %d", num_reports);
728507d06b8S[email protected]     uint8_t event[2 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
72957c9da5bS[email protected]     for (i=0; i<num_reports;i++){
730210c6774S[email protected]         uint8_t data_length = packet[offset + 8];
7312b552b23S[email protected]         uint8_t event_size = 10 + data_length;
732d1dc057bS[email protected]         int pos = 0;
7332b552b23S[email protected]         event[pos++] = GAP_LE_ADVERTISING_REPORT;
73457c9da5bS[email protected]         event[pos++] = event_size;
735210c6774S[email protected]         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
736d1dc057bS[email protected]         offset += 8;
737d1dc057bS[email protected]         pos += 8;
738d1dc057bS[email protected]         event[pos++] = packet[offset + 1 + data_length]; // rssi
739d1dc057bS[email protected]         event[pos++] = packet[offset++]; //data_length;
740d1dc057bS[email protected]         memcpy(&event[pos], &packet[offset], data_length);
74157c9da5bS[email protected]         pos += data_length;
742d1dc057bS[email protected]         offset += data_length + 1; // rssi
7434f4b43f3S[email protected]         hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
74457c9da5bS[email protected]         hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
74557c9da5bS[email protected]     }
74657c9da5bS[email protected] }
747b2f949feS[email protected] #endif
74857c9da5bS[email protected] 
7496155b3d3S[email protected] static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
750a2481739S[email protected]     uint8_t command_completed = 0;
751a2481739S[email protected]     if ((hci_stack->substate % 2) == 0) return;
7526155b3d3S[email protected]     // odd: waiting for event
7536155b3d3S[email protected]     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
7546155b3d3S[email protected]         uint16_t opcode = READ_BT_16(packet,3);
7556155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
756a2481739S[email protected]             command_completed = 1;
757f456b2d0S[email protected]             log_info("Command complete for expected opcode %04x -> new substate %u", opcode, hci_stack->substate >> 1);
7586155b3d3S[email protected]         } else {
7596155b3d3S[email protected]             log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
7606155b3d3S[email protected]         }
7616155b3d3S[email protected]     }
7626155b3d3S[email protected]     if (packet[0] == HCI_EVENT_COMMAND_STATUS){
7636155b3d3S[email protected]         uint8_t  status = packet[2];
7646155b3d3S[email protected]         uint16_t opcode = READ_BT_16(packet,4);
7656155b3d3S[email protected]         if (opcode == hci_stack->last_cmd_opcode){
7666155b3d3S[email protected]             if (status){
767a2481739S[email protected]                 command_completed = 1;
768f456b2d0S[email protected]                 log_error("Command status error 0x%02x for expected opcode %04x -> new substate %u", status, opcode, hci_stack->substate >> 1);
7696155b3d3S[email protected]             } else {
7706155b3d3S[email protected]                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
7716155b3d3S[email protected]             }
7726155b3d3S[email protected]         } else {
7736155b3d3S[email protected]             log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
7746155b3d3S[email protected]         }
7756155b3d3S[email protected]     }
776a2481739S[email protected] 
777a2481739S[email protected]     if (!command_completed) return;
778a2481739S[email protected] 
779a2481739S[email protected]     switch(hci_stack->substate >> 1){
780a2481739S[email protected]         default:
781a2481739S[email protected]             hci_stack->substate++;
782a2481739S[email protected]             break;
7836155b3d3S[email protected]     }
7846155b3d3S[email protected] }
7856155b3d3S[email protected] 
7866155b3d3S[email protected] static void hci_initializing_state_machine(){
7876155b3d3S[email protected]     if (hci_stack->substate % 2) {
7886155b3d3S[email protected]         // odd: waiting for command completion
7896155b3d3S[email protected]         return;
7906155b3d3S[email protected]     }
791f456b2d0S[email protected]     // log_info("hci_init: substate %u", hci_stack->substate >> 1);
7926155b3d3S[email protected]     switch (hci_stack->substate >> 1){
7936155b3d3S[email protected]         case 0: // RESET
7946155b3d3S[email protected]             hci_state_reset();
7956155b3d3S[email protected] 
7966155b3d3S[email protected]             hci_send_cmd(&hci_reset);
7976155b3d3S[email protected]             if (hci_stack->config == NULL || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
7986155b3d3S[email protected]                 // skip baud change
799f456b2d0S[email protected]                 hci_stack->substate = 2 << 1;
8006155b3d3S[email protected]             }
8016155b3d3S[email protected]             break;
8026155b3d3S[email protected]         case 1: // SEND BAUD CHANGE
8036155b3d3S[email protected]             hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
80488789c61Smatthias.ringwald             hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
8056155b3d3S[email protected]             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
8066155b3d3S[email protected]             break;
8076155b3d3S[email protected]         case 2: // LOCAL BAUD CHANGE
8086155b3d3S[email protected]             log_info("Local baud rate change");
8096155b3d3S[email protected]             hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
8106155b3d3S[email protected]             hci_stack->substate += 2;
8116155b3d3S[email protected]             // break missing here for fall through
8126155b3d3S[email protected] 
813f456b2d0S[email protected]         case 3: // SET BD ADDR
814f456b2d0S[email protected]             if ( hci_stack->custom_bd_addr_set && hci_stack->control && hci_stack->control->set_bd_addr_cmd){
815f456b2d0S[email protected]                 log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
816f456b2d0S[email protected]                 hci_stack->control->set_bd_addr_cmd(hci_stack->config, hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
817*bc01039dS[email protected]                 hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
818f456b2d0S[email protected]                 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
819f456b2d0S[email protected]                 break;
820f456b2d0S[email protected]             }
821f456b2d0S[email protected]             hci_stack->substate += 2;
822f456b2d0S[email protected]             // break missing here for fall through
823f456b2d0S[email protected] 
824f456b2d0S[email protected]         case 4:
8256155b3d3S[email protected]             log_info("Custom init");
8266155b3d3S[email protected]             // Custom initialization
8276155b3d3S[email protected]             if (hci_stack->control && hci_stack->control->next_cmd){
8286155b3d3S[email protected]                 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
8296155b3d3S[email protected]                 if (valid_cmd){
8306155b3d3S[email protected]                     int size = 3 + hci_stack->hci_packet_buffer[2];
8316155b3d3S[email protected]                     hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
8325bb5bc3eS[email protected]                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
8336155b3d3S[email protected]                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
834f456b2d0S[email protected]                     hci_stack->substate = 3 << 1; // 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;
842f456b2d0S[email protected]         case 5:
8436155b3d3S[email protected]             hci_send_cmd(&hci_read_buffer_size);
8446155b3d3S[email protected]             break;
845f456b2d0S[email protected]         case 6:
8466155b3d3S[email protected]             hci_send_cmd(&hci_read_local_supported_features);
8476155b3d3S[email protected]             break;
848f456b2d0S[email protected]         case 7:
8496155b3d3S[email protected]             if (hci_le_supported()){
8506155b3d3S[email protected]                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
8516155b3d3S[email protected]             } else {
852f456b2d0S[email protected]                 // Kensington Bluetooth 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()){
859f456b2d0S[email protected]                     hci_stack->substate = 12 << 1;    // skip all classic command
8606155b3d3S[email protected]                 } else {
8616155b3d3S[email protected]                     log_error("Neither BR/EDR nor LE supported");
862f456b2d0S[email protected]                     hci_stack->substate = 15 << 1;    // skip all
8636155b3d3S[email protected]                 }
8646155b3d3S[email protected]             }
8656155b3d3S[email protected]             break;
866f456b2d0S[email protected]         case 8:
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] 
874f456b2d0S[email protected]         case 9:
8756155b3d3S[email protected]             // ca. 15 sec
8766155b3d3S[email protected]             hci_send_cmd(&hci_write_page_timeout, 0x6000);
8776155b3d3S[email protected]             break;
878f456b2d0S[email protected]         case 10:
8796155b3d3S[email protected]             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
8806155b3d3S[email protected]             break;
881f456b2d0S[email protected]         case 11:
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;
899f456b2d0S[email protected]         case 12:
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
903f456b2d0S[email protected]                 hci_stack->substate = 15 << 1;
9046155b3d3S[email protected]             }
9056155b3d3S[email protected]             break;
9066155b3d3S[email protected] 
9076155b3d3S[email protected] #ifdef HAVE_BLE
9086155b3d3S[email protected]         // LE INIT
909f456b2d0S[email protected]         case 13:
9106155b3d3S[email protected]             hci_send_cmd(&hci_le_read_buffer_size);
9116155b3d3S[email protected]             break;
912f456b2d0S[email protected]         case 14:
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;
916f456b2d0S[email protected]         case 15:
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
923f456b2d0S[email protected]         case 16:
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] 
1010a5a23fc2S[email protected]                 // determine usable ACL packet types based on host buffer size and supported features
1011a5a23fc2S[email protected]                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &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
1263ccda6e14S[email protected]         // has been split, to first notify stack before shutting connection down
1264ccda6e14S[email protected]         // see end of function, too.
1265a4f30ec0S[email protected]         case HCI_EVENT_DISCONNECTION_COMPLETE:
1266a4f30ec0S[email protected]             if (packet[2]) break;   // status != 0
1267ccda6e14S[email protected]             handle = READ_BT_16(packet, 3);
1268ccda6e14S[email protected]             hci_connection_t * conn = hci_connection_for_handle(handle);
1269a4f30ec0S[email protected]             if (!conn) break;       // no conn struct anymore
1270ccda6e14S[email protected]             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1271ccda6e14S[email protected]             break;
12726772a24cSmatthias.ringwald 
1273c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
12743a9fb326S[email protected]             if(hci_stack->control && hci_stack->control->hw_error){
12753a9fb326S[email protected]                 (*hci_stack->control->hw_error)();
12767586ee35S[email protected]             } else {
12777586ee35S[email protected]                 // if no special requests, just reboot stack
12787586ee35S[email protected]                 hci_power_control_off();
12797586ee35S[email protected]                 hci_power_control_on();
1280c68bdf90Smatthias.ringwald             }
1281c68bdf90Smatthias.ringwald             break;
1282c68bdf90Smatthias.ringwald 
12836b4af23dS[email protected]         case DAEMON_EVENT_HCI_PACKET_SENT:
1284d051460cS[email protected]             // release packet buffer only for asynchronous transport and if there are not further fragements
12854fa24b5fS[email protected]             if (hci_transport_synchronous()) {
12864fa24b5fS[email protected]                 log_error("Synchronous HCI Transport shouldn't send DAEMON_EVENT_HCI_PACKET_SENT");
12874fa24b5fS[email protected]                 return; // instead of break: to avoid re-entering hci_run()
12884fa24b5fS[email protected]             }
1289d051460cS[email protected]             if (hci_stack->acl_fragmentation_total_size) break;
1290d051460cS[email protected]             hci_release_packet_buffer();
12916b4af23dS[email protected]             break;
12926b4af23dS[email protected] 
12935909f7f2Smatthias.ringwald #ifdef HAVE_BLE
12945909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
12955909f7f2Smatthias.ringwald             switch (packet[2]){
129657c9da5bS[email protected]                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
12979da54300S[email protected]                     log_info("advertising report received");
12987bdc6798S[email protected]                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
129957c9da5bS[email protected]                     le_handle_advertisement_report(packet, size);
13007bdc6798S[email protected]                     break;
13015909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
13025909f7f2Smatthias.ringwald                     // Connection management
13035909f7f2Smatthias.ringwald                     bt_flip_addr(addr, &packet[8]);
13047bdc6798S[email protected]                     addr_type = (bd_addr_type_t)packet[7];
13059da54300S[email protected]                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
13065909f7f2Smatthias.ringwald                     // LE connections are auto-accepted, so just create a connection if there isn't one already
130796a45072S[email protected]                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
13085909f7f2Smatthias.ringwald                     if (packet[3]){
13095909f7f2Smatthias.ringwald                         if (conn){
13105909f7f2Smatthias.ringwald                             // outgoing connection failed, remove entry
13113a9fb326S[email protected]                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
13125909f7f2Smatthias.ringwald                             btstack_memory_hci_connection_free( conn );
13135909f7f2Smatthias.ringwald                         }
13145909f7f2Smatthias.ringwald                         // if authentication error, also delete link key
13155909f7f2Smatthias.ringwald                         if (packet[3] == 0x05) {
13165909f7f2Smatthias.ringwald                             hci_drop_link_key_for_bd_addr(&addr);
13175909f7f2Smatthias.ringwald                         }
13185909f7f2Smatthias.ringwald                         break;
13195909f7f2Smatthias.ringwald                     }
13205909f7f2Smatthias.ringwald                     if (!conn){
132196a45072S[email protected]                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
13225909f7f2Smatthias.ringwald                     }
13235909f7f2Smatthias.ringwald                     if (!conn){
13245909f7f2Smatthias.ringwald                         // no memory
13255909f7f2Smatthias.ringwald                         break;
13265909f7f2Smatthias.ringwald                     }
13275909f7f2Smatthias.ringwald 
13285909f7f2Smatthias.ringwald                     conn->state = OPEN;
13295909f7f2Smatthias.ringwald                     conn->con_handle = READ_BT_16(packet, 4);
13305909f7f2Smatthias.ringwald 
13315909f7f2Smatthias.ringwald                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
13325909f7f2Smatthias.ringwald 
13335909f7f2Smatthias.ringwald                     // restart timer
13345909f7f2Smatthias.ringwald                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
13355909f7f2Smatthias.ringwald                     // run_loop_add_timer(&conn->timeout);
13365909f7f2Smatthias.ringwald 
13379da54300S[email protected]                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
13385909f7f2Smatthias.ringwald 
13395909f7f2Smatthias.ringwald                     hci_emit_nr_connections_changed();
13405909f7f2Smatthias.ringwald                     break;
13415909f7f2Smatthias.ringwald 
13429da54300S[email protected]             // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]);
134365a46ef3S[email protected] 
13445909f7f2Smatthias.ringwald                 default:
13455909f7f2Smatthias.ringwald                     break;
13465909f7f2Smatthias.ringwald             }
13475909f7f2Smatthias.ringwald             break;
13485909f7f2Smatthias.ringwald #endif
13496772a24cSmatthias.ringwald         default:
13506772a24cSmatthias.ringwald             break;
1351fe1ed1b8Smatthias.ringwald     }
1352fe1ed1b8Smatthias.ringwald 
13533429f56bSmatthias.ringwald     // handle BT initialization
13543a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_INITIALIZING){
13556155b3d3S[email protected]         hci_initializing_event_handler(packet, size);
1356c9af4d3fS[email protected]     }
135722909952Smatthias.ringwald 
135889db417bSmatthias.ringwald     // help with BT sleep
13593a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
13603a9fb326S[email protected]         && hci_stack->substate == 1
136189db417bSmatthias.ringwald         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
13623a9fb326S[email protected]         hci_stack->substate++;
136389db417bSmatthias.ringwald     }
136489db417bSmatthias.ringwald 
136586805605S[email protected]     // notify upper stack
13663a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
136794ab26f8Smatthias.ringwald 
136886805605S[email protected]     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
136986805605S[email protected]     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
137086805605S[email protected]         if (!packet[2]){
137186805605S[email protected]             handle = READ_BT_16(packet, 3);
137286805605S[email protected]             hci_connection_t * conn = hci_connection_for_handle(handle);
137386805605S[email protected]             if (conn) {
137486805605S[email protected]                 uint8_t status = conn->bonding_status;
1375bb820044S[email protected]                 uint16_t flags = conn->bonding_flags;
137686805605S[email protected]                 bd_addr_t bd_address;
137786805605S[email protected]                 memcpy(&bd_address, conn->address, 6);
137886805605S[email protected]                 hci_shutdown_connection(conn);
1379bb820044S[email protected]                 // connection struct is gone, don't access anymore
1380bb820044S[email protected]                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
138186805605S[email protected]                     hci_emit_dedicated_bonding_result(bd_address, status);
138286805605S[email protected]                 }
138386805605S[email protected]             }
138486805605S[email protected]         }
138586805605S[email protected]     }
138686805605S[email protected] 
138794ab26f8Smatthias.ringwald 	// execute main loop
138894ab26f8Smatthias.ringwald 	hci_run();
138916833f0aSmatthias.ringwald }
139016833f0aSmatthias.ringwald 
13910a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
13925bb5bc3eS[email protected]     hci_dump_packet(packet_type, 1, packet, size);
139310e830c9Smatthias.ringwald     switch (packet_type) {
139410e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
139510e830c9Smatthias.ringwald             event_handler(packet, size);
139610e830c9Smatthias.ringwald             break;
139710e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
139810e830c9Smatthias.ringwald             acl_handler(packet, size);
139910e830c9Smatthias.ringwald             break;
140010e830c9Smatthias.ringwald         default:
140110e830c9Smatthias.ringwald             break;
140210e830c9Smatthias.ringwald     }
140310e830c9Smatthias.ringwald }
140410e830c9Smatthias.ringwald 
1405fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
14062718e2e7Smatthias.ringwald void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
14073a9fb326S[email protected]     hci_stack->packet_handler = handler;
140816833f0aSmatthias.ringwald }
140916833f0aSmatthias.ringwald 
14106155b3d3S[email protected] static void hci_state_reset(){
1411595bdbfbS[email protected]     // no connections yet
1412595bdbfbS[email protected]     hci_stack->connections = NULL;
141374308b23Smatthias.ringwald 
141474308b23Smatthias.ringwald     // keep discoverable/connectable as this has been requested by the client(s)
141574308b23Smatthias.ringwald     // hci_stack->discoverable = 0;
141674308b23Smatthias.ringwald     // hci_stack->connectable = 0;
141774308b23Smatthias.ringwald     // hci_stack->bondable = 1;
1418595bdbfbS[email protected] 
141944935e40S[email protected]     // buffer is free
142044935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
142144935e40S[email protected] 
1422595bdbfbS[email protected]     // no pending cmds
1423595bdbfbS[email protected]     hci_stack->decline_reason = 0;
1424595bdbfbS[email protected]     hci_stack->new_scan_enable_value = 0xff;
1425595bdbfbS[email protected] 
1426595bdbfbS[email protected]     // LE
1427595bdbfbS[email protected]     hci_stack->adv_addr_type = 0;
1428595bdbfbS[email protected]     memset(hci_stack->adv_address, 0, 6);
1429595bdbfbS[email protected]     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1430e2602ea2Smatthias.ringwald     hci_stack->le_scan_type = 0xff;
1431da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_interval_min = 0x0006;
1432da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_interval_max = 0x0C80;
1433da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_latency_min = 0x0000;
1434da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_conn_latency_max = 0x03E8;
1435da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = 0x000A;
1436da886c03S[email protected]     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 0x0C80;
1437595bdbfbS[email protected] }
1438595bdbfbS[email protected] 
14394f4fc1dfSmatthias.ringwald void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
1440475c8125Smatthias.ringwald 
14413a9fb326S[email protected] #ifdef HAVE_MALLOC
14423a9fb326S[email protected]     if (!hci_stack) {
14433a9fb326S[email protected]         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
14443a9fb326S[email protected]     }
14453a9fb326S[email protected] #else
14463a9fb326S[email protected]     hci_stack = &hci_stack_static;
14473a9fb326S[email protected] #endif
144866fb9560S[email protected]     memset(hci_stack, 0, sizeof(hci_stack_t));
14493a9fb326S[email protected] 
1450475c8125Smatthias.ringwald     // reference to use transport layer implementation
14513a9fb326S[email protected]     hci_stack->hci_transport = transport;
1452475c8125Smatthias.ringwald 
145311e23e5fSmatthias.ringwald     // references to used control implementation
14543a9fb326S[email protected]     hci_stack->control = control;
145511e23e5fSmatthias.ringwald 
145611e23e5fSmatthias.ringwald     // reference to used config
14573a9fb326S[email protected]     hci_stack->config = config;
145811e23e5fSmatthias.ringwald 
145916833f0aSmatthias.ringwald     // higher level handler
14603a9fb326S[email protected]     hci_stack->packet_handler = dummy_handler;
146116833f0aSmatthias.ringwald 
1462404843c1Smatthias.ringwald     // store and open remote device db
14633a9fb326S[email protected]     hci_stack->remote_device_db = remote_device_db;
14643a9fb326S[email protected]     if (hci_stack->remote_device_db) {
14653a9fb326S[email protected]         hci_stack->remote_device_db->open();
1466404843c1Smatthias.ringwald     }
146729d53098Smatthias.ringwald 
14688fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
14693a9fb326S[email protected]     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
14708fcba05dSmatthias.ringwald 
147116833f0aSmatthias.ringwald     // register packet handlers with transport
147210e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
1473f5454fc6Smatthias.ringwald 
14743a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
1475e2386ba1S[email protected] 
1476e2386ba1S[email protected]     // class of device
14773a9fb326S[email protected]     hci_stack->class_of_device = 0x007a020c; // Smartphone
1478a45d6b9fS[email protected] 
1479f20168b8Smatthias.ringwald     // bondable by default
1480f20168b8Smatthias.ringwald     hci_stack->bondable = 1;
1481f20168b8Smatthias.ringwald 
148263048403S[email protected]     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
14833a9fb326S[email protected]     hci_stack->ssp_enable = 1;
14843a9fb326S[email protected]     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
14853a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
14863a9fb326S[email protected]     hci_stack->ssp_auto_accept = 1;
148769a97523S[email protected] 
1488595bdbfbS[email protected]     hci_state_reset();
1489475c8125Smatthias.ringwald }
1490475c8125Smatthias.ringwald 
1491404843c1Smatthias.ringwald void hci_close(){
1492404843c1Smatthias.ringwald     // close remote device db
14933a9fb326S[email protected]     if (hci_stack->remote_device_db) {
14943a9fb326S[email protected]         hci_stack->remote_device_db->close();
1495404843c1Smatthias.ringwald     }
14963a9fb326S[email protected]     while (hci_stack->connections) {
1497bc68afe2S[email protected]         // cancel all l2cap connections
1498bc68afe2S[email protected]         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
14993a9fb326S[email protected]         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1500f5454fc6Smatthias.ringwald     }
1501f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
15023a9fb326S[email protected] 
15033a9fb326S[email protected] #ifdef HAVE_MALLOC
15043a9fb326S[email protected]     free(hci_stack);
15053a9fb326S[email protected] #endif
15063a9fb326S[email protected]     hci_stack = NULL;
1507404843c1Smatthias.ringwald }
1508404843c1Smatthias.ringwald 
15099e61646fS[email protected] void hci_set_class_of_device(uint32_t class_of_device){
15109e61646fS[email protected]     hci_stack->class_of_device = class_of_device;
15119e61646fS[email protected] }
15129e61646fS[email protected] 
1513f456b2d0S[email protected] // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
1514f456b2d0S[email protected] void hci_set_bd_addr(bd_addr_t addr){
1515f456b2d0S[email protected]     memcpy(hci_stack->custom_bd_addr, addr, 6);
1516f456b2d0S[email protected]     hci_stack->custom_bd_addr_set = 1;
1517f456b2d0S[email protected] }
1518f456b2d0S[email protected] 
151966fb9560S[email protected] void hci_disable_l2cap_timeout_check(){
152066fb9560S[email protected]     disable_l2cap_timeouts = 1;
152166fb9560S[email protected] }
15228d213e1aSmatthias.ringwald // State-Module-Driver overview
15238d213e1aSmatthias.ringwald // state                    module  low-level
15248d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
15258d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
15268d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
15278d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
1528d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
1529d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
1530c7e0c5f6Smatthias.ringwald 
153140d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
15327301ad89Smatthias.ringwald 
1533038bc64cSmatthias.ringwald     // power on
1534f9a30166Smatthias.ringwald     int err = 0;
15353a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->on){
15363a9fb326S[email protected]         err = (*hci_stack->control->on)(hci_stack->config);
1537f9a30166Smatthias.ringwald     }
1538038bc64cSmatthias.ringwald     if (err){
15399da54300S[email protected]         log_error( "POWER_ON failed");
1540038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
1541038bc64cSmatthias.ringwald         return err;
1542038bc64cSmatthias.ringwald     }
1543038bc64cSmatthias.ringwald 
1544038bc64cSmatthias.ringwald     // open low-level device
15453a9fb326S[email protected]     err = hci_stack->hci_transport->open(hci_stack->config);
1546038bc64cSmatthias.ringwald     if (err){
15479da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
15483a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
15493a9fb326S[email protected]             (*hci_stack->control->off)(hci_stack->config);
1550f9a30166Smatthias.ringwald         }
1551038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
1552038bc64cSmatthias.ringwald         return err;
1553038bc64cSmatthias.ringwald     }
15548d213e1aSmatthias.ringwald     return 0;
15558d213e1aSmatthias.ringwald }
1556038bc64cSmatthias.ringwald 
155740d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
15588d213e1aSmatthias.ringwald 
15599da54300S[email protected]     log_info("hci_power_control_off");
15609418f9c9Smatthias.ringwald 
15618d213e1aSmatthias.ringwald     // close low-level device
15623a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
15638d213e1aSmatthias.ringwald 
15649da54300S[email protected]     log_info("hci_power_control_off - hci_transport closed");
15659418f9c9Smatthias.ringwald 
15668d213e1aSmatthias.ringwald     // power off
15673a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->off){
15683a9fb326S[email protected]         (*hci_stack->control->off)(hci_stack->config);
15698d213e1aSmatthias.ringwald     }
15709418f9c9Smatthias.ringwald 
15719da54300S[email protected]     log_info("hci_power_control_off - control closed");
15729418f9c9Smatthias.ringwald 
15733a9fb326S[email protected]     hci_stack->state = HCI_STATE_OFF;
157472ea5239Smatthias.ringwald }
157572ea5239Smatthias.ringwald 
157640d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
157772ea5239Smatthias.ringwald 
15789da54300S[email protected]     log_info("hci_power_control_sleep");
15793144bce4Smatthias.ringwald 
1580b429b9b7Smatthias.ringwald #if 0
1581b429b9b7Smatthias.ringwald     // don't close serial port during sleep
1582b429b9b7Smatthias.ringwald 
158372ea5239Smatthias.ringwald     // close low-level device
15843a9fb326S[email protected]     hci_stack->hci_transport->close(hci_stack->config);
1585b429b9b7Smatthias.ringwald #endif
158672ea5239Smatthias.ringwald 
158772ea5239Smatthias.ringwald     // sleep mode
15883a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->sleep){
15893a9fb326S[email protected]         (*hci_stack->control->sleep)(hci_stack->config);
159072ea5239Smatthias.ringwald     }
1591b429b9b7Smatthias.ringwald 
15923a9fb326S[email protected]     hci_stack->state = HCI_STATE_SLEEPING;
15938d213e1aSmatthias.ringwald }
15948d213e1aSmatthias.ringwald 
159540d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
1596b429b9b7Smatthias.ringwald 
15979da54300S[email protected]     log_info("hci_power_control_wake");
1598b429b9b7Smatthias.ringwald 
1599b429b9b7Smatthias.ringwald     // wake on
16003a9fb326S[email protected]     if (hci_stack->control && hci_stack->control->wake){
16013a9fb326S[email protected]         (*hci_stack->control->wake)(hci_stack->config);
1602b429b9b7Smatthias.ringwald     }
1603b429b9b7Smatthias.ringwald 
1604b429b9b7Smatthias.ringwald #if 0
1605b429b9b7Smatthias.ringwald     // open low-level device
16063a9fb326S[email protected]     int err = hci_stack->hci_transport->open(hci_stack->config);
1607b429b9b7Smatthias.ringwald     if (err){
16089da54300S[email protected]         log_error( "HCI_INIT failed, turning Bluetooth off again");
16093a9fb326S[email protected]         if (hci_stack->control && hci_stack->control->off){
16103a9fb326S[email protected]             (*hci_stack->control->off)(hci_stack->config);
1611b429b9b7Smatthias.ringwald         }
1612b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
1613b429b9b7Smatthias.ringwald         return err;
1614b429b9b7Smatthias.ringwald     }
1615b429b9b7Smatthias.ringwald #endif
1616b429b9b7Smatthias.ringwald 
1617b429b9b7Smatthias.ringwald     return 0;
1618b429b9b7Smatthias.ringwald }
1619b429b9b7Smatthias.ringwald 
162044935e40S[email protected] static void hci_power_transition_to_initializing(void){
162144935e40S[email protected]     // set up state machine
162244935e40S[email protected]     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
162344935e40S[email protected]     hci_stack->hci_packet_buffer_reserved = 0;
162444935e40S[email protected]     hci_stack->state = HCI_STATE_INITIALIZING;
162544935e40S[email protected]     hci_stack->substate = 0;
162644935e40S[email protected] }
1627b429b9b7Smatthias.ringwald 
16288d213e1aSmatthias.ringwald int hci_power_control(HCI_POWER_MODE power_mode){
1629d661ed19Smatthias.ringwald 
16309da54300S[email protected]     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
1631d661ed19Smatthias.ringwald 
16328d213e1aSmatthias.ringwald     int err = 0;
16333a9fb326S[email protected]     switch (hci_stack->state){
16348d213e1aSmatthias.ringwald 
16358d213e1aSmatthias.ringwald         case HCI_STATE_OFF:
16368d213e1aSmatthias.ringwald             switch (power_mode){
16378d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
16388d213e1aSmatthias.ringwald                     err = hci_power_control_on();
163997b61c7bS[email protected]                     if (err) {
164097b61c7bS[email protected]                         log_error("hci_power_control_on() error %u", err);
164197b61c7bS[email protected]                         return err;
164297b61c7bS[email protected]                     }
164344935e40S[email protected]                     hci_power_transition_to_initializing();
16448d213e1aSmatthias.ringwald                     break;
16458d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
16468d213e1aSmatthias.ringwald                     // do nothing
16478d213e1aSmatthias.ringwald                     break;
16488d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1649b546ac54Smatthias.ringwald                     // do nothing (with SLEEP == OFF)
16508d213e1aSmatthias.ringwald                     break;
16518d213e1aSmatthias.ringwald             }
16528d213e1aSmatthias.ringwald             break;
16537301ad89Smatthias.ringwald 
16548d213e1aSmatthias.ringwald         case HCI_STATE_INITIALIZING:
16558d213e1aSmatthias.ringwald             switch (power_mode){
16568d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
16578d213e1aSmatthias.ringwald                     // do nothing
16588d213e1aSmatthias.ringwald                     break;
16598d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
16608d213e1aSmatthias.ringwald                     // no connections yet, just turn it off
16618d213e1aSmatthias.ringwald                     hci_power_control_off();
16628d213e1aSmatthias.ringwald                     break;
16638d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1664b546ac54Smatthias.ringwald                     // no connections yet, just turn it off
166572ea5239Smatthias.ringwald                     hci_power_control_sleep();
16668d213e1aSmatthias.ringwald                     break;
16678d213e1aSmatthias.ringwald             }
16688d213e1aSmatthias.ringwald             break;
16697301ad89Smatthias.ringwald 
16708d213e1aSmatthias.ringwald         case HCI_STATE_WORKING:
16718d213e1aSmatthias.ringwald             switch (power_mode){
16728d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
16738d213e1aSmatthias.ringwald                     // do nothing
16748d213e1aSmatthias.ringwald                     break;
16758d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
1676c7e0c5f6Smatthias.ringwald                     // see hci_run
16773a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
16788d213e1aSmatthias.ringwald                     break;
16798d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1680b546ac54Smatthias.ringwald                     // see hci_run
16813a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
16823a9fb326S[email protected]                     hci_stack->substate = 0;
16838d213e1aSmatthias.ringwald                     break;
16848d213e1aSmatthias.ringwald             }
16858d213e1aSmatthias.ringwald             break;
16867301ad89Smatthias.ringwald 
16878d213e1aSmatthias.ringwald         case HCI_STATE_HALTING:
16888d213e1aSmatthias.ringwald             switch (power_mode){
16898d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
169044935e40S[email protected]                     hci_power_transition_to_initializing();
16918d213e1aSmatthias.ringwald                     break;
16928d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
16938d213e1aSmatthias.ringwald                     // do nothing
16948d213e1aSmatthias.ringwald                     break;
16958d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1696b546ac54Smatthias.ringwald                     // see hci_run
16973a9fb326S[email protected]                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
16983a9fb326S[email protected]                     hci_stack->substate = 0;
16998d213e1aSmatthias.ringwald                     break;
17008d213e1aSmatthias.ringwald             }
17018d213e1aSmatthias.ringwald             break;
17028d213e1aSmatthias.ringwald 
17038d213e1aSmatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
17048d213e1aSmatthias.ringwald             switch (power_mode){
17058d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
170628171530Smatthias.ringwald 
170728171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
170828171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
170928171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
17103a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
17113a9fb326S[email protected]                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
171228171530Smatthias.ringwald                         break;
171328171530Smatthias.ringwald                     }
171428171530Smatthias.ringwald #endif
171544935e40S[email protected]                     hci_power_transition_to_initializing();
17168d213e1aSmatthias.ringwald                     break;
17178d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
1718b546ac54Smatthias.ringwald                     // see hci_run
17193a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
17208d213e1aSmatthias.ringwald                     break;
17218d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1722b546ac54Smatthias.ringwald                     // do nothing
17238d213e1aSmatthias.ringwald                     break;
17248d213e1aSmatthias.ringwald             }
17258d213e1aSmatthias.ringwald             break;
17268d213e1aSmatthias.ringwald 
17278d213e1aSmatthias.ringwald         case HCI_STATE_SLEEPING:
17288d213e1aSmatthias.ringwald             switch (power_mode){
17298d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
173028171530Smatthias.ringwald 
173128171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
173228171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
173328171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
17343a9fb326S[email protected]                         hci_stack->state = HCI_STATE_INITIALIZING;
17353a9fb326S[email protected]                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1736758b46ceSmatthias.ringwald                         hci_update_scan_enable();
173728171530Smatthias.ringwald                         break;
173828171530Smatthias.ringwald                     }
173928171530Smatthias.ringwald #endif
17403144bce4Smatthias.ringwald                     err = hci_power_control_wake();
17413144bce4Smatthias.ringwald                     if (err) return err;
174244935e40S[email protected]                     hci_power_transition_to_initializing();
17438d213e1aSmatthias.ringwald                     break;
17448d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
17453a9fb326S[email protected]                     hci_stack->state = HCI_STATE_HALTING;
17468d213e1aSmatthias.ringwald                     break;
17478d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1748b546ac54Smatthias.ringwald                     // do nothing
17498d213e1aSmatthias.ringwald                     break;
17508d213e1aSmatthias.ringwald             }
17518d213e1aSmatthias.ringwald             break;
175211e23e5fSmatthias.ringwald     }
175368d92d03Smatthias.ringwald 
1754038bc64cSmatthias.ringwald     // create internal event
1755ee8bf225Smatthias.ringwald 	hci_emit_state();
1756ee8bf225Smatthias.ringwald 
175768d92d03Smatthias.ringwald 	// trigger next/first action
175868d92d03Smatthias.ringwald 	hci_run();
175968d92d03Smatthias.ringwald 
1760475c8125Smatthias.ringwald     return 0;
1761475c8125Smatthias.ringwald }
1762475c8125Smatthias.ringwald 
1763758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
1764758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
17653a9fb326S[email protected]     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1766758b46ceSmatthias.ringwald     hci_run();
1767758b46ceSmatthias.ringwald }
1768758b46ceSmatthias.ringwald 
1769381fbed8Smatthias.ringwald void hci_discoverable_control(uint8_t enable){
1770381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
1771381fbed8Smatthias.ringwald 
17723a9fb326S[email protected]     if (hci_stack->discoverable == enable){
17733a9fb326S[email protected]         hci_emit_discoverable_enabled(hci_stack->discoverable);
1774381fbed8Smatthias.ringwald         return;
1775381fbed8Smatthias.ringwald     }
1776381fbed8Smatthias.ringwald 
17773a9fb326S[email protected]     hci_stack->discoverable = enable;
1778758b46ceSmatthias.ringwald     hci_update_scan_enable();
1779758b46ceSmatthias.ringwald }
1780b031bebbSmatthias.ringwald 
1781758b46ceSmatthias.ringwald void hci_connectable_control(uint8_t enable){
1782758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
1783758b46ceSmatthias.ringwald 
1784758b46ceSmatthias.ringwald     // don't emit event
17853a9fb326S[email protected]     if (hci_stack->connectable == enable) return;
1786758b46ceSmatthias.ringwald 
17873a9fb326S[email protected]     hci_stack->connectable = enable;
1788758b46ceSmatthias.ringwald     hci_update_scan_enable();
1789381fbed8Smatthias.ringwald }
1790381fbed8Smatthias.ringwald 
17915061f3afS[email protected] bd_addr_t * hci_local_bd_addr(void){
17923a9fb326S[email protected]     return &hci_stack->local_bd_addr;
17935061f3afS[email protected] }
17945061f3afS[email protected] 
179506b35ec0Smatthias.ringwald void hci_run(){
17968a485f27Smatthias.ringwald 
179732ab9390Smatthias.ringwald     hci_connection_t * connection;
179832ab9390Smatthias.ringwald     linked_item_t * it;
179932ab9390Smatthias.ringwald 
1800b5d8b22bS[email protected]     // send continuation fragments first, as they block the prepared packet buffer
1801b5d8b22bS[email protected]     if (hci_stack->acl_fragmentation_total_size > 0) {
1802b5d8b22bS[email protected]         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
1803b5d8b22bS[email protected]         if (hci_can_send_prepared_acl_packet_now(con_handle)){
1804b5d8b22bS[email protected]             hci_connection_t *connection = hci_connection_for_handle(con_handle);
1805b5d8b22bS[email protected]             if (connection) {
1806b5d8b22bS[email protected]                 hci_send_acl_packet_fragments(connection);
1807b5d8b22bS[email protected]                 return;
1808b5d8b22bS[email protected]             }
1809b5d8b22bS[email protected]             // connection gone -> discard further fragments
1810b5d8b22bS[email protected]             hci_stack->acl_fragmentation_total_size = 0;
1811b5d8b22bS[email protected]             hci_stack->acl_fragmentation_pos = 0;
1812b5d8b22bS[email protected]         }
1813b5d8b22bS[email protected]     }
1814b5d8b22bS[email protected] 
1815d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()) return;
1816ce4c8fabSmatthias.ringwald 
1817b031bebbSmatthias.ringwald     // global/non-connection oriented commands
1818b031bebbSmatthias.ringwald 
1819b031bebbSmatthias.ringwald     // decline incoming connections
18203a9fb326S[email protected]     if (hci_stack->decline_reason){
18213a9fb326S[email protected]         uint8_t reason = hci_stack->decline_reason;
18223a9fb326S[email protected]         hci_stack->decline_reason = 0;
18233a9fb326S[email protected]         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1824dbe1a790S[email protected]         return;
1825ce4c8fabSmatthias.ringwald     }
1826ce4c8fabSmatthias.ringwald 
1827b031bebbSmatthias.ringwald     // send scan enable
18283a9fb326S[email protected]     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
18293a9fb326S[email protected]         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
18303a9fb326S[email protected]         hci_stack->new_scan_enable_value = 0xff;
1831dbe1a790S[email protected]         return;
1832b031bebbSmatthias.ringwald     }
1833b031bebbSmatthias.ringwald 
1834b2f949feS[email protected] #ifdef HAVE_BLE
18357bdc6798S[email protected]     // handle le scan
18367bdc6798S[email protected]     if (hci_stack->state == HCI_STATE_WORKING){
18377bdc6798S[email protected]         switch(hci_stack->le_scanning_state){
18387bdc6798S[email protected]             case LE_START_SCAN:
18397bdc6798S[email protected]                 hci_stack->le_scanning_state = LE_SCANNING;
18407bdc6798S[email protected]                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
18417bdc6798S[email protected]                 return;
18427bdc6798S[email protected] 
18437bdc6798S[email protected]             case LE_STOP_SCAN:
18447bdc6798S[email protected]                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
18457bdc6798S[email protected]                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
18467bdc6798S[email protected]                 return;
18477bdc6798S[email protected]             default:
18487bdc6798S[email protected]                 break;
18497bdc6798S[email protected]         }
1850e2602ea2Smatthias.ringwald         if (hci_stack->le_scan_type != 0xff){
1851e2602ea2Smatthias.ringwald             // defaults: active scanning, accept all advertisement packets
1852e2602ea2Smatthias.ringwald             int scan_type = hci_stack->le_scan_type;
1853e2602ea2Smatthias.ringwald             hci_stack->le_scan_type = 0xff;
1854e2602ea2Smatthias.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);
1855e2602ea2Smatthias.ringwald             return;
1856e2602ea2Smatthias.ringwald         }
18577bdc6798S[email protected]     }
1858b2f949feS[email protected] #endif
18597bdc6798S[email protected] 
186032ab9390Smatthias.ringwald     // send pending HCI commands
18613a9fb326S[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1862b031bebbSmatthias.ringwald         connection = (hci_connection_t *) it;
186332ab9390Smatthias.ringwald 
18640bf6344aS[email protected]         switch(connection->state){
18650bf6344aS[email protected]             case SEND_CREATE_CONNECTION:
18664f3229d8S[email protected]                 switch(connection->address_type){
18674f3229d8S[email protected]                     case BD_ADDR_TYPE_CLASSIC:
18689da54300S[email protected]                         log_info("sending hci_create_connection");
1869ad83dc6aS[email protected]                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
18704f3229d8S[email protected]                         break;
18714f3229d8S[email protected]                     default:
1872b2f949feS[email protected] #ifdef HAVE_BLE
18739da54300S[email protected]                         log_info("sending hci_le_create_connection");
18744f3229d8S[email protected]                         hci_send_cmd(&hci_le_create_connection,
1875b2571179Smatthias.ringwald                                      0x0060,    // scan interval: 60 ms
1876b2571179Smatthias.ringwald                                      0x0030,    // scan interval: 30 ms
18774f3229d8S[email protected]                                      0,         // don't use whitelist
18784f3229d8S[email protected]                                      connection->address_type, // peer address type
18794f3229d8S[email protected]                                      connection->address,      // peer bd addr
1880b2571179Smatthias.ringwald                                      hci_stack->adv_addr_type, // our addr type:
1881b2571179Smatthias.ringwald                                      0x0008,    // conn interval min
1882b2571179Smatthias.ringwald                                      0x0018,    // conn interval max
18834f3229d8S[email protected]                                      0,         // conn latency
1884b2571179Smatthias.ringwald                                      0x0048,    // supervision timeout
1885b2571179Smatthias.ringwald                                      0x0001,    // min ce length
1886b2571179Smatthias.ringwald                                      0x0001     // max ce length
18874f3229d8S[email protected]                                      );
18884f3229d8S[email protected] 
18894f3229d8S[email protected]                         connection->state = SENT_CREATE_CONNECTION;
1890b2f949feS[email protected] #endif
18914f3229d8S[email protected]                         break;
18924f3229d8S[email protected]                 }
1893ad83dc6aS[email protected]                 return;
1894ad83dc6aS[email protected] 
18950bf6344aS[email protected]             case RECEIVED_CONNECTION_REQUEST:
18969da54300S[email protected]                 log_info("sending hci_accept_connection_request");
189732ab9390Smatthias.ringwald                 connection->state = ACCEPTED_CONNECTION_REQUEST;
189834d2123cS[email protected]                 hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1899dbe1a790S[email protected]                 return;
19000bf6344aS[email protected] 
1901a6725849S[email protected] #ifdef HAVE_BLE
19020bf6344aS[email protected]             case SEND_CANCEL_CONNECTION:
19030bf6344aS[email protected]                 connection->state = SENT_CANCEL_CONNECTION;
19040bf6344aS[email protected]                 hci_send_cmd(&hci_le_create_connection_cancel);
19050bf6344aS[email protected]                 return;
1906a6725849S[email protected] #endif
19070bf6344aS[email protected]             case SEND_DISCONNECT:
19080bf6344aS[email protected]                 connection->state = SENT_DISCONNECT;
19097851196eSmatthias.ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
19100bf6344aS[email protected]                 return;
19110bf6344aS[email protected] 
19120bf6344aS[email protected]             default:
19130bf6344aS[email protected]                 break;
1914c7e0c5f6Smatthias.ringwald         }
1915c7e0c5f6Smatthias.ringwald 
191632ab9390Smatthias.ringwald         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
19179da54300S[email protected]             log_info("responding to link key request");
191834d2123cS[email protected]             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
191932ab9390Smatthias.ringwald             link_key_t link_key;
1920c77e8838S[email protected]             link_key_type_t link_key_type;
19213a9fb326S[email protected]             if ( hci_stack->remote_device_db
19223a9fb326S[email protected]               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
192334d2123cS[email protected]               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
19249ab95c90S[email protected]                connection->link_key_type = link_key_type;
192532ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
192632ab9390Smatthias.ringwald             } else {
192732ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
192832ab9390Smatthias.ringwald             }
1929dbe1a790S[email protected]             return;
193032ab9390Smatthias.ringwald         }
19311d6b20aeS[email protected] 
1932899283eaS[email protected]         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
19339da54300S[email protected]             log_info("denying to pin request");
1934899283eaS[email protected]             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
193534d2123cS[email protected]             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
19364c57c146S[email protected]             return;
19374c57c146S[email protected]         }
19384c57c146S[email protected] 
1939dbe1a790S[email protected]         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
194034d2123cS[email protected]             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
194182d8f825S[email protected]             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
194282d8f825S[email protected]             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
1943106d6d11S[email protected]                 // tweak authentication requirements
19443a9fb326S[email protected]                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
1945106d6d11S[email protected]                 if (connection->bonding_flags & BONDING_DEDICATED){
19469faad3abS[email protected]                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
19479faad3abS[email protected]                 }
19489faad3abS[email protected]                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
19499faad3abS[email protected]                     authreq |= 1;
1950106d6d11S[email protected]                 }
19513a9fb326S[email protected]                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
1952f8fb5f6eS[email protected]             } else {
1953f8fb5f6eS[email protected]                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
1954f8fb5f6eS[email protected]             }
1955dbe1a790S[email protected]             return;
195632ab9390Smatthias.ringwald         }
195732ab9390Smatthias.ringwald 
1958dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1959dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
196034d2123cS[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1961dbe1a790S[email protected]             return;
1962dbe1a790S[email protected]         }
1963dbe1a790S[email protected] 
1964dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1965dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
196634d2123cS[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1967dbe1a790S[email protected]             return;
1968dbe1a790S[email protected]         }
1969afd4e962S[email protected] 
1970afd4e962S[email protected]         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
1971afd4e962S[email protected]             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
197234d2123cS[email protected]             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
19732bd8b7e7S[email protected]             return;
19742bd8b7e7S[email protected]         }
19752bd8b7e7S[email protected] 
19762bd8b7e7S[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
19772bd8b7e7S[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
197834d2123cS[email protected]             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
197934d2123cS[email protected]             return;
198034d2123cS[email protected]         }
1981ad83dc6aS[email protected]         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
1982ad83dc6aS[email protected]             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
19831bd5283dS[email protected]             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
198452d34f98S[email protected]             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
1985ad83dc6aS[email protected]             return;
1986ad83dc6aS[email protected]         }
198734d2123cS[email protected]         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
198834d2123cS[email protected]             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
198934d2123cS[email protected]             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
19902bd8b7e7S[email protected]             return;
1991afd4e962S[email protected]         }
1992dce78009S[email protected]         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
1993dce78009S[email protected]             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
1994dce78009S[email protected]             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
1995dce78009S[email protected]             return;
1996dce78009S[email protected]         }
1997da886c03S[email protected] 
1998c37a3166S[email protected] #ifdef HAVE_BLE
1999da886c03S[email protected]         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2000da886c03S[email protected]             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2001da886c03S[email protected] 
2002c37a3166S[email protected]             uint16_t connection_interval_min = connection->le_conn_interval_min;
2003c37a3166S[email protected]             connection->le_conn_interval_min = 0;
2004c37a3166S[email protected]             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2005c37a3166S[email protected]                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2006c37a3166S[email protected]                 0x0000, 0xffff);
2007c37a3166S[email protected]         }
2008c37a3166S[email protected] #endif
2009dbe1a790S[email protected]     }
2010c7e0c5f6Smatthias.ringwald 
20113a9fb326S[email protected]     switch (hci_stack->state){
20123429f56bSmatthias.ringwald         case HCI_STATE_INITIALIZING:
2013bd88fde9S[email protected]             hci_initializing_state_machine();
20143429f56bSmatthias.ringwald             break;
2015c7e0c5f6Smatthias.ringwald 
2016c7e0c5f6Smatthias.ringwald         case HCI_STATE_HALTING:
2017c7e0c5f6Smatthias.ringwald 
20189da54300S[email protected]             log_info("HCI_STATE_HALTING");
2019c7e0c5f6Smatthias.ringwald             // close all open connections
20203a9fb326S[email protected]             connection =  (hci_connection_t *) hci_stack->connections;
2021c7e0c5f6Smatthias.ringwald             if (connection){
202232ab9390Smatthias.ringwald 
2023c7e0c5f6Smatthias.ringwald                 // send disconnect
2024d94d3cafS[email protected]                 if (!hci_can_send_command_packet_now()) return;
202532ab9390Smatthias.ringwald 
20269da54300S[email protected]                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
20276ad890d3Smatthias.ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2028c7e0c5f6Smatthias.ringwald 
2029c7e0c5f6Smatthias.ringwald                 // send disconnected event right away - causes higher layer connections to get closed, too.
2030c7e0c5f6Smatthias.ringwald                 hci_shutdown_connection(connection);
2031c7e0c5f6Smatthias.ringwald                 return;
2032c7e0c5f6Smatthias.ringwald             }
20339da54300S[email protected]             log_info("HCI_STATE_HALTING, calling off");
2034c7e0c5f6Smatthias.ringwald 
203572ea5239Smatthias.ringwald             // switch mode
2036c7e0c5f6Smatthias.ringwald             hci_power_control_off();
20379418f9c9Smatthias.ringwald 
20389da54300S[email protected]             log_info("HCI_STATE_HALTING, emitting state");
203972ea5239Smatthias.ringwald             hci_emit_state();
20409da54300S[email protected]             log_info("HCI_STATE_HALTING, done");
204172ea5239Smatthias.ringwald             break;
2042c7e0c5f6Smatthias.ringwald 
204372ea5239Smatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
20443a9fb326S[email protected]             switch(hci_stack->substate) {
204589db417bSmatthias.ringwald                 case 0:
20469da54300S[email protected]                     log_info("HCI_STATE_FALLING_ASLEEP");
204772ea5239Smatthias.ringwald                     // close all open connections
20483a9fb326S[email protected]                     connection =  (hci_connection_t *) hci_stack->connections;
204966da7044Smatthias.ringwald 
205028171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
205166da7044Smatthias.ringwald                     // don't close connections, if H4 supports power management
205266da7044Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
205366da7044Smatthias.ringwald                         connection = NULL;
205466da7044Smatthias.ringwald                     }
205566da7044Smatthias.ringwald #endif
205672ea5239Smatthias.ringwald                     if (connection){
205732ab9390Smatthias.ringwald 
205872ea5239Smatthias.ringwald                         // send disconnect
2059d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
206032ab9390Smatthias.ringwald 
20619da54300S[email protected]                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
20626ad890d3Smatthias.ringwald                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
206372ea5239Smatthias.ringwald 
206472ea5239Smatthias.ringwald                         // send disconnected event right away - causes higher layer connections to get closed, too.
206572ea5239Smatthias.ringwald                         hci_shutdown_connection(connection);
206672ea5239Smatthias.ringwald                         return;
206772ea5239Smatthias.ringwald                     }
206872ea5239Smatthias.ringwald 
206992368cd3S[email protected]                     if (hci_classic_supported()){
207089db417bSmatthias.ringwald                         // disable page and inquiry scan
2071d94d3cafS[email protected]                         if (!hci_can_send_command_packet_now()) return;
207232ab9390Smatthias.ringwald 
20739da54300S[email protected]                         log_info("HCI_STATE_HALTING, disabling inq scans");
20743a9fb326S[email protected]                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
207589db417bSmatthias.ringwald 
207689db417bSmatthias.ringwald                         // continue in next sub state
20773a9fb326S[email protected]                         hci_stack->substate++;
207889db417bSmatthias.ringwald                         break;
207992368cd3S[email protected]                     }
208092368cd3S[email protected]                     // fall through for ble-only chips
208192368cd3S[email protected] 
208289db417bSmatthias.ringwald                 case 2:
20839da54300S[email protected]                     log_info("HCI_STATE_HALTING, calling sleep");
208428171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
208528171530Smatthias.ringwald                     // don't actually go to sleep, if H4 supports power management
208628171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
208728171530Smatthias.ringwald                         // SLEEP MODE reached
20883a9fb326S[email protected]                         hci_stack->state = HCI_STATE_SLEEPING;
208928171530Smatthias.ringwald                         hci_emit_state();
209028171530Smatthias.ringwald                         break;
209128171530Smatthias.ringwald                     }
209228171530Smatthias.ringwald #endif
209372ea5239Smatthias.ringwald                     // switch mode
20943a9fb326S[email protected]                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
2095c7e0c5f6Smatthias.ringwald                     hci_emit_state();
209628171530Smatthias.ringwald                     break;
209728171530Smatthias.ringwald 
209889db417bSmatthias.ringwald                 default:
209989db417bSmatthias.ringwald                     break;
210089db417bSmatthias.ringwald             }
2101c7e0c5f6Smatthias.ringwald             break;
2102c7e0c5f6Smatthias.ringwald 
21033429f56bSmatthias.ringwald         default:
21043429f56bSmatthias.ringwald             break;
21051f504dbdSmatthias.ringwald     }
21063429f56bSmatthias.ringwald }
210716833f0aSmatthias.ringwald 
210831452debSmatthias.ringwald int hci_send_cmd_packet(uint8_t *packet, int size){
2109c8e4258aSmatthias.ringwald     bd_addr_t addr;
2110c8e4258aSmatthias.ringwald     hci_connection_t * conn;
2111c8e4258aSmatthias.ringwald     // house-keeping
2112c8e4258aSmatthias.ringwald 
2113c8e4258aSmatthias.ringwald     // create_connection?
2114c8e4258aSmatthias.ringwald     if (IS_COMMAND(packet, hci_create_connection)){
2115c8e4258aSmatthias.ringwald         bt_flip_addr(addr, &packet[3]);
21169da54300S[email protected]         log_info("Create_connection to %s", bd_addr_to_str(addr));
2117c8e4258aSmatthias.ringwald 
211896a45072S[email protected]         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2119ad83dc6aS[email protected]         if (!conn){
212096a45072S[email protected]             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
212117f1ba2aSmatthias.ringwald             if (!conn){
212217f1ba2aSmatthias.ringwald                 // notify client that alloc failed
212317f1ba2aSmatthias.ringwald                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
212417f1ba2aSmatthias.ringwald                 return 0; // don't sent packet to controller
212517f1ba2aSmatthias.ringwald             }
2126ad83dc6aS[email protected]             conn->state = SEND_CREATE_CONNECTION;
2127ad83dc6aS[email protected]         }
2128ad83dc6aS[email protected]         log_info("conn state %u", conn->state);
2129ad83dc6aS[email protected]         switch (conn->state){
2130ad83dc6aS[email protected]             // if connection active exists
2131ad83dc6aS[email protected]             case OPEN:
213262bda3fbS[email protected]                 // and OPEN, emit connection complete command, don't send to controller
2133ad83dc6aS[email protected]                 hci_emit_connection_complete(conn, 0);
213462bda3fbS[email protected]                 return 0;
2135ad83dc6aS[email protected]             case SEND_CREATE_CONNECTION:
2136ad83dc6aS[email protected]                 // connection created by hci, e.g. dedicated bonding
2137ad83dc6aS[email protected]                 break;
2138ad83dc6aS[email protected]             default:
2139ad83dc6aS[email protected]                 // otherwise, just ignore as it is already in the open process
2140ad83dc6aS[email protected]                 return 0;
2141ad83dc6aS[email protected]         }
2142c8e4258aSmatthias.ringwald         conn->state = SENT_CREATE_CONNECTION;
2143c8e4258aSmatthias.ringwald     }
2144c8e4258aSmatthias.ringwald 
21457fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_reply)){
21467fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
21477fde4af9Smatthias.ringwald     }
21487fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
21497fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
21507fde4af9Smatthias.ringwald     }
21517fde4af9Smatthias.ringwald 
21528ef73945Smatthias.ringwald     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
21533a9fb326S[email protected]         if (hci_stack->remote_device_db){
21548ef73945Smatthias.ringwald             bt_flip_addr(addr, &packet[3]);
21553a9fb326S[email protected]             hci_stack->remote_device_db->delete_link_key(&addr);
21568ef73945Smatthias.ringwald         }
21578ef73945Smatthias.ringwald     }
2158c8e4258aSmatthias.ringwald 
21596724cd9eS[email protected]     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
21606724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
21616724cd9eS[email protected]         bt_flip_addr(addr, &packet[3]);
216296a45072S[email protected]         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
21636724cd9eS[email protected]         if (conn){
21646724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
21656724cd9eS[email protected]         }
21666724cd9eS[email protected]     }
21676724cd9eS[email protected] 
21686724cd9eS[email protected]     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
21696724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
21706724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
21716724cd9eS[email protected]     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
21726724cd9eS[email protected]         bt_flip_addr(addr, &packet[3]);
217396a45072S[email protected]         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
21746724cd9eS[email protected]         if (conn){
21756724cd9eS[email protected]             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
21766724cd9eS[email protected]         }
21776724cd9eS[email protected]     }
21786724cd9eS[email protected] 
217969a97523S[email protected] #ifdef HAVE_BLE
218069a97523S[email protected]     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
21813a9fb326S[email protected]         hci_stack->adv_addr_type = packet[8];
218269a97523S[email protected]     }
218369a97523S[email protected]     if (IS_COMMAND(packet, hci_le_set_random_address)){
21843a9fb326S[email protected]         bt_flip_addr(hci_stack->adv_address, &packet[3]);
218569a97523S[email protected]     }
218669a97523S[email protected] #endif
218769a97523S[email protected] 
21883a9fb326S[email protected]     hci_stack->num_cmd_packets--;
21895bb5bc3eS[email protected] 
21905bb5bc3eS[email protected]     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
21916b4af23dS[email protected]     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
21926b4af23dS[email protected] 
2193d051460cS[email protected]     // release packet buffer for synchronous transport implementations
2194c8b9416aS[email protected]     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
21956b4af23dS[email protected]         hci_stack->hci_packet_buffer_reserved = 0;
21966b4af23dS[email protected]     }
21976b4af23dS[email protected] 
21986b4af23dS[email protected]     return err;
219931452debSmatthias.ringwald }
22008adf0ddaSmatthias.ringwald 
22012bd8b7e7S[email protected] // disconnect because of security block
22022bd8b7e7S[email protected] void hci_disconnect_security_block(hci_con_handle_t con_handle){
22032bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
22042bd8b7e7S[email protected]     if (!connection) return;
22052bd8b7e7S[email protected]     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
22062bd8b7e7S[email protected] }
22072bd8b7e7S[email protected] 
22082bd8b7e7S[email protected] 
2209dbe1a790S[email protected] // Configure Secure Simple Pairing
2210dbe1a790S[email protected] 
2211dbe1a790S[email protected] // enable will enable SSP during init
2212dbe1a790S[email protected] void hci_ssp_set_enable(int enable){
22133a9fb326S[email protected]     hci_stack->ssp_enable = enable;
2214dbe1a790S[email protected] }
2215dbe1a790S[email protected] 
22162bd8b7e7S[email protected] int hci_local_ssp_activated(){
22173a9fb326S[email protected]     return hci_ssp_supported() && hci_stack->ssp_enable;
22182bd8b7e7S[email protected] }
22192bd8b7e7S[email protected] 
2220dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
2221dbe1a790S[email protected] void hci_ssp_set_io_capability(int io_capability){
22223a9fb326S[email protected]     hci_stack->ssp_io_capability = io_capability;
2223dbe1a790S[email protected] }
2224dbe1a790S[email protected] void hci_ssp_set_authentication_requirement(int authentication_requirement){
22253a9fb326S[email protected]     hci_stack->ssp_authentication_requirement = authentication_requirement;
2226dbe1a790S[email protected] }
2227dbe1a790S[email protected] 
2228dbe1a790S[email protected] // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2229dbe1a790S[email protected] void hci_ssp_set_auto_accept(int auto_accept){
22303a9fb326S[email protected]     hci_stack->ssp_auto_accept = auto_accept;
2231dbe1a790S[email protected] }
2232dbe1a790S[email protected] 
22331cd208adSmatthias.ringwald /**
22341cd208adSmatthias.ringwald  * pre: numcmds >= 0 - it's allowed to send a command to the controller
22351cd208adSmatthias.ringwald  */
2236fe35119dSmatthias.ringwald int hci_send_cmd(const hci_cmd_t *cmd, ...){
22375127cc62S[email protected] 
2238d94d3cafS[email protected]     if (!hci_can_send_command_packet_now()){
22399d14b626S[email protected]         log_error("hci_send_cmd called but cannot send packet now");
22409d14b626S[email protected]         return 0;
22419d14b626S[email protected]     }
22429d14b626S[email protected] 
22435127cc62S[email protected]     // for HCI INITIALIZATION
22449da54300S[email protected]     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
22455127cc62S[email protected]     hci_stack->last_cmd_opcode = cmd->opcode;
22465127cc62S[email protected] 
22479d14b626S[email protected]     hci_reserve_packet_buffer();
22489d14b626S[email protected]     uint8_t * packet = hci_stack->hci_packet_buffer;
22499d14b626S[email protected] 
22501cd208adSmatthias.ringwald     va_list argptr;
22511cd208adSmatthias.ringwald     va_start(argptr, cmd);
22529d14b626S[email protected]     uint16_t size = hci_create_cmd_internal(packet, cmd, argptr);
22531cd208adSmatthias.ringwald     va_end(argptr);
22549d14b626S[email protected] 
22559d14b626S[email protected]     return hci_send_cmd_packet(packet, size);
225693b8dc03Smatthias.ringwald }
2257c8e4258aSmatthias.ringwald 
2258ee091cf1Smatthias.ringwald // Create various non-HCI events.
2259ee091cf1Smatthias.ringwald // TODO: generalize, use table similar to hci_create_command
2260ee091cf1Smatthias.ringwald 
2261c8e4258aSmatthias.ringwald void hci_emit_state(){
22623a9fb326S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2263425d1371Smatthias.ringwald     uint8_t event[3];
226480d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
2265425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
22663a9fb326S[email protected]     event[2] = hci_stack->state;
2267425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
22683a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2269c8e4258aSmatthias.ringwald }
2270c8e4258aSmatthias.ringwald 
227117f1ba2aSmatthias.ringwald void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
2272425d1371Smatthias.ringwald     uint8_t event[13];
2273c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
2274425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
227517f1ba2aSmatthias.ringwald     event[2] = status;
2276c8e4258aSmatthias.ringwald     bt_store_16(event, 3, conn->con_handle);
2277c8e4258aSmatthias.ringwald     bt_flip_addr(&event[5], conn->address);
2278c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
2279c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
2280425d1371Smatthias.ringwald     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
22813a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2282c8e4258aSmatthias.ringwald }
2283c8e4258aSmatthias.ringwald 
22846e2e9a6bS[email protected] void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t * address, uint16_t conn_handle, uint8_t status){
22854f3229d8S[email protected]     uint8_t event[21];
22864f3229d8S[email protected]     event[0] = HCI_EVENT_LE_META;
22874f3229d8S[email protected]     event[1] = sizeof(event) - 2;
22884f3229d8S[email protected]     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
22894f3229d8S[email protected]     event[3] = status;
22906e2e9a6bS[email protected]     bt_store_16(event, 4, conn_handle);
22914f3229d8S[email protected]     event[6] = 0; // TODO: role
22926e2e9a6bS[email protected]     event[7] = address_type;
22936e2e9a6bS[email protected]     bt_flip_addr(&event[8], *address);
22944f3229d8S[email protected]     bt_store_16(event, 14, 0); // interval
22954f3229d8S[email protected]     bt_store_16(event, 16, 0); // latency
22964f3229d8S[email protected]     bt_store_16(event, 18, 0); // supervision timeout
22974f3229d8S[email protected]     event[20] = 0; // master clock accuracy
22984f3229d8S[email protected]     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
22994f3229d8S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
23004f3229d8S[email protected] }
23014f3229d8S[email protected] 
23023c4d4b90Smatthias.ringwald void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
2303425d1371Smatthias.ringwald     uint8_t event[6];
23043c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
2305e518c4b8Smatthias.ringwald     event[1] = sizeof(event) - 2;
23063c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
23073c4d4b90Smatthias.ringwald     bt_store_16(event, 3, handle);
23083c4d4b90Smatthias.ringwald     event[5] = reason;
2309425d1371Smatthias.ringwald     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
23103a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
23113c4d4b90Smatthias.ringwald }
23123c4d4b90Smatthias.ringwald 
2313ee091cf1Smatthias.ringwald void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
231466fb9560S[email protected]     if (disable_l2cap_timeouts) return;
2315e0abb8e7S[email protected]     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
2316425d1371Smatthias.ringwald     uint8_t event[4];
231780d52d6bSmatthias.ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
2318425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2319ee091cf1Smatthias.ringwald     bt_store_16(event, 2, conn->con_handle);
2320425d1371Smatthias.ringwald     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
23213a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2322ee091cf1Smatthias.ringwald }
232343bfb1bdSmatthias.ringwald 
232443bfb1bdSmatthias.ringwald void hci_emit_nr_connections_changed(){
2325e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
2326425d1371Smatthias.ringwald     uint8_t event[3];
232780d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
2328425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
232943bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
2330425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23313a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
233243bfb1bdSmatthias.ringwald }
2333038bc64cSmatthias.ringwald 
2334038bc64cSmatthias.ringwald void hci_emit_hci_open_failed(){
2335e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
2336425d1371Smatthias.ringwald     uint8_t event[2];
233780d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
2338425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2339425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23403a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2341038bc64cSmatthias.ringwald }
23421b0e3922Smatthias.ringwald 
234309ba8edeSmatthias.ringwald #ifndef EMBEDDED
23441b0e3922Smatthias.ringwald void hci_emit_btstack_version() {
2345e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
2346425d1371Smatthias.ringwald     uint8_t event[6];
23471b0e3922Smatthias.ringwald     event[0] = BTSTACK_EVENT_VERSION;
2348425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2349425d1371Smatthias.ringwald     event[2] = BTSTACK_MAJOR;
2350425d1371Smatthias.ringwald     event[3] = BTSTACK_MINOR;
2351425d1371Smatthias.ringwald     bt_store_16(event, 4, BTSTACK_REVISION);
2352425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23533a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
23541b0e3922Smatthias.ringwald }
235509ba8edeSmatthias.ringwald #endif
23561b0e3922Smatthias.ringwald 
23572ed6235cSmatthias.ringwald void hci_emit_system_bluetooth_enabled(uint8_t enabled){
2358e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
2359425d1371Smatthias.ringwald     uint8_t event[3];
23602ed6235cSmatthias.ringwald     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
2361425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
23622ed6235cSmatthias.ringwald     event[2] = enabled;
2363425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23643a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
23652ed6235cSmatthias.ringwald }
2366627c2f45Smatthias.ringwald 
2367627c2f45Smatthias.ringwald void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
2368e0abb8e7S[email protected]     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
2369627c2f45Smatthias.ringwald     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
2370e0abb8e7S[email protected]     event[1] = sizeof(event) - 2 - 1;
2371f653b6bdSmatthias.ringwald     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
23722f89d309Smatthias.ringwald     bt_flip_addr(&event[3], *addr);
2373f653b6bdSmatthias.ringwald     memcpy(&event[9], name, 248);
2374e0abb8e7S[email protected] 
2375e0abb8e7S[email protected]     event[9+248] = 0;   // assert \0 for log_info
2376e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2377e0abb8e7S[email protected] 
2378e0abb8e7S[email protected]     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
23793a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2380627c2f45Smatthias.ringwald }
2381381fbed8Smatthias.ringwald 
2382381fbed8Smatthias.ringwald void hci_emit_discoverable_enabled(uint8_t enabled){
2383e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2384425d1371Smatthias.ringwald     uint8_t event[3];
2385381fbed8Smatthias.ringwald     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2386425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
2387381fbed8Smatthias.ringwald     event[2] = enabled;
2388425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
23893a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2390381fbed8Smatthias.ringwald }
2391458bf4e8S[email protected] 
2392a00031e2S[email protected] void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2393df3354fcS[email protected]     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2394a00031e2S[email protected]     uint8_t event[5];
2395e00caf9cS[email protected]     int pos = 0;
2396a00031e2S[email protected]     event[pos++] = GAP_SECURITY_LEVEL;
2397e00caf9cS[email protected]     event[pos++] = sizeof(event) - 2;
2398a00031e2S[email protected]     bt_store_16(event, 2, con_handle);
2399e00caf9cS[email protected]     pos += 2;
2400e00caf9cS[email protected]     event[pos++] = level;
2401e00caf9cS[email protected]     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
24023a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2403e00caf9cS[email protected] }
2404e00caf9cS[email protected] 
24051bd5283dS[email protected] void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
2406ad83dc6aS[email protected]     log_info("hci_emit_dedicated_bonding_result %u ", status);
2407ad83dc6aS[email protected]     uint8_t event[9];
2408ad83dc6aS[email protected]     int pos = 0;
2409ad83dc6aS[email protected]     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2410ad83dc6aS[email protected]     event[pos++] = sizeof(event) - 2;
2411ad83dc6aS[email protected]     event[pos++] = status;
24121bd5283dS[email protected]     bt_flip_addr( * (bd_addr_t *) &event[pos], address);
2413ad83dc6aS[email protected]     pos += 6;
2414ad83dc6aS[email protected]     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
24153a9fb326S[email protected]     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2416ad83dc6aS[email protected] }
2417ad83dc6aS[email protected] 
24182bd8b7e7S[email protected] // query if remote side supports SSP
24192bd8b7e7S[email protected] int hci_remote_ssp_supported(hci_con_handle_t con_handle){
24202bd8b7e7S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
24212bd8b7e7S[email protected]     if (!connection) return 0;
24222bd8b7e7S[email protected]     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
24232bd8b7e7S[email protected] }
24242bd8b7e7S[email protected] 
2425df3354fcS[email protected] int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2426df3354fcS[email protected]     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2427df3354fcS[email protected] }
2428df3354fcS[email protected] 
2429458bf4e8S[email protected] // GAP API
2430458bf4e8S[email protected] /**
2431458bf4e8S[email protected]  * @bbrief enable/disable bonding. default is enabled
2432458bf4e8S[email protected]  * @praram enabled
2433458bf4e8S[email protected]  */
24344c57c146S[email protected] void gap_set_bondable_mode(int enable){
24353a9fb326S[email protected]     hci_stack->bondable = enable ? 1 : 0;
2436458bf4e8S[email protected] }
2437cb230b9dS[email protected] 
2438cb230b9dS[email protected] /**
243934d2123cS[email protected]  * @brief map link keys to security levels
2440cb230b9dS[email protected]  */
244134d2123cS[email protected] gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
244234d2123cS[email protected]     switch (link_key_type){
24433c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
24443c68dfa9S[email protected]             return LEVEL_4;
24453c68dfa9S[email protected]         case COMBINATION_KEY:
24463c68dfa9S[email protected]         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
24473c68dfa9S[email protected]             return LEVEL_3;
24483c68dfa9S[email protected]         default:
24493c68dfa9S[email protected]             return LEVEL_2;
24503c68dfa9S[email protected]     }
2451cb230b9dS[email protected] }
2452cb230b9dS[email protected] 
2453a00031e2S[email protected] static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
245434d2123cS[email protected]     if (!connection) return LEVEL_0;
245534d2123cS[email protected]     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
245634d2123cS[email protected]     return gap_security_level_for_link_key_type(connection->link_key_type);
245734d2123cS[email protected] }
245834d2123cS[email protected] 
245934d2123cS[email protected] 
2460106d6d11S[email protected] int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
24615127cc62S[email protected]     log_info("gap_mitm_protection_required_for_security_level %u", level);
2462106d6d11S[email protected]     return level > LEVEL_2;
2463106d6d11S[email protected] }
2464106d6d11S[email protected] 
246534d2123cS[email protected] /**
246634d2123cS[email protected]  * @brief get current security level
246734d2123cS[email protected]  */
246834d2123cS[email protected] gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
246934d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
247034d2123cS[email protected]     if (!connection) return LEVEL_0;
247134d2123cS[email protected]     return gap_security_level_for_connection(connection);
247234d2123cS[email protected] }
247334d2123cS[email protected] 
2474cb230b9dS[email protected] /**
2475cb230b9dS[email protected]  * @brief request connection to device to
2476cb230b9dS[email protected]  * @result GAP_AUTHENTICATION_RESULT
2477cb230b9dS[email protected]  */
247834d2123cS[email protected] void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
247934d2123cS[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
248034d2123cS[email protected]     if (!connection){
2481a00031e2S[email protected]         hci_emit_security_level(con_handle, LEVEL_0);
248234d2123cS[email protected]         return;
248334d2123cS[email protected]     }
248434d2123cS[email protected]     gap_security_level_t current_level = gap_security_level(con_handle);
248534d2123cS[email protected]     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
248634d2123cS[email protected]     if (current_level >= requested_level){
2487a00031e2S[email protected]         hci_emit_security_level(con_handle, current_level);
248834d2123cS[email protected]         return;
248934d2123cS[email protected]     }
2490a00031e2S[email protected] 
249134d2123cS[email protected]     connection->requested_security_level = requested_level;
2492a00031e2S[email protected] 
249325bf5872S[email protected] #if 0
249425bf5872S[email protected]     // sending encryption request without a link key results in an error.
249525bf5872S[email protected]     // TODO: figure out how to use it properly
249625bf5872S[email protected] 
2497fb8ba0dbS[email protected]     // would enabling ecnryption suffice (>= LEVEL_2)?
24983a9fb326S[email protected]     if (hci_stack->remote_device_db){
2499a00031e2S[email protected]         link_key_type_t link_key_type;
2500a00031e2S[email protected]         link_key_t      link_key;
25013a9fb326S[email protected]         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2502a00031e2S[email protected]             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2503a00031e2S[email protected]                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2504a00031e2S[email protected]                 return;
2505a00031e2S[email protected]             }
2506a00031e2S[email protected]         }
2507a00031e2S[email protected]     }
250825bf5872S[email protected] #endif
2509a00031e2S[email protected] 
25101eb2563eS[email protected]     // try to authenticate connection
25111eb2563eS[email protected]     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2512e80b2cf9S[email protected]     hci_run();
2513e00caf9cS[email protected] }
2514ad83dc6aS[email protected] 
2515ad83dc6aS[email protected] /**
2516ad83dc6aS[email protected]  * @brief start dedicated bonding with device. disconnect after bonding
2517ad83dc6aS[email protected]  * @param device
2518ad83dc6aS[email protected]  * @param request MITM protection
2519ad83dc6aS[email protected]  * @result GAP_DEDICATED_BONDING_COMPLETE
2520ad83dc6aS[email protected]  */
2521ad83dc6aS[email protected] int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2522ad83dc6aS[email protected] 
2523ad83dc6aS[email protected]     // create connection state machine
252496a45072S[email protected]     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2525ad83dc6aS[email protected] 
2526ad83dc6aS[email protected]     if (!connection){
2527ad83dc6aS[email protected]         return BTSTACK_MEMORY_ALLOC_FAILED;
2528ad83dc6aS[email protected]     }
2529ad83dc6aS[email protected] 
2530ad83dc6aS[email protected]     // delete linkn key
2531ad83dc6aS[email protected]     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2532ad83dc6aS[email protected] 
2533ad83dc6aS[email protected]     // configure LEVEL_2/3, dedicated bonding
2534ad83dc6aS[email protected]     connection->state = SEND_CREATE_CONNECTION;
2535ad83dc6aS[email protected]     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
25365127cc62S[email protected]     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
2537ad83dc6aS[email protected]     connection->bonding_flags = BONDING_DEDICATED;
2538ad83dc6aS[email protected] 
2539ad83dc6aS[email protected]     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2540ad83dc6aS[email protected] 
2541ad83dc6aS[email protected]     // handle: connnection failure (connection complete != ok)
2542ad83dc6aS[email protected]     // handle: authentication failure
2543ad83dc6aS[email protected]     // handle: disconnect on done
2544ad83dc6aS[email protected] 
2545ad83dc6aS[email protected]     hci_run();
2546ad83dc6aS[email protected] 
2547ad83dc6aS[email protected]     return 0;
2548ad83dc6aS[email protected] }
25498e618f72S[email protected] 
25508e618f72S[email protected] void gap_set_local_name(const char * local_name){
25518e618f72S[email protected]     hci_stack->local_name = local_name;
25528e618f72S[email protected] }
25538e618f72S[email protected] 
25547bdc6798S[email protected] le_command_status_t le_central_start_scan(){
255536af3e18S[email protected]     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
25567bdc6798S[email protected]     hci_stack->le_scanning_state = LE_START_SCAN;
25577bdc6798S[email protected]     hci_run();
25587bdc6798S[email protected]     return BLE_PERIPHERAL_OK;
25597bdc6798S[email protected] }
25608e618f72S[email protected] 
25617bdc6798S[email protected] le_command_status_t le_central_stop_scan(){
256236af3e18S[email protected]     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
25637bdc6798S[email protected]     hci_stack->le_scanning_state = LE_STOP_SCAN;
25647bdc6798S[email protected]     hci_run();
25657bdc6798S[email protected]     return BLE_PERIPHERAL_OK;
25667bdc6798S[email protected] }
25674f3229d8S[email protected] 
2568ef11999fSmatthias.ringwald void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
2569ef11999fSmatthias.ringwald     hci_stack->le_scan_type     = scan_type;
2570ef11999fSmatthias.ringwald     hci_stack->le_scan_interval = scan_interval;
2571ef11999fSmatthias.ringwald     hci_stack->le_scan_window   = scan_window;
2572ef11999fSmatthias.ringwald     hci_run();
2573ef11999fSmatthias.ringwald }
25744f3229d8S[email protected] 
25754f3229d8S[email protected] le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
25764f3229d8S[email protected]     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
25774f3229d8S[email protected]     if (!conn){
25781f479f8cS[email protected]         log_info("le_central_connect: no connection exists yet, creating context");
25794f3229d8S[email protected]         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
25804f3229d8S[email protected]         if (!conn){
25814f3229d8S[email protected]             // notify client that alloc failed
25826e2e9a6bS[email protected]             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
25836e2e9a6bS[email protected]             log_info("le_central_connect: failed to alloc hci_connection_t");
25844f3229d8S[email protected]             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
25854f3229d8S[email protected]         }
25864f3229d8S[email protected]         conn->state = SEND_CREATE_CONNECTION;
25871f479f8cS[email protected]         log_info("le_central_connect: send create connection next");
2588564fca32S[email protected]         hci_run();
25894f3229d8S[email protected]         return BLE_PERIPHERAL_OK;
25904f3229d8S[email protected]     }
25910bf6344aS[email protected] 
25920bf6344aS[email protected]     if (!hci_is_le_connection(conn) ||
25930bf6344aS[email protected]         conn->state == SEND_CREATE_CONNECTION ||
25940bf6344aS[email protected]         conn->state == SENT_CREATE_CONNECTION) {
25956e2e9a6bS[email protected]         hci_emit_le_connection_complete(conn->address_type, &conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
25961f479f8cS[email protected]         log_error("le_central_connect: classic connection or connect is already being created");
25970bf6344aS[email protected]         return BLE_PERIPHERAL_IN_WRONG_STATE;
25980bf6344aS[email protected]     }
25990bf6344aS[email protected] 
26001f479f8cS[email protected]     log_info("le_central_connect: context exists with state %u", conn->state);
26016e2e9a6bS[email protected]     hci_emit_le_connection_complete(conn->address_type, &conn->address, conn->con_handle, 0);
26024f3229d8S[email protected]     hci_run();
26034f3229d8S[email protected]     return BLE_PERIPHERAL_OK;
26044f3229d8S[email protected] }
26054f3229d8S[email protected] 
26067851196eSmatthias.ringwald // @assumption: only a single outgoing LE Connection exists
26077851196eSmatthias.ringwald static hci_connection_t * le_central_get_outgoing_connection(){
26080bf6344aS[email protected]     linked_item_t *it;
26090bf6344aS[email protected]     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
26100bf6344aS[email protected]         hci_connection_t * conn = (hci_connection_t *) it;
26110bf6344aS[email protected]         if (!hci_is_le_connection(conn)) continue;
26120bf6344aS[email protected]         switch (conn->state){
2613a6725849S[email protected]             case SEND_CREATE_CONNECTION:
26147851196eSmatthias.ringwald             case SENT_CREATE_CONNECTION:
26157851196eSmatthias.ringwald                 return conn;
26167851196eSmatthias.ringwald             default:
26177851196eSmatthias.ringwald                 break;
26187851196eSmatthias.ringwald         };
26197851196eSmatthias.ringwald     }
26207851196eSmatthias.ringwald     return NULL;
26217851196eSmatthias.ringwald }
26227851196eSmatthias.ringwald 
26237851196eSmatthias.ringwald le_command_status_t le_central_connect_cancel(){
26247851196eSmatthias.ringwald     hci_connection_t * conn = le_central_get_outgoing_connection();
26257851196eSmatthias.ringwald     switch (conn->state){
26267851196eSmatthias.ringwald         case SEND_CREATE_CONNECTION:
26277851196eSmatthias.ringwald             // skip sending create connection and emit event instead
26286e2e9a6bS[email protected]             hci_emit_le_connection_complete(conn->address_type, &conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
26297851196eSmatthias.ringwald             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
26307851196eSmatthias.ringwald             btstack_memory_hci_connection_free( conn );
26310bf6344aS[email protected]             break;
2632a6725849S[email protected]         case SENT_CREATE_CONNECTION:
26337851196eSmatthias.ringwald             // request to send cancel connection
26340bf6344aS[email protected]             conn->state = SEND_CANCEL_CONNECTION;
26350bf6344aS[email protected]             hci_run();
26360bf6344aS[email protected]             break;
26370bf6344aS[email protected]         default:
26380bf6344aS[email protected]             break;
26390bf6344aS[email protected]     }
2640e31f89a7S[email protected]     return BLE_PERIPHERAL_OK;
2641e31f89a7S[email protected] }
26424f3229d8S[email protected] 
2643c37a3166S[email protected] /**
2644c37a3166S[email protected]  * @brief Updates the connection parameters for a given LE connection
2645c37a3166S[email protected]  * @param handle
2646c37a3166S[email protected]  * @param conn_interval_min (unit: 1.25ms)
2647c37a3166S[email protected]  * @param conn_interval_max (unit: 1.25ms)
2648c37a3166S[email protected]  * @param conn_latency
2649c37a3166S[email protected]  * @param supervision_timeout (unit: 10ms)
2650c37a3166S[email protected]  * @returns 0 if ok
2651c37a3166S[email protected]  */
2652c37a3166S[email protected] int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
2653c37a3166S[email protected]     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
2654c37a3166S[email protected]     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2655c37a3166S[email protected]     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2656c37a3166S[email protected]     connection->le_conn_interval_min = conn_interval_min;
2657c37a3166S[email protected]     connection->le_conn_interval_max = conn_interval_max;
2658c37a3166S[email protected]     connection->le_conn_latency = conn_latency;
2659c37a3166S[email protected]     connection->le_supervision_timeout = supervision_timeout;
2660c37a3166S[email protected]     return 0;
2661c37a3166S[email protected] }
2662c37a3166S[email protected] 
26635917a5c5S[email protected] le_command_status_t gap_disconnect(hci_con_handle_t handle){
26645917a5c5S[email protected]     hci_connection_t * conn = hci_connection_for_handle(handle);
26655917a5c5S[email protected]     if (!conn){
26667851196eSmatthias.ringwald         hci_emit_disconnection_complete(handle, 0);
26675917a5c5S[email protected]         return BLE_PERIPHERAL_OK;
26685917a5c5S[email protected]     }
26695917a5c5S[email protected]     conn->state = SEND_DISCONNECT;
26705917a5c5S[email protected]     hci_run();
26714f3229d8S[email protected]     return BLE_PERIPHERAL_OK;
26724f3229d8S[email protected] }
267304a6ef8cSmatthias.ringwald 
267404a6ef8cSmatthias.ringwald void hci_disconnect_all(){
267504a6ef8cSmatthias.ringwald     linked_list_iterator_t it;
267604a6ef8cSmatthias.ringwald     linked_list_iterator_init(&it, &hci_stack->connections);
267704a6ef8cSmatthias.ringwald     while (linked_list_iterator_has_next(&it)){
267804a6ef8cSmatthias.ringwald         hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it);
267904a6ef8cSmatthias.ringwald         if (con->state == SENT_DISCONNECT) continue;
268004a6ef8cSmatthias.ringwald         con->state = SEND_DISCONNECT;
268104a6ef8cSmatthias.ringwald     }
2682d31fba26S[email protected]     hci_run();
268304a6ef8cSmatthias.ringwald }
2684