xref: /btstack/src/hci.c (revision 92368cd38418a93e42de57cbdef7e8daf4fc22cc)
11f504dbdSmatthias.ringwald /*
26b64433eSmatthias.ringwald  * Copyright (C) 2009-2012 by Matthias Ringwald
31713bceaSmatthias.ringwald  *
41713bceaSmatthias.ringwald  * Redistribution and use in source and binary forms, with or without
51713bceaSmatthias.ringwald  * modification, are permitted provided that the following conditions
61713bceaSmatthias.ringwald  * are met:
71713bceaSmatthias.ringwald  *
81713bceaSmatthias.ringwald  * 1. Redistributions of source code must retain the above copyright
91713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer.
101713bceaSmatthias.ringwald  * 2. Redistributions in binary form must reproduce the above copyright
111713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer in the
121713bceaSmatthias.ringwald  *    documentation and/or other materials provided with the distribution.
131713bceaSmatthias.ringwald  * 3. Neither the name of the copyright holders nor the names of
141713bceaSmatthias.ringwald  *    contributors may be used to endorse or promote products derived
151713bceaSmatthias.ringwald  *    from this software without specific prior written permission.
166b64433eSmatthias.ringwald  * 4. Any redistribution, use, or modification is done solely for
176b64433eSmatthias.ringwald  *    personal benefit and not for any commercial purpose or for
186b64433eSmatthias.ringwald  *    monetary gain.
191713bceaSmatthias.ringwald  *
201713bceaSmatthias.ringwald  * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS
211713bceaSmatthias.ringwald  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
221713bceaSmatthias.ringwald  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
231713bceaSmatthias.ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
241713bceaSmatthias.ringwald  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
251713bceaSmatthias.ringwald  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
261713bceaSmatthias.ringwald  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
271713bceaSmatthias.ringwald  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
281713bceaSmatthias.ringwald  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
291713bceaSmatthias.ringwald  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
301713bceaSmatthias.ringwald  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311713bceaSmatthias.ringwald  * SUCH DAMAGE.
321713bceaSmatthias.ringwald  *
336b64433eSmatthias.ringwald  * Please inquire about commercial licensing options at [email protected]
346b64433eSmatthias.ringwald  *
351713bceaSmatthias.ringwald  */
361713bceaSmatthias.ringwald 
371713bceaSmatthias.ringwald /*
381f504dbdSmatthias.ringwald  *  hci.c
391f504dbdSmatthias.ringwald  *
401f504dbdSmatthias.ringwald  *  Created by Matthias Ringwald on 4/29/09.
411f504dbdSmatthias.ringwald  *
421f504dbdSmatthias.ringwald  */
431f504dbdSmatthias.ringwald 
44c8901d41Smatthias.ringwald #include "config.h"
4528171530Smatthias.ringwald 
467f2435e6Smatthias.ringwald #include "hci.h"
477f2435e6Smatthias.ringwald 
4893b8dc03Smatthias.ringwald #include <stdarg.h>
4993b8dc03Smatthias.ringwald #include <string.h>
5056fe0872Smatthias.ringwald #include <stdio.h>
517f2435e6Smatthias.ringwald 
52549e6ebeSmatthias.ringwald #ifndef EMBEDDED
53549e6ebeSmatthias.ringwald #include <unistd.h> // gethostbyname
5409ba8edeSmatthias.ringwald #include <btstack/version.h>
55549e6ebeSmatthias.ringwald #endif
56549e6ebeSmatthias.ringwald 
57a3b02b71Smatthias.ringwald #include "btstack_memory.h"
587f2435e6Smatthias.ringwald #include "debug.h"
59d8905019Smatthias.ringwald #include "hci_dump.h"
6093b8dc03Smatthias.ringwald 
61ae1fd9f3Smatthias.ringwald #include <btstack/hci_cmds.h>
621b0e3922Smatthias.ringwald 
63169f8b28Smatthias.ringwald #define HCI_CONNECTION_TIMEOUT_MS 10000
64ee091cf1Smatthias.ringwald 
65a45d6b9fS[email protected] #define HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP 11
66da5275c5S[email protected] 
6728171530Smatthias.ringwald #ifdef USE_BLUETOOL
6828171530Smatthias.ringwald #include "bt_control_iphone.h"
6928171530Smatthias.ringwald #endif
7028171530Smatthias.ringwald 
71758b46ceSmatthias.ringwald static void hci_update_scan_enable(void);
72758b46ceSmatthias.ringwald 
7306b35ec0Smatthias.ringwald // the STACK is here
7416833f0aSmatthias.ringwald static hci_stack_t       hci_stack;
7516833f0aSmatthias.ringwald 
7697addcc5Smatthias.ringwald /**
77ee091cf1Smatthias.ringwald  * get connection for a given handle
78ee091cf1Smatthias.ringwald  *
79ee091cf1Smatthias.ringwald  * @return connection OR NULL, if not found
80ee091cf1Smatthias.ringwald  */
81645658c9Smatthias.ringwald hci_connection_t * connection_for_handle(hci_con_handle_t con_handle){
82ee091cf1Smatthias.ringwald     linked_item_t *it;
83ee091cf1Smatthias.ringwald     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
84ee091cf1Smatthias.ringwald         if ( ((hci_connection_t *) it)->con_handle == con_handle){
85ee091cf1Smatthias.ringwald             return (hci_connection_t *) it;
86ee091cf1Smatthias.ringwald         }
87ee091cf1Smatthias.ringwald     }
88ee091cf1Smatthias.ringwald     return NULL;
89ee091cf1Smatthias.ringwald }
90ee091cf1Smatthias.ringwald 
912b12a0b9Smatthias.ringwald static void hci_connection_timeout_handler(timer_source_t *timer){
9228ca2b46S[email protected]     hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item);
93c785ef68Smatthias.ringwald #ifdef HAVE_TIME
94ee091cf1Smatthias.ringwald     struct timeval tv;
95ee091cf1Smatthias.ringwald     gettimeofday(&tv, NULL);
96c21e6239Smatthias.ringwald     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
97ee091cf1Smatthias.ringwald         // connections might be timed out
98ee091cf1Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
99ee091cf1Smatthias.ringwald     }
1002b12a0b9Smatthias.ringwald #endif
101e5780900Smatthias.ringwald #ifdef HAVE_TICK
102c785ef68Smatthias.ringwald     if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
103c785ef68Smatthias.ringwald         // connections might be timed out
104c785ef68Smatthias.ringwald         hci_emit_l2cap_check_timeout(connection);
105c785ef68Smatthias.ringwald     }
106c785ef68Smatthias.ringwald #endif
107c785ef68Smatthias.ringwald     run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
108c785ef68Smatthias.ringwald     run_loop_add_timer(timer);
109c785ef68Smatthias.ringwald }
110ee091cf1Smatthias.ringwald 
111ee091cf1Smatthias.ringwald static void hci_connection_timestamp(hci_connection_t *connection){
112c7492964Smatthias.ringwald #ifdef HAVE_TIME
113ee091cf1Smatthias.ringwald     gettimeofday(&connection->timestamp, NULL);
114c7492964Smatthias.ringwald #endif
115e5780900Smatthias.ringwald #ifdef HAVE_TICK
116c785ef68Smatthias.ringwald     connection->timestamp = embedded_get_ticks();
117c785ef68Smatthias.ringwald #endif
118ee091cf1Smatthias.ringwald }
119ee091cf1Smatthias.ringwald 
120ee091cf1Smatthias.ringwald /**
121c8e4258aSmatthias.ringwald  * create connection for given address
122c8e4258aSmatthias.ringwald  *
12317f1ba2aSmatthias.ringwald  * @return connection OR NULL, if no memory left
124c8e4258aSmatthias.ringwald  */
125c8e4258aSmatthias.ringwald static hci_connection_t * create_connection_for_addr(bd_addr_t addr){
12628ca2b46S[email protected]     hci_connection_t * conn = (hci_connection_t *) btstack_memory_hci_connection_get();
127c8e4258aSmatthias.ringwald     if (!conn) return NULL;
128c8e4258aSmatthias.ringwald     BD_ADDR_COPY(conn->address, addr);
129c8e4258aSmatthias.ringwald     conn->con_handle = 0xffff;
1307d3b3569Smatthias.ringwald     conn->authentication_flags = AUTH_FLAGS_NONE;
131ee091cf1Smatthias.ringwald     linked_item_set_user(&conn->timeout.item, conn);
132ee091cf1Smatthias.ringwald     conn->timeout.process = hci_connection_timeout_handler;
133ee091cf1Smatthias.ringwald     hci_connection_timestamp(conn);
134d55db49eSmatthias.ringwald     conn->acl_recombination_length = 0;
1357856c818Smatthias.ringwald     conn->acl_recombination_pos = 0;
13656cf178bSmatthias.ringwald     conn->num_acl_packets_sent = 0;
137c8e4258aSmatthias.ringwald     linked_list_add(&hci_stack.connections, (linked_item_t *) conn);
138c8e4258aSmatthias.ringwald     return conn;
139c8e4258aSmatthias.ringwald }
140c8e4258aSmatthias.ringwald 
141c8e4258aSmatthias.ringwald /**
14206b35ec0Smatthias.ringwald  * get connection for given address
14397addcc5Smatthias.ringwald  *
14497addcc5Smatthias.ringwald  * @return connection OR NULL, if not found
14597addcc5Smatthias.ringwald  */
146fe1ed1b8Smatthias.ringwald static hci_connection_t * connection_for_address(bd_addr_t address){
14706b35ec0Smatthias.ringwald     linked_item_t *it;
14806b35ec0Smatthias.ringwald     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
14906b35ec0Smatthias.ringwald         if ( ! BD_ADDR_CMP( ((hci_connection_t *) it)->address, address) ){
15006b35ec0Smatthias.ringwald             return (hci_connection_t *) it;
15106b35ec0Smatthias.ringwald         }
15206b35ec0Smatthias.ringwald     }
15306b35ec0Smatthias.ringwald     return NULL;
15406b35ec0Smatthias.ringwald }
15506b35ec0Smatthias.ringwald 
15628ca2b46S[email protected] inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
15728ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
15828ca2b46S[email protected] }
15928ca2b46S[email protected] 
16028ca2b46S[email protected] inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
16128ca2b46S[email protected]     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
16228ca2b46S[email protected] }
16328ca2b46S[email protected] 
16428ca2b46S[email protected] 
16543bfb1bdSmatthias.ringwald /**
16680ca58a0Smatthias.ringwald  * add authentication flags and reset timer
1677fde4af9Smatthias.ringwald  */
1687fde4af9Smatthias.ringwald static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
1697fde4af9Smatthias.ringwald     bd_addr_t addr;
1707fde4af9Smatthias.ringwald     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
1717fde4af9Smatthias.ringwald     hci_connection_t * conn = connection_for_address(addr);
1727fde4af9Smatthias.ringwald     if (conn) {
17328ca2b46S[email protected]         connectionSetAuthenticationFlags(conn, flags);
17480ca58a0Smatthias.ringwald         hci_connection_timestamp(conn);
1757fde4af9Smatthias.ringwald     }
1767fde4af9Smatthias.ringwald }
1777fde4af9Smatthias.ringwald 
17880ca58a0Smatthias.ringwald int  hci_authentication_active_for_handle(hci_con_handle_t handle){
17980ca58a0Smatthias.ringwald     hci_connection_t * conn = connection_for_handle(handle);
18080ca58a0Smatthias.ringwald     if (!conn) return 0;
18180ca58a0Smatthias.ringwald     if (!conn->authentication_flags) return 0;
18280ca58a0Smatthias.ringwald     if (conn->authentication_flags & SENT_LINK_KEY_REPLY) return 0;
18380ca58a0Smatthias.ringwald     if (conn->authentication_flags & RECV_LINK_KEY_NOTIFICATION) return 0;
18480ca58a0Smatthias.ringwald     return 1;
18580ca58a0Smatthias.ringwald }
18680ca58a0Smatthias.ringwald 
187c12e46e7Smatthias.ringwald void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
188c12e46e7Smatthias.ringwald     if (hci_stack.remote_device_db) {
189c12e46e7Smatthias.ringwald         hci_stack.remote_device_db->delete_link_key(addr);
190c12e46e7Smatthias.ringwald     }
191c12e46e7Smatthias.ringwald }
192c12e46e7Smatthias.ringwald 
1937fde4af9Smatthias.ringwald 
1947fde4af9Smatthias.ringwald /**
19543bfb1bdSmatthias.ringwald  * count connections
19643bfb1bdSmatthias.ringwald  */
19740d1c7a4Smatthias.ringwald static int nr_hci_connections(void){
19856c253c9Smatthias.ringwald     int count = 0;
19943bfb1bdSmatthias.ringwald     linked_item_t *it;
20043bfb1bdSmatthias.ringwald     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next, count++);
20143bfb1bdSmatthias.ringwald     return count;
20243bfb1bdSmatthias.ringwald }
203c8e4258aSmatthias.ringwald 
20497addcc5Smatthias.ringwald /**
205ba681a6cSmatthias.ringwald  * Dummy handler called by HCI
20616833f0aSmatthias.ringwald  */
2072718e2e7Smatthias.ringwald static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
20816833f0aSmatthias.ringwald }
20916833f0aSmatthias.ringwald 
210998906cdSmatthias.ringwald uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
211998906cdSmatthias.ringwald     hci_connection_t * connection = connection_for_handle(handle);
212998906cdSmatthias.ringwald     if (!connection) {
2137d67539fSmatthias.ringwald         log_error("hci_number_outgoing_packets connectino for handle %u does not exist!\n", handle);
214998906cdSmatthias.ringwald         return 0;
215998906cdSmatthias.ringwald     }
216998906cdSmatthias.ringwald     return connection->num_acl_packets_sent;
217998906cdSmatthias.ringwald }
218998906cdSmatthias.ringwald 
219998906cdSmatthias.ringwald uint8_t hci_number_free_acl_slots(){
220998906cdSmatthias.ringwald     uint8_t free_slots = hci_stack.total_num_acl_packets;
221998906cdSmatthias.ringwald     linked_item_t *it;
222998906cdSmatthias.ringwald     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
223998906cdSmatthias.ringwald         hci_connection_t * connection = (hci_connection_t *) it;
224998906cdSmatthias.ringwald         if (free_slots < connection->num_acl_packets_sent) {
2257d67539fSmatthias.ringwald             log_error("hci_number_free_acl_slots: sum of outgoing packets > total acl packets!\n");
226998906cdSmatthias.ringwald             return 0;
227998906cdSmatthias.ringwald         }
228998906cdSmatthias.ringwald         free_slots -= connection->num_acl_packets_sent;
229998906cdSmatthias.ringwald     }
230998906cdSmatthias.ringwald     return free_slots;
231998906cdSmatthias.ringwald }
232998906cdSmatthias.ringwald 
233c24735b1Smatthias.ringwald int hci_can_send_packet_now(uint8_t packet_type){
2342b12a0b9Smatthias.ringwald 
2352b12a0b9Smatthias.ringwald     // check for async hci transport implementations
2362b12a0b9Smatthias.ringwald     if (hci_stack.hci_transport->can_send_packet_now){
2372b12a0b9Smatthias.ringwald         if (!hci_stack.hci_transport->can_send_packet_now(packet_type)){
2382b12a0b9Smatthias.ringwald             return 0;
2392b12a0b9Smatthias.ringwald         }
2402b12a0b9Smatthias.ringwald     }
2412b12a0b9Smatthias.ringwald 
2422b12a0b9Smatthias.ringwald     // check regular Bluetooth flow control
243c24735b1Smatthias.ringwald     switch (packet_type) {
244c24735b1Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
245c24735b1Smatthias.ringwald             return hci_number_free_acl_slots();
246c24735b1Smatthias.ringwald         case HCI_COMMAND_DATA_PACKET:
247de009a8cSmatthias.ringwald             return hci_stack.num_cmd_packets;
248c24735b1Smatthias.ringwald         default:
249c24735b1Smatthias.ringwald             return 0;
250c24735b1Smatthias.ringwald     }
251c24735b1Smatthias.ringwald }
252c24735b1Smatthias.ringwald 
253ee091cf1Smatthias.ringwald int hci_send_acl_packet(uint8_t *packet, int size){
2547856c818Smatthias.ringwald 
2556218e6f1Smatthias.ringwald     // check for free places on BT module
2565932f1b4Smatthias.ringwald     if (!hci_number_free_acl_slots()) return BTSTACK_ACL_BUFFERS_FULL;
2576218e6f1Smatthias.ringwald 
2587856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
2597856c818Smatthias.ringwald     hci_connection_t *connection = connection_for_handle( con_handle);
26056cf178bSmatthias.ringwald     if (!connection) return 0;
26156cf178bSmatthias.ringwald     hci_connection_timestamp(connection);
26256cf178bSmatthias.ringwald 
26356cf178bSmatthias.ringwald     // count packet
26456cf178bSmatthias.ringwald     connection->num_acl_packets_sent++;
2657b5fbe1fSmatthias.ringwald     // log_info("hci_send_acl_packet - handle %u, sent %u\n", connection->con_handle, connection->num_acl_packets_sent);
2667856c818Smatthias.ringwald 
26700d8e42eSmatthias.ringwald     // send packet
26800d8e42eSmatthias.ringwald     int err = hci_stack.hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
2696218e6f1Smatthias.ringwald 
27000d8e42eSmatthias.ringwald     return err;
271ee091cf1Smatthias.ringwald }
272ee091cf1Smatthias.ringwald 
27316833f0aSmatthias.ringwald static void acl_handler(uint8_t *packet, int size){
2747856c818Smatthias.ringwald 
2757856c818Smatthias.ringwald     // get info
2767856c818Smatthias.ringwald     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
2777856c818Smatthias.ringwald     hci_connection_t *conn      = connection_for_handle(con_handle);
2787856c818Smatthias.ringwald     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
2797856c818Smatthias.ringwald     uint16_t acl_length         = READ_ACL_LENGTH(packet);
2807856c818Smatthias.ringwald 
2817856c818Smatthias.ringwald     // ignore non-registered handle
2827856c818Smatthias.ringwald     if (!conn){
2837d67539fSmatthias.ringwald         log_error( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle);
2847856c818Smatthias.ringwald         return;
2857856c818Smatthias.ringwald     }
2867856c818Smatthias.ringwald 
2877856c818Smatthias.ringwald     // update idle timestamp
2887856c818Smatthias.ringwald     hci_connection_timestamp(conn);
2897856c818Smatthias.ringwald 
2907856c818Smatthias.ringwald     // handle different packet types
2917856c818Smatthias.ringwald     switch (acl_flags & 0x03) {
2927856c818Smatthias.ringwald 
2937856c818Smatthias.ringwald         case 0x01: // continuation fragment
2947856c818Smatthias.ringwald 
2957856c818Smatthias.ringwald             // sanity check
2967856c818Smatthias.ringwald             if (conn->acl_recombination_pos == 0) {
2977d67539fSmatthias.ringwald                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle);
2987856c818Smatthias.ringwald                 return;
2997856c818Smatthias.ringwald             }
3007856c818Smatthias.ringwald 
3017856c818Smatthias.ringwald             // append fragment payload (header already stored)
3027856c818Smatthias.ringwald             memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length );
3037856c818Smatthias.ringwald             conn->acl_recombination_pos += acl_length;
3047856c818Smatthias.ringwald 
3057d67539fSmatthias.ringwald             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n", acl_length,
306decc01a8Smatthias.ringwald             //        conn->acl_recombination_pos, conn->acl_recombination_length);
3077856c818Smatthias.ringwald 
3087856c818Smatthias.ringwald             // forward complete L2CAP packet if complete.
3097856c818Smatthias.ringwald             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
3107856c818Smatthias.ringwald 
3112718e2e7Smatthias.ringwald                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos);
3127856c818Smatthias.ringwald                 // reset recombination buffer
3137856c818Smatthias.ringwald                 conn->acl_recombination_length = 0;
3147856c818Smatthias.ringwald                 conn->acl_recombination_pos = 0;
3157856c818Smatthias.ringwald             }
3167856c818Smatthias.ringwald             break;
3177856c818Smatthias.ringwald 
3187856c818Smatthias.ringwald         case 0x02: { // first fragment
3197856c818Smatthias.ringwald 
3207856c818Smatthias.ringwald             // sanity check
3217856c818Smatthias.ringwald             if (conn->acl_recombination_pos) {
3227d67539fSmatthias.ringwald                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle);
3237856c818Smatthias.ringwald                 return;
3247856c818Smatthias.ringwald             }
3257856c818Smatthias.ringwald 
3267856c818Smatthias.ringwald             // peek into L2CAP packet!
3277856c818Smatthias.ringwald             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
3287856c818Smatthias.ringwald 
3297d67539fSmatthias.ringwald             // log_error( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length);
330decc01a8Smatthias.ringwald 
3317856c818Smatthias.ringwald             // compare fragment size to L2CAP packet size
3327856c818Smatthias.ringwald             if (acl_length >= l2cap_length + 4){
3337856c818Smatthias.ringwald 
3347856c818Smatthias.ringwald                 // forward fragment as L2CAP packet
3352718e2e7Smatthias.ringwald                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
3367856c818Smatthias.ringwald 
3377856c818Smatthias.ringwald             } else {
3387856c818Smatthias.ringwald                 // store first fragment and tweak acl length for complete package
3397856c818Smatthias.ringwald                 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4);
3407856c818Smatthias.ringwald                 conn->acl_recombination_pos    = acl_length + 4;
3417856c818Smatthias.ringwald                 conn->acl_recombination_length = l2cap_length;
342decc01a8Smatthias.ringwald                 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4);
3437856c818Smatthias.ringwald             }
3447856c818Smatthias.ringwald             break;
3457856c818Smatthias.ringwald 
3467856c818Smatthias.ringwald         }
3477856c818Smatthias.ringwald         default:
3487d67539fSmatthias.ringwald             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03);
3497856c818Smatthias.ringwald             return;
3507856c818Smatthias.ringwald     }
35194ab26f8Smatthias.ringwald 
35294ab26f8Smatthias.ringwald     // execute main loop
35394ab26f8Smatthias.ringwald     hci_run();
35416833f0aSmatthias.ringwald }
35522909952Smatthias.ringwald 
35667a3e8ecSmatthias.ringwald static void hci_shutdown_connection(hci_connection_t *conn){
357339b6768Smatthias.ringwald     log_info("Connection closed: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
3583c4d4b90Smatthias.ringwald 
3593c4d4b90Smatthias.ringwald     // cancel all l2cap connections
3603c4d4b90Smatthias.ringwald     hci_emit_disconnection_complete(conn->con_handle, 0x16);    // terminated by local host
3613c4d4b90Smatthias.ringwald 
362c7e0c5f6Smatthias.ringwald     run_loop_remove_timer(&conn->timeout);
363c785ef68Smatthias.ringwald 
364c7e0c5f6Smatthias.ringwald     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
365a3b02b71Smatthias.ringwald     btstack_memory_hci_connection_free( conn );
3663c4d4b90Smatthias.ringwald 
3673c4d4b90Smatthias.ringwald     // now it's gone
368c7e0c5f6Smatthias.ringwald     hci_emit_nr_connections_changed();
369c7e0c5f6Smatthias.ringwald }
370c7e0c5f6Smatthias.ringwald 
3710c042179S[email protected] static const uint16_t packet_type_sizes[] = {
3728f8108aaSmatthias.ringwald     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
3738f8108aaSmatthias.ringwald     HCI_ACL_DH1_SIZE, 0, 0, 0,
3748f8108aaSmatthias.ringwald     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
3758f8108aaSmatthias.ringwald     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
3768f8108aaSmatthias.ringwald };
37765389bfcS[email protected] static const uint8_t  packet_type_feature_requirement_bit[] = {
37865389bfcS[email protected]      0, // 3 slot packets
37965389bfcS[email protected]      1, // 5 slot packets
38065389bfcS[email protected]     25, // EDR 2 mpbs
38165389bfcS[email protected]     26, // EDR 3 mbps
38265389bfcS[email protected]     39, // 3 slot EDR packts
38365389bfcS[email protected]     40, // 5 slot EDR packet
38465389bfcS[email protected] };
38565389bfcS[email protected] static const uint16_t packet_type_feature_packet_mask[] = {
38665389bfcS[email protected]     0x0f00, // 3 slot packets
38765389bfcS[email protected]     0xf000, // 5 slot packets
38865389bfcS[email protected]     0x1102, // EDR 2 mpbs
38965389bfcS[email protected]     0x2204, // EDR 3 mbps
39065389bfcS[email protected]     0x0300, // 3 slot EDR packts
39165389bfcS[email protected]     0x3000, // 5 slot EDR packet
39265389bfcS[email protected] };
3938f8108aaSmatthias.ringwald 
39465389bfcS[email protected] static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
39565389bfcS[email protected]     // enable packet types based on size
3968f8108aaSmatthias.ringwald     uint16_t packet_types = 0;
3978f8108aaSmatthias.ringwald     int i;
3988f8108aaSmatthias.ringwald     for (i=0;i<16;i++){
3998f8108aaSmatthias.ringwald         if (packet_type_sizes[i] == 0) continue;
4008f8108aaSmatthias.ringwald         if (packet_type_sizes[i] <= buffer_size){
4018f8108aaSmatthias.ringwald             packet_types |= 1 << i;
4028f8108aaSmatthias.ringwald         }
4038f8108aaSmatthias.ringwald     }
40465389bfcS[email protected]     // disable packet types due to missing local supported features
40565389bfcS[email protected]     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
40665389bfcS[email protected]         int bit_idx = packet_type_feature_requirement_bit[i];
40765389bfcS[email protected]         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
40865389bfcS[email protected]         if (feature_set) continue;
40965389bfcS[email protected]         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
41065389bfcS[email protected]         packet_types &= ~packet_type_feature_packet_mask[i];
41165389bfcS[email protected]     }
4128f8108aaSmatthias.ringwald     // flip bits for "may not be used"
4138f8108aaSmatthias.ringwald     packet_types ^= 0x3306;
4148f8108aaSmatthias.ringwald     return packet_types;
4158f8108aaSmatthias.ringwald }
4168f8108aaSmatthias.ringwald 
4178f8108aaSmatthias.ringwald uint16_t hci_usable_acl_packet_types(void){
4188f8108aaSmatthias.ringwald     return hci_stack.packet_types;
4198f8108aaSmatthias.ringwald }
4208f8108aaSmatthias.ringwald 
4217dc17943Smatthias.ringwald uint8_t* hci_get_outgoing_acl_packet_buffer(void){
4227dc17943Smatthias.ringwald     // hci packet buffer is >= acl data packet length
4237dc17943Smatthias.ringwald     return hci_stack.hci_packet_buffer;
4247dc17943Smatthias.ringwald }
4257dc17943Smatthias.ringwald 
426f5d8d141S[email protected] uint16_t hci_max_acl_data_packet_length(void){
4277dc17943Smatthias.ringwald     return hci_stack.acl_data_packet_length;
4287dc17943Smatthias.ringwald }
4297dc17943Smatthias.ringwald 
430f5d8d141S[email protected] int hci_ssp_supported(void){
431f5d8d141S[email protected]     // No 51, byte 6, bit 3
432f5d8d141S[email protected]     return (hci_stack.local_supported_features[6] & (1 << 3)) != 0;
433f5d8d141S[email protected] }
434f5d8d141S[email protected] 
435f5d8d141S[email protected] int hci_classic_supported(void){
436f5d8d141S[email protected]     // No 37, byte 4, bit 5, = No BR/EDR Support
437f5d8d141S[email protected]     return (hci_stack.local_supported_features[4] & (1 << 5)) == 0;
438f5d8d141S[email protected] }
439f5d8d141S[email protected] 
440f5d8d141S[email protected] int hci_le_supported(void){
441f5d8d141S[email protected]     // No 37, byte 4, bit 6 = LE Supported (Controller)
442f5d8d141S[email protected] #ifdef HAVE_BLE
443f5d8d141S[email protected]     return (hci_stack.local_supported_features[4] & (1 << 6)) != 0;
444f5d8d141S[email protected] #else
445f5d8d141S[email protected]     return 0;
446f5d8d141S[email protected] #endif
447f5d8d141S[email protected] }
448f5d8d141S[email protected] 
44974ec757aSmatthias.ringwald // avoid huge local variables
450223aafc1Smatthias.ringwald #ifndef EMBEDDED
45174ec757aSmatthias.ringwald static device_name_t device_name;
452223aafc1Smatthias.ringwald #endif
45316833f0aSmatthias.ringwald static void event_handler(uint8_t *packet, int size){
4541281a47eSmatthias.ringwald     bd_addr_t addr;
4552d00edd4Smatthias.ringwald     uint8_t link_type;
456fe1ed1b8Smatthias.ringwald     hci_con_handle_t handle;
4571f7b95a1Smatthias.ringwald     hci_connection_t * conn;
45856cf178bSmatthias.ringwald     int i;
45922909952Smatthias.ringwald 
4605909f7f2Smatthias.ringwald     // printf("HCI:EVENT:%02x\n", packet[0]);
4615909f7f2Smatthias.ringwald 
4626772a24cSmatthias.ringwald     switch (packet[0]) {
46322909952Smatthias.ringwald 
4646772a24cSmatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
4657ec5eeaaSmatthias.ringwald             // get num cmd packets
4667b5fbe1fSmatthias.ringwald             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u\n", hci_stack.num_cmd_packets, packet[2]);
4677ec5eeaaSmatthias.ringwald             hci_stack.num_cmd_packets = packet[2];
4687ec5eeaaSmatthias.ringwald 
469e2edc0c3Smatthias.ringwald             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
470e2edc0c3Smatthias.ringwald                 // from offset 5
471e2edc0c3Smatthias.ringwald                 // status
4721d279b20Smatthias.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"
473e2edc0c3Smatthias.ringwald                 hci_stack.acl_data_packet_length = READ_BT_16(packet, 6);
47456cf178bSmatthias.ringwald                 // ignore: SCO data packet len (8)
475e2edc0c3Smatthias.ringwald                 hci_stack.total_num_acl_packets  = packet[9];
47656cf178bSmatthias.ringwald                 // ignore: total num SCO packets
47756cf178bSmatthias.ringwald                 if (hci_stack.state == HCI_STATE_INITIALIZING){
478a7a04bd9Smatthias.ringwald                     // determine usable ACL payload size
4798fcba05dSmatthias.ringwald                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack.acl_data_packet_length){
4808fcba05dSmatthias.ringwald                         hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
4818f8108aaSmatthias.ringwald                     }
48265389bfcS[email protected]                     log_info("hci_read_buffer_size: used size %u, count %u\n",
48365389bfcS[email protected]                              hci_stack.acl_data_packet_length, hci_stack.total_num_acl_packets);
484e2edc0c3Smatthias.ringwald                 }
48556cf178bSmatthias.ringwald             }
486188981d2Smatthias.ringwald             // Dump local address
487188981d2Smatthias.ringwald             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
488e2386ba1S[email protected]                 bt_flip_addr(hci_stack.local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
489188981d2Smatthias.ringwald                 log_info("Local Address, Status: 0x%02x: Addr: %s\n",
490e2386ba1S[email protected]                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack.local_bd_addr));
491188981d2Smatthias.ringwald             }
492381fbed8Smatthias.ringwald             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
493381fbed8Smatthias.ringwald                 hci_emit_discoverable_enabled(hci_stack.discoverable);
494381fbed8Smatthias.ringwald             }
49565389bfcS[email protected]             // Note: HCI init checks
496559e517eS[email protected]             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
49765389bfcS[email protected]                 memcpy(hci_stack.local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
498559e517eS[email protected]                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
499559e517eS[email protected]                     hci_stack.local_supported_features[0], hci_stack.local_supported_features[1],
500559e517eS[email protected]                     hci_stack.local_supported_features[2], hci_stack.local_supported_features[3],
501559e517eS[email protected]                     hci_stack.local_supported_features[4], hci_stack.local_supported_features[5],
502559e517eS[email protected]                     hci_stack.local_supported_features[6], hci_stack.local_supported_features[7]);
50365389bfcS[email protected] 
50465389bfcS[email protected]                 // determine usable ACL packet types based buffer size and supported features
50565389bfcS[email protected]                 hci_stack.packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(hci_stack.acl_data_packet_length, &hci_stack.local_supported_features[0]);
506f5d8d141S[email protected]                 log_info("packet types %04x", hci_stack.packet_types);
507f5d8d141S[email protected] 
508f5d8d141S[email protected]                 // Classic/LE
509f5d8d141S[email protected]                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
510559e517eS[email protected]             }
51156cf178bSmatthias.ringwald             break;
51256cf178bSmatthias.ringwald 
5137ec5eeaaSmatthias.ringwald         case HCI_EVENT_COMMAND_STATUS:
5147ec5eeaaSmatthias.ringwald             // get num cmd packets
5157b5fbe1fSmatthias.ringwald             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u\n", hci_stack.num_cmd_packets, packet[3]);
5167ec5eeaaSmatthias.ringwald             hci_stack.num_cmd_packets = packet[3];
5177ec5eeaaSmatthias.ringwald             break;
5187ec5eeaaSmatthias.ringwald 
51956cf178bSmatthias.ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
52056cf178bSmatthias.ringwald             for (i=0; i<packet[2];i++){
52156cf178bSmatthias.ringwald                 handle = READ_BT_16(packet, 3 + 2*i);
52256cf178bSmatthias.ringwald                 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i);
52356cf178bSmatthias.ringwald                 conn = connection_for_handle(handle);
52456cf178bSmatthias.ringwald                 if (!conn){
5257d67539fSmatthias.ringwald                     log_error("hci_number_completed_packet lists unused con handle %u\n", handle);
52656cf178bSmatthias.ringwald                     continue;
52756cf178bSmatthias.ringwald                 }
52856cf178bSmatthias.ringwald                 conn->num_acl_packets_sent -= num_packets;
5297b5fbe1fSmatthias.ringwald                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent);
53056cf178bSmatthias.ringwald             }
5316772a24cSmatthias.ringwald             break;
5326772a24cSmatthias.ringwald 
5331f7b95a1Smatthias.ringwald         case HCI_EVENT_CONNECTION_REQUEST:
53437eaa4cfSmatthias.ringwald             bt_flip_addr(addr, &packet[2]);
53537eaa4cfSmatthias.ringwald             // TODO: eval COD 8-10
5362d00edd4Smatthias.ringwald             link_type = packet[11];
537339b6768Smatthias.ringwald             log_info("Connection_incoming: %s, type %u\n", bd_addr_to_str(addr), link_type);
53837eaa4cfSmatthias.ringwald             if (link_type == 1) { // ACL
5391f7b95a1Smatthias.ringwald                 conn = connection_for_address(addr);
5401f7b95a1Smatthias.ringwald                 if (!conn) {
5411f7b95a1Smatthias.ringwald                     conn = create_connection_for_addr(addr);
5421f7b95a1Smatthias.ringwald                 }
543ce4c8fabSmatthias.ringwald                 if (!conn) {
544ce4c8fabSmatthias.ringwald                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
545ce4c8fabSmatthias.ringwald                     hci_stack.decline_reason = 0x0d;
546ce4c8fabSmatthias.ringwald                     BD_ADDR_COPY(hci_stack.decline_addr, addr);
547ce4c8fabSmatthias.ringwald                     break;
548ce4c8fabSmatthias.ringwald                 }
54932ab9390Smatthias.ringwald                 conn->state = RECEIVED_CONNECTION_REQUEST;
55032ab9390Smatthias.ringwald                 hci_run();
55137eaa4cfSmatthias.ringwald             } else {
552ce4c8fabSmatthias.ringwald                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
553ce4c8fabSmatthias.ringwald                 hci_stack.decline_reason = 0x0a;
554ce4c8fabSmatthias.ringwald                 BD_ADDR_COPY(hci_stack.decline_addr, addr);
55537eaa4cfSmatthias.ringwald             }
5561f7b95a1Smatthias.ringwald             break;
5571f7b95a1Smatthias.ringwald 
5586772a24cSmatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
559fe1ed1b8Smatthias.ringwald             // Connection management
560fe1ed1b8Smatthias.ringwald             bt_flip_addr(addr, &packet[5]);
561339b6768Smatthias.ringwald             log_info("Connection_complete (status=%u) %s\n", packet[2], bd_addr_to_str(addr));
5621f7b95a1Smatthias.ringwald             conn = connection_for_address(addr);
563fe1ed1b8Smatthias.ringwald             if (conn) {
564b448a0e7Smatthias.ringwald                 if (!packet[2]){
565c8e4258aSmatthias.ringwald                     conn->state = OPEN;
566fe1ed1b8Smatthias.ringwald                     conn->con_handle = READ_BT_16(packet, 3);
567ee091cf1Smatthias.ringwald 
568c785ef68Smatthias.ringwald                     // restart timer
569c21e6239Smatthias.ringwald                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
570ee091cf1Smatthias.ringwald                     run_loop_add_timer(&conn->timeout);
571c785ef68Smatthias.ringwald 
572339b6768Smatthias.ringwald                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
57343bfb1bdSmatthias.ringwald 
57443bfb1bdSmatthias.ringwald                     hci_emit_nr_connections_changed();
575b448a0e7Smatthias.ringwald                 } else {
576b448a0e7Smatthias.ringwald                     // connection failed, remove entry
577b448a0e7Smatthias.ringwald                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
578a3b02b71Smatthias.ringwald                     btstack_memory_hci_connection_free( conn );
579c12e46e7Smatthias.ringwald 
580c12e46e7Smatthias.ringwald                     // if authentication error, also delete link key
581c12e46e7Smatthias.ringwald                     if (packet[2] == 0x05) {
582c12e46e7Smatthias.ringwald                         hci_drop_link_key_for_bd_addr(&addr);
583c12e46e7Smatthias.ringwald                     }
584fe1ed1b8Smatthias.ringwald                 }
585fe1ed1b8Smatthias.ringwald             }
5866772a24cSmatthias.ringwald             break;
587fe1ed1b8Smatthias.ringwald 
5887fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_REQUEST:
5897b5fbe1fSmatthias.ringwald             log_info("HCI_EVENT_LINK_KEY_REQUEST\n");
5907fde4af9Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
59174ec757aSmatthias.ringwald             if (!hci_stack.remote_device_db) break;
59232ab9390Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
59364472d52Smatthias.ringwald             hci_run();
594d9a327f9Smatthias.ringwald             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
59529d53098Smatthias.ringwald             return;
5967fde4af9Smatthias.ringwald 
5977fde4af9Smatthias.ringwald         case HCI_EVENT_LINK_KEY_NOTIFICATION:
5987fde4af9Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_NOTIFICATION);
59974ec757aSmatthias.ringwald             if (!hci_stack.remote_device_db) break;
60029d53098Smatthias.ringwald             bt_flip_addr(addr, &packet[2]);
601287d19b8Smatthias.ringwald             hci_stack.remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8]);
60229d53098Smatthias.ringwald             // still forward event to allow dismiss of pairing dialog
6037fde4af9Smatthias.ringwald             break;
6047fde4af9Smatthias.ringwald 
6057fde4af9Smatthias.ringwald         case HCI_EVENT_PIN_CODE_REQUEST:
6067fde4af9Smatthias.ringwald             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_PIN_CODE_REQUEST);
607d9a327f9Smatthias.ringwald             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
608d9a327f9Smatthias.ringwald             if (!hci_stack.remote_device_db) break;
609d9a327f9Smatthias.ringwald             bt_flip_addr(addr, &packet[2]);
610d9a327f9Smatthias.ringwald             hci_stack.remote_device_db->delete_link_key(&addr);
6117fde4af9Smatthias.ringwald             break;
6127fde4af9Smatthias.ringwald 
6131d6b20aeS[email protected]         case HCI_EVENT_IO_CAPABILITY_REQUEST:
6141d6b20aeS[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
6151d6b20aeS[email protected]             if (hci_stack.ssp_io_capability == SSP_IO_CAPABILITY_UNKNOWN) break;
616dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
617dbe1a790S[email protected]             break;
618dbe1a790S[email protected] 
619dbe1a790S[email protected]         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
620dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_USER_CONFIRM_REQUEST);
621dbe1a790S[email protected]             if (!hci_stack.ssp_auto_accept) break;
622dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
623dbe1a790S[email protected]             break;
624dbe1a790S[email protected] 
625dbe1a790S[email protected]         case HCI_EVENT_USER_PASSKEY_REQUEST:
626dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_USER_PASSKEY_REQUEST);
627dbe1a790S[email protected]             if (!hci_stack.ssp_auto_accept) break;
628dbe1a790S[email protected]             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
6291d6b20aeS[email protected]             break;
6301d6b20aeS[email protected] 
631223aafc1Smatthias.ringwald #ifndef EMBEDDED
63274ec757aSmatthias.ringwald         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
63374ec757aSmatthias.ringwald             if (!hci_stack.remote_device_db) break;
63474ec757aSmatthias.ringwald             if (packet[2]) break; // status not ok
63574ec757aSmatthias.ringwald             bt_flip_addr(addr, &packet[3]);
6365a06394aSmatthias.ringwald             // fix for invalid remote names - terminate on 0xff
6375a06394aSmatthias.ringwald             for (i=0; i<248;i++){
6385a06394aSmatthias.ringwald                 if (packet[9+i] == 0xff){
6395a06394aSmatthias.ringwald                     packet[9+i] = 0;
6405a06394aSmatthias.ringwald                     break;
641cdc9101dSmatthias.ringwald                 }
6425a06394aSmatthias.ringwald             }
643d2fe945cS[email protected]             memset(&device_name, 0, sizeof(device_name_t));
64474ec757aSmatthias.ringwald             strncpy((char*) device_name, (char*) &packet[9], 248);
64574ec757aSmatthias.ringwald             hci_stack.remote_device_db->put_name(&addr, &device_name);
64674ec757aSmatthias.ringwald             break;
64774ec757aSmatthias.ringwald 
64874ec757aSmatthias.ringwald         case HCI_EVENT_INQUIRY_RESULT:
64974ec757aSmatthias.ringwald         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
65074ec757aSmatthias.ringwald             if (!hci_stack.remote_device_db) break;
65174ec757aSmatthias.ringwald             // first send inq result packet
65274ec757aSmatthias.ringwald             hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
65374ec757aSmatthias.ringwald             // then send cached remote names
65474ec757aSmatthias.ringwald             for (i=0; i<packet[2];i++){
65574ec757aSmatthias.ringwald                 bt_flip_addr(addr, &packet[3+i*6]);
65674ec757aSmatthias.ringwald                 if (hci_stack.remote_device_db->get_name(&addr, &device_name)){
65774ec757aSmatthias.ringwald                     hci_emit_remote_name_cached(&addr, &device_name);
65874ec757aSmatthias.ringwald                 }
65974ec757aSmatthias.ringwald             }
66074ec757aSmatthias.ringwald             return;
661223aafc1Smatthias.ringwald #endif
66274ec757aSmatthias.ringwald 
6636772a24cSmatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
664fe1ed1b8Smatthias.ringwald             if (!packet[2]){
665fe1ed1b8Smatthias.ringwald                 handle = READ_BT_16(packet, 3);
666fe1ed1b8Smatthias.ringwald                 hci_connection_t * conn = connection_for_handle(handle);
667fe1ed1b8Smatthias.ringwald                 if (conn) {
668c7e0c5f6Smatthias.ringwald                     hci_shutdown_connection(conn);
669fe1ed1b8Smatthias.ringwald                 }
670fe1ed1b8Smatthias.ringwald             }
6716772a24cSmatthias.ringwald             break;
6726772a24cSmatthias.ringwald 
673c68bdf90Smatthias.ringwald         case HCI_EVENT_HARDWARE_ERROR:
674c68bdf90Smatthias.ringwald             if(hci_stack.control->hw_error){
675c68bdf90Smatthias.ringwald                 (*hci_stack.control->hw_error)();
676c68bdf90Smatthias.ringwald             }
677c68bdf90Smatthias.ringwald             break;
678c68bdf90Smatthias.ringwald 
6795909f7f2Smatthias.ringwald #ifdef HAVE_BLE
6805909f7f2Smatthias.ringwald         case HCI_EVENT_LE_META:
6815909f7f2Smatthias.ringwald             switch (packet[2]) {
6825909f7f2Smatthias.ringwald                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
6835909f7f2Smatthias.ringwald                     // Connection management
6845909f7f2Smatthias.ringwald                     bt_flip_addr(addr, &packet[8]);
6855909f7f2Smatthias.ringwald                     log_info("LE Connection_complete (status=%u) %s\n", packet[3], bd_addr_to_str(addr));
6865909f7f2Smatthias.ringwald                     // LE connections are auto-accepted, so just create a connection if there isn't one already
6875909f7f2Smatthias.ringwald                     conn = connection_for_address(addr);
6885909f7f2Smatthias.ringwald                     if (packet[3]){
6895909f7f2Smatthias.ringwald                         if (conn){
6905909f7f2Smatthias.ringwald                             // outgoing connection failed, remove entry
6915909f7f2Smatthias.ringwald                             linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
6925909f7f2Smatthias.ringwald                             btstack_memory_hci_connection_free( conn );
6935909f7f2Smatthias.ringwald 
6945909f7f2Smatthias.ringwald                         }
6955909f7f2Smatthias.ringwald                         // if authentication error, also delete link key
6965909f7f2Smatthias.ringwald                         if (packet[3] == 0x05) {
6975909f7f2Smatthias.ringwald                             hci_drop_link_key_for_bd_addr(&addr);
6985909f7f2Smatthias.ringwald                         }
6995909f7f2Smatthias.ringwald                         break;
7005909f7f2Smatthias.ringwald                     }
7015909f7f2Smatthias.ringwald                     if (!conn){
7025909f7f2Smatthias.ringwald                         conn = create_connection_for_addr(addr);
7035909f7f2Smatthias.ringwald                     }
7045909f7f2Smatthias.ringwald                     if (!conn){
7055909f7f2Smatthias.ringwald                         // no memory
7065909f7f2Smatthias.ringwald                         break;
7075909f7f2Smatthias.ringwald                     }
7085909f7f2Smatthias.ringwald 
7095909f7f2Smatthias.ringwald                     conn->state = OPEN;
7105909f7f2Smatthias.ringwald                     conn->con_handle = READ_BT_16(packet, 4);
7115909f7f2Smatthias.ringwald 
7125909f7f2Smatthias.ringwald                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
7135909f7f2Smatthias.ringwald 
7145909f7f2Smatthias.ringwald                     // restart timer
7155909f7f2Smatthias.ringwald                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
7165909f7f2Smatthias.ringwald                     // run_loop_add_timer(&conn->timeout);
7175909f7f2Smatthias.ringwald 
7185909f7f2Smatthias.ringwald                     log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address));
7195909f7f2Smatthias.ringwald 
7205909f7f2Smatthias.ringwald                     hci_emit_nr_connections_changed();
7215909f7f2Smatthias.ringwald                     break;
7225909f7f2Smatthias.ringwald 
7235909f7f2Smatthias.ringwald                 default:
7245909f7f2Smatthias.ringwald                     break;
7255909f7f2Smatthias.ringwald             }
7265909f7f2Smatthias.ringwald             break;
7275909f7f2Smatthias.ringwald #endif
7285909f7f2Smatthias.ringwald 
7296772a24cSmatthias.ringwald         default:
7306772a24cSmatthias.ringwald             break;
731fe1ed1b8Smatthias.ringwald     }
732fe1ed1b8Smatthias.ringwald 
7333429f56bSmatthias.ringwald     // handle BT initialization
7343429f56bSmatthias.ringwald     if (hci_stack.state == HCI_STATE_INITIALIZING){
7357301ad89Smatthias.ringwald         // handle H4 synchronization loss on restart
7367301ad89Smatthias.ringwald         // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){
7377301ad89Smatthias.ringwald         //    hci_stack.substate = 0;
7387301ad89Smatthias.ringwald         // }
7397301ad89Smatthias.ringwald         // handle normal init sequence
7403429f56bSmatthias.ringwald         if (hci_stack.substate % 2){
7413429f56bSmatthias.ringwald             // odd: waiting for event
742f155fca3Smatthias.ringwald             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){
7433429f56bSmatthias.ringwald                 hci_stack.substate++;
7443429f56bSmatthias.ringwald             }
7453429f56bSmatthias.ringwald         }
74622909952Smatthias.ringwald     }
74722909952Smatthias.ringwald 
74889db417bSmatthias.ringwald     // help with BT sleep
74989db417bSmatthias.ringwald     if (hci_stack.state == HCI_STATE_FALLING_ASLEEP
75089db417bSmatthias.ringwald         && hci_stack.substate == 1
75189db417bSmatthias.ringwald         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
75289db417bSmatthias.ringwald         hci_stack.substate++;
75389db417bSmatthias.ringwald     }
75489db417bSmatthias.ringwald 
7552718e2e7Smatthias.ringwald     hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
75694ab26f8Smatthias.ringwald 
75794ab26f8Smatthias.ringwald 	// execute main loop
75894ab26f8Smatthias.ringwald 	hci_run();
75916833f0aSmatthias.ringwald }
76016833f0aSmatthias.ringwald 
7610a57e69fSmatthias.ringwald static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
76210e830c9Smatthias.ringwald     switch (packet_type) {
76310e830c9Smatthias.ringwald         case HCI_EVENT_PACKET:
76410e830c9Smatthias.ringwald             event_handler(packet, size);
76510e830c9Smatthias.ringwald             break;
76610e830c9Smatthias.ringwald         case HCI_ACL_DATA_PACKET:
76710e830c9Smatthias.ringwald             acl_handler(packet, size);
76810e830c9Smatthias.ringwald             break;
76910e830c9Smatthias.ringwald         default:
77010e830c9Smatthias.ringwald             break;
77110e830c9Smatthias.ringwald     }
77210e830c9Smatthias.ringwald }
77310e830c9Smatthias.ringwald 
774fcadd0caSmatthias.ringwald /** Register HCI packet handlers */
7752718e2e7Smatthias.ringwald void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
7762718e2e7Smatthias.ringwald     hci_stack.packet_handler = handler;
77716833f0aSmatthias.ringwald }
77816833f0aSmatthias.ringwald 
7794f4fc1dfSmatthias.ringwald void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
780475c8125Smatthias.ringwald 
781475c8125Smatthias.ringwald     // reference to use transport layer implementation
78216833f0aSmatthias.ringwald     hci_stack.hci_transport = transport;
783475c8125Smatthias.ringwald 
78411e23e5fSmatthias.ringwald     // references to used control implementation
78511e23e5fSmatthias.ringwald     hci_stack.control = control;
78611e23e5fSmatthias.ringwald 
78711e23e5fSmatthias.ringwald     // reference to used config
78811e23e5fSmatthias.ringwald     hci_stack.config = config;
78911e23e5fSmatthias.ringwald 
790fe1ed1b8Smatthias.ringwald     // no connections yet
791fe1ed1b8Smatthias.ringwald     hci_stack.connections = NULL;
7920a90cc40Smatthias.ringwald     hci_stack.discoverable = 0;
793c0e866bfSmatthias.ringwald     hci_stack.connectable = 0;
794758b46ceSmatthias.ringwald 
795b031bebbSmatthias.ringwald     // no pending cmds
796b031bebbSmatthias.ringwald     hci_stack.decline_reason = 0;
797b031bebbSmatthias.ringwald     hci_stack.new_scan_enable_value = 0xff;
798b031bebbSmatthias.ringwald 
79916833f0aSmatthias.ringwald     // higher level handler
8002718e2e7Smatthias.ringwald     hci_stack.packet_handler = dummy_handler;
80116833f0aSmatthias.ringwald 
802404843c1Smatthias.ringwald     // store and open remote device db
803404843c1Smatthias.ringwald     hci_stack.remote_device_db = remote_device_db;
804404843c1Smatthias.ringwald     if (hci_stack.remote_device_db) {
805404843c1Smatthias.ringwald         hci_stack.remote_device_db->open();
806404843c1Smatthias.ringwald     }
80729d53098Smatthias.ringwald 
8088fcba05dSmatthias.ringwald     // max acl payload size defined in config.h
8098fcba05dSmatthias.ringwald     hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
8108fcba05dSmatthias.ringwald 
81116833f0aSmatthias.ringwald     // register packet handlers with transport
81210e830c9Smatthias.ringwald     transport->register_packet_handler(&packet_handler);
813f5454fc6Smatthias.ringwald 
814f5454fc6Smatthias.ringwald     hci_stack.state = HCI_STATE_OFF;
815e2386ba1S[email protected] 
816e2386ba1S[email protected]     // class of device
817e2386ba1S[email protected]     hci_stack.class_of_device = 0x007a020c; // Smartphone
818a45d6b9fS[email protected] 
819a45d6b9fS[email protected]     // Secure Simple Pairing
820a45d6b9fS[email protected]     hci_stack.ssp_enable = 0;
821a45d6b9fS[email protected]     hci_stack.ssp_io_capability = SSP_IO_CAPABILITY_UNKNOWN;
822a45d6b9fS[email protected]     hci_stack.ssp_authentication_requirement = 0;
823475c8125Smatthias.ringwald }
824475c8125Smatthias.ringwald 
825404843c1Smatthias.ringwald void hci_close(){
826404843c1Smatthias.ringwald     // close remote device db
827404843c1Smatthias.ringwald     if (hci_stack.remote_device_db) {
828404843c1Smatthias.ringwald         hci_stack.remote_device_db->close();
829404843c1Smatthias.ringwald     }
830f5454fc6Smatthias.ringwald     while (hci_stack.connections) {
831f5454fc6Smatthias.ringwald         hci_shutdown_connection((hci_connection_t *) hci_stack.connections);
832f5454fc6Smatthias.ringwald }
833f5454fc6Smatthias.ringwald     hci_power_control(HCI_POWER_OFF);
834404843c1Smatthias.ringwald }
835404843c1Smatthias.ringwald 
8368d213e1aSmatthias.ringwald // State-Module-Driver overview
8378d213e1aSmatthias.ringwald // state                    module  low-level
8388d213e1aSmatthias.ringwald // HCI_STATE_OFF             off      close
8398d213e1aSmatthias.ringwald // HCI_STATE_INITIALIZING,   on       open
8408d213e1aSmatthias.ringwald // HCI_STATE_WORKING,        on       open
8418d213e1aSmatthias.ringwald // HCI_STATE_HALTING,        on       open
842d661ed19Smatthias.ringwald // HCI_STATE_SLEEPING,    off/sleep   close
843d661ed19Smatthias.ringwald // HCI_STATE_FALLING_ASLEEP  on       open
844c7e0c5f6Smatthias.ringwald 
84540d1c7a4Smatthias.ringwald static int hci_power_control_on(void){
8467301ad89Smatthias.ringwald 
847038bc64cSmatthias.ringwald     // power on
848f9a30166Smatthias.ringwald     int err = 0;
849f9a30166Smatthias.ringwald     if (hci_stack.control && hci_stack.control->on){
850f9a30166Smatthias.ringwald         err = (*hci_stack.control->on)(hci_stack.config);
851f9a30166Smatthias.ringwald     }
852038bc64cSmatthias.ringwald     if (err){
8537d67539fSmatthias.ringwald         log_error( "POWER_ON failed\n");
854038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
855038bc64cSmatthias.ringwald         return err;
856038bc64cSmatthias.ringwald     }
857038bc64cSmatthias.ringwald 
858038bc64cSmatthias.ringwald     // open low-level device
859038bc64cSmatthias.ringwald     err = hci_stack.hci_transport->open(hci_stack.config);
860038bc64cSmatthias.ringwald     if (err){
8617d67539fSmatthias.ringwald         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
862f9a30166Smatthias.ringwald         if (hci_stack.control && hci_stack.control->off){
863f9a30166Smatthias.ringwald             (*hci_stack.control->off)(hci_stack.config);
864f9a30166Smatthias.ringwald         }
865038bc64cSmatthias.ringwald         hci_emit_hci_open_failed();
866038bc64cSmatthias.ringwald         return err;
867038bc64cSmatthias.ringwald     }
8688d213e1aSmatthias.ringwald     return 0;
8698d213e1aSmatthias.ringwald }
870038bc64cSmatthias.ringwald 
87140d1c7a4Smatthias.ringwald static void hci_power_control_off(void){
8728d213e1aSmatthias.ringwald 
8737b5fbe1fSmatthias.ringwald     log_info("hci_power_control_off\n");
8749418f9c9Smatthias.ringwald 
8758d213e1aSmatthias.ringwald     // close low-level device
8768d213e1aSmatthias.ringwald     hci_stack.hci_transport->close(hci_stack.config);
8778d213e1aSmatthias.ringwald 
8787b5fbe1fSmatthias.ringwald     log_info("hci_power_control_off - hci_transport closed\n");
8799418f9c9Smatthias.ringwald 
8808d213e1aSmatthias.ringwald     // power off
8818d213e1aSmatthias.ringwald     if (hci_stack.control && hci_stack.control->off){
8828d213e1aSmatthias.ringwald         (*hci_stack.control->off)(hci_stack.config);
8838d213e1aSmatthias.ringwald     }
8849418f9c9Smatthias.ringwald 
8857b5fbe1fSmatthias.ringwald     log_info("hci_power_control_off - control closed\n");
8869418f9c9Smatthias.ringwald 
88772ea5239Smatthias.ringwald     hci_stack.state = HCI_STATE_OFF;
88872ea5239Smatthias.ringwald }
88972ea5239Smatthias.ringwald 
89040d1c7a4Smatthias.ringwald static void hci_power_control_sleep(void){
89172ea5239Smatthias.ringwald 
8927b5fbe1fSmatthias.ringwald     log_info("hci_power_control_sleep\n");
8933144bce4Smatthias.ringwald 
894b429b9b7Smatthias.ringwald #if 0
895b429b9b7Smatthias.ringwald     // don't close serial port during sleep
896b429b9b7Smatthias.ringwald 
89772ea5239Smatthias.ringwald     // close low-level device
89872ea5239Smatthias.ringwald     hci_stack.hci_transport->close(hci_stack.config);
899b429b9b7Smatthias.ringwald #endif
90072ea5239Smatthias.ringwald 
90172ea5239Smatthias.ringwald     // sleep mode
9023144bce4Smatthias.ringwald     if (hci_stack.control && hci_stack.control->sleep){
90372ea5239Smatthias.ringwald         (*hci_stack.control->sleep)(hci_stack.config);
90472ea5239Smatthias.ringwald     }
905b429b9b7Smatthias.ringwald 
90672ea5239Smatthias.ringwald     hci_stack.state = HCI_STATE_SLEEPING;
9078d213e1aSmatthias.ringwald }
9088d213e1aSmatthias.ringwald 
90940d1c7a4Smatthias.ringwald static int hci_power_control_wake(void){
910b429b9b7Smatthias.ringwald 
9117b5fbe1fSmatthias.ringwald     log_info("hci_power_control_wake\n");
912b429b9b7Smatthias.ringwald 
913b429b9b7Smatthias.ringwald     // wake on
914b429b9b7Smatthias.ringwald     if (hci_stack.control && hci_stack.control->wake){
915b429b9b7Smatthias.ringwald         (*hci_stack.control->wake)(hci_stack.config);
916b429b9b7Smatthias.ringwald     }
917b429b9b7Smatthias.ringwald 
918b429b9b7Smatthias.ringwald #if 0
919b429b9b7Smatthias.ringwald     // open low-level device
920b429b9b7Smatthias.ringwald     int err = hci_stack.hci_transport->open(hci_stack.config);
921b429b9b7Smatthias.ringwald     if (err){
9227d67539fSmatthias.ringwald         log_error( "HCI_INIT failed, turning Bluetooth off again\n");
923b429b9b7Smatthias.ringwald         if (hci_stack.control && hci_stack.control->off){
924b429b9b7Smatthias.ringwald             (*hci_stack.control->off)(hci_stack.config);
925b429b9b7Smatthias.ringwald         }
926b429b9b7Smatthias.ringwald         hci_emit_hci_open_failed();
927b429b9b7Smatthias.ringwald         return err;
928b429b9b7Smatthias.ringwald     }
929b429b9b7Smatthias.ringwald #endif
930b429b9b7Smatthias.ringwald 
931b429b9b7Smatthias.ringwald     return 0;
932b429b9b7Smatthias.ringwald }
933b429b9b7Smatthias.ringwald 
934b429b9b7Smatthias.ringwald 
9358d213e1aSmatthias.ringwald int hci_power_control(HCI_POWER_MODE power_mode){
936d661ed19Smatthias.ringwald 
9377b5fbe1fSmatthias.ringwald     log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack.state);
938d661ed19Smatthias.ringwald 
9398d213e1aSmatthias.ringwald     int err = 0;
9408d213e1aSmatthias.ringwald     switch (hci_stack.state){
9418d213e1aSmatthias.ringwald 
9428d213e1aSmatthias.ringwald         case HCI_STATE_OFF:
9438d213e1aSmatthias.ringwald             switch (power_mode){
9448d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
9458d213e1aSmatthias.ringwald                     err = hci_power_control_on();
9468d213e1aSmatthias.ringwald                     if (err) return err;
9477301ad89Smatthias.ringwald                     // set up state machine
9487301ad89Smatthias.ringwald                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
9497301ad89Smatthias.ringwald                     hci_stack.state = HCI_STATE_INITIALIZING;
9507301ad89Smatthias.ringwald                     hci_stack.substate = 0;
9518d213e1aSmatthias.ringwald                     break;
9528d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
9538d213e1aSmatthias.ringwald                     // do nothing
9548d213e1aSmatthias.ringwald                     break;
9558d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
956b546ac54Smatthias.ringwald                     // do nothing (with SLEEP == OFF)
9578d213e1aSmatthias.ringwald                     break;
9588d213e1aSmatthias.ringwald             }
9598d213e1aSmatthias.ringwald             break;
9607301ad89Smatthias.ringwald 
9618d213e1aSmatthias.ringwald         case HCI_STATE_INITIALIZING:
9628d213e1aSmatthias.ringwald             switch (power_mode){
9638d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
9648d213e1aSmatthias.ringwald                     // do nothing
9658d213e1aSmatthias.ringwald                     break;
9668d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
9678d213e1aSmatthias.ringwald                     // no connections yet, just turn it off
9688d213e1aSmatthias.ringwald                     hci_power_control_off();
9698d213e1aSmatthias.ringwald                     break;
9708d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
971b546ac54Smatthias.ringwald                     // no connections yet, just turn it off
97272ea5239Smatthias.ringwald                     hci_power_control_sleep();
9738d213e1aSmatthias.ringwald                     break;
9748d213e1aSmatthias.ringwald             }
9758d213e1aSmatthias.ringwald             break;
9767301ad89Smatthias.ringwald 
9778d213e1aSmatthias.ringwald         case HCI_STATE_WORKING:
9788d213e1aSmatthias.ringwald             switch (power_mode){
9798d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
9808d213e1aSmatthias.ringwald                     // do nothing
9818d213e1aSmatthias.ringwald                     break;
9828d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
983c7e0c5f6Smatthias.ringwald                     // see hci_run
984c7e0c5f6Smatthias.ringwald                     hci_stack.state = HCI_STATE_HALTING;
9858d213e1aSmatthias.ringwald                     break;
9868d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
987b546ac54Smatthias.ringwald                     // see hci_run
988b546ac54Smatthias.ringwald                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
98989db417bSmatthias.ringwald                     hci_stack.substate = 0;
9908d213e1aSmatthias.ringwald                     break;
9918d213e1aSmatthias.ringwald             }
9928d213e1aSmatthias.ringwald             break;
9937301ad89Smatthias.ringwald 
9948d213e1aSmatthias.ringwald         case HCI_STATE_HALTING:
9958d213e1aSmatthias.ringwald             switch (power_mode){
9968d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
9978d213e1aSmatthias.ringwald                     // set up state machine
9988d213e1aSmatthias.ringwald                     hci_stack.state = HCI_STATE_INITIALIZING;
9998d213e1aSmatthias.ringwald                     hci_stack.substate = 0;
10008d213e1aSmatthias.ringwald                     break;
10018d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
10028d213e1aSmatthias.ringwald                     // do nothing
10038d213e1aSmatthias.ringwald                     break;
10048d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1005b546ac54Smatthias.ringwald                     // see hci_run
1006b546ac54Smatthias.ringwald                     hci_stack.state = HCI_STATE_FALLING_ASLEEP;
100789db417bSmatthias.ringwald                     hci_stack.substate = 0;
10088d213e1aSmatthias.ringwald                     break;
10098d213e1aSmatthias.ringwald             }
10108d213e1aSmatthias.ringwald             break;
10118d213e1aSmatthias.ringwald 
10128d213e1aSmatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
10138d213e1aSmatthias.ringwald             switch (power_mode){
10148d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
101528171530Smatthias.ringwald 
101628171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
101728171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
101828171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
10198747d67fSmatthias.ringwald                         hci_stack.state = HCI_STATE_INITIALIZING;
1020da5275c5S[email protected]                         hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
102128171530Smatthias.ringwald                         break;
102228171530Smatthias.ringwald                     }
102328171530Smatthias.ringwald #endif
1024b546ac54Smatthias.ringwald                     // set up state machine
1025b546ac54Smatthias.ringwald                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1026b546ac54Smatthias.ringwald                     hci_stack.state = HCI_STATE_INITIALIZING;
1027b546ac54Smatthias.ringwald                     hci_stack.substate = 0;
10288d213e1aSmatthias.ringwald                     break;
10298d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
1030b546ac54Smatthias.ringwald                     // see hci_run
1031b546ac54Smatthias.ringwald                     hci_stack.state = HCI_STATE_HALTING;
10328d213e1aSmatthias.ringwald                     break;
10338d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1034b546ac54Smatthias.ringwald                     // do nothing
10358d213e1aSmatthias.ringwald                     break;
10368d213e1aSmatthias.ringwald             }
10378d213e1aSmatthias.ringwald             break;
10388d213e1aSmatthias.ringwald 
10398d213e1aSmatthias.ringwald         case HCI_STATE_SLEEPING:
10408d213e1aSmatthias.ringwald             switch (power_mode){
10418d213e1aSmatthias.ringwald                 case HCI_POWER_ON:
104228171530Smatthias.ringwald 
104328171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
104428171530Smatthias.ringwald                     // nothing to do, if H4 supports power management
104528171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
10468747d67fSmatthias.ringwald                         hci_stack.state = HCI_STATE_INITIALIZING;
1047da5275c5S[email protected]                         hci_stack.substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1048758b46ceSmatthias.ringwald                         hci_update_scan_enable();
104928171530Smatthias.ringwald                         break;
105028171530Smatthias.ringwald                     }
105128171530Smatthias.ringwald #endif
10523144bce4Smatthias.ringwald                     err = hci_power_control_wake();
10533144bce4Smatthias.ringwald                     if (err) return err;
1054b546ac54Smatthias.ringwald                     // set up state machine
1055b546ac54Smatthias.ringwald                     hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
1056b546ac54Smatthias.ringwald                     hci_stack.state = HCI_STATE_INITIALIZING;
1057b546ac54Smatthias.ringwald                     hci_stack.substate = 0;
10588d213e1aSmatthias.ringwald                     break;
10598d213e1aSmatthias.ringwald                 case HCI_POWER_OFF:
10604ddb5bedSmatthias.ringwald                     hci_stack.state = HCI_STATE_HALTING;
10618d213e1aSmatthias.ringwald                     break;
10628d213e1aSmatthias.ringwald                 case HCI_POWER_SLEEP:
1063b546ac54Smatthias.ringwald                     // do nothing
10648d213e1aSmatthias.ringwald                     break;
10658d213e1aSmatthias.ringwald             }
10668d213e1aSmatthias.ringwald             break;
106711e23e5fSmatthias.ringwald     }
106868d92d03Smatthias.ringwald 
1069038bc64cSmatthias.ringwald     // create internal event
1070ee8bf225Smatthias.ringwald 	hci_emit_state();
1071ee8bf225Smatthias.ringwald 
107268d92d03Smatthias.ringwald 	// trigger next/first action
107368d92d03Smatthias.ringwald 	hci_run();
107468d92d03Smatthias.ringwald 
1075475c8125Smatthias.ringwald     return 0;
1076475c8125Smatthias.ringwald }
1077475c8125Smatthias.ringwald 
1078758b46ceSmatthias.ringwald static void hci_update_scan_enable(void){
1079758b46ceSmatthias.ringwald     // 2 = page scan, 1 = inq scan
1080758b46ceSmatthias.ringwald     hci_stack.new_scan_enable_value  = hci_stack.connectable << 1 | hci_stack.discoverable;
1081758b46ceSmatthias.ringwald     hci_run();
1082758b46ceSmatthias.ringwald }
1083758b46ceSmatthias.ringwald 
1084381fbed8Smatthias.ringwald void hci_discoverable_control(uint8_t enable){
1085381fbed8Smatthias.ringwald     if (enable) enable = 1; // normalize argument
1086381fbed8Smatthias.ringwald 
1087381fbed8Smatthias.ringwald     if (hci_stack.discoverable == enable){
1088381fbed8Smatthias.ringwald         hci_emit_discoverable_enabled(hci_stack.discoverable);
1089381fbed8Smatthias.ringwald         return;
1090381fbed8Smatthias.ringwald     }
1091381fbed8Smatthias.ringwald 
1092381fbed8Smatthias.ringwald     hci_stack.discoverable = enable;
1093758b46ceSmatthias.ringwald     hci_update_scan_enable();
1094758b46ceSmatthias.ringwald }
1095b031bebbSmatthias.ringwald 
1096758b46ceSmatthias.ringwald void hci_connectable_control(uint8_t enable){
1097758b46ceSmatthias.ringwald     if (enable) enable = 1; // normalize argument
1098758b46ceSmatthias.ringwald 
1099758b46ceSmatthias.ringwald     // don't emit event
1100758b46ceSmatthias.ringwald     if (hci_stack.connectable == enable) return;
1101758b46ceSmatthias.ringwald 
1102758b46ceSmatthias.ringwald     hci_stack.connectable = enable;
1103758b46ceSmatthias.ringwald     hci_update_scan_enable();
1104381fbed8Smatthias.ringwald }
1105381fbed8Smatthias.ringwald 
110606b35ec0Smatthias.ringwald void hci_run(){
11078a485f27Smatthias.ringwald 
110832ab9390Smatthias.ringwald     hci_connection_t * connection;
110932ab9390Smatthias.ringwald     linked_item_t * it;
111032ab9390Smatthias.ringwald 
1111ce4c8fabSmatthias.ringwald     if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
1112ce4c8fabSmatthias.ringwald 
1113b031bebbSmatthias.ringwald     // global/non-connection oriented commands
1114b031bebbSmatthias.ringwald 
1115b031bebbSmatthias.ringwald     // decline incoming connections
1116ce4c8fabSmatthias.ringwald     if (hci_stack.decline_reason){
1117ce4c8fabSmatthias.ringwald         uint8_t reason = hci_stack.decline_reason;
1118ce4c8fabSmatthias.ringwald         hci_stack.decline_reason = 0;
1119ce4c8fabSmatthias.ringwald         hci_send_cmd(&hci_reject_connection_request, hci_stack.decline_addr, reason);
1120dbe1a790S[email protected]         return;
1121ce4c8fabSmatthias.ringwald     }
1122ce4c8fabSmatthias.ringwald 
1123b031bebbSmatthias.ringwald     // send scan enable
1124*92368cd3S[email protected]     if (hci_stack.state == HCI_STATE_WORKING && hci_stack.new_scan_enable_value != 0xff && hci_classic_supported()){
1125b031bebbSmatthias.ringwald         hci_send_cmd(&hci_write_scan_enable, hci_stack.new_scan_enable_value);
1126b031bebbSmatthias.ringwald         hci_stack.new_scan_enable_value = 0xff;
1127dbe1a790S[email protected]         return;
1128b031bebbSmatthias.ringwald     }
1129b031bebbSmatthias.ringwald 
113032ab9390Smatthias.ringwald     // send pending HCI commands
113132ab9390Smatthias.ringwald     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
113232ab9390Smatthias.ringwald 
1133b031bebbSmatthias.ringwald         connection = (hci_connection_t *) it;
113432ab9390Smatthias.ringwald 
113532ab9390Smatthias.ringwald         if (connection->state == RECEIVED_CONNECTION_REQUEST){
11367b5fbe1fSmatthias.ringwald             log_info("sending hci_accept_connection_request\n");
113732ab9390Smatthias.ringwald             hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
113832ab9390Smatthias.ringwald             connection->state = ACCEPTED_CONNECTION_REQUEST;
1139dbe1a790S[email protected]             return;
1140c7e0c5f6Smatthias.ringwald         }
1141c7e0c5f6Smatthias.ringwald 
114232ab9390Smatthias.ringwald         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
114332ab9390Smatthias.ringwald             link_key_t link_key;
11447b5fbe1fSmatthias.ringwald             log_info("responding to link key request\n");
114532ab9390Smatthias.ringwald             if ( hci_stack.remote_device_db->get_link_key( &connection->address, &link_key)){
114632ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
114732ab9390Smatthias.ringwald             } else {
114832ab9390Smatthias.ringwald                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
114932ab9390Smatthias.ringwald             }
115028ca2b46S[email protected]             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1151dbe1a790S[email protected]             return;
115232ab9390Smatthias.ringwald         }
11531d6b20aeS[email protected] 
1154dbe1a790S[email protected]         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
1155dbe1a790S[email protected]             hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack.ssp_io_capability, NULL, hci_stack.ssp_authentication_requirement);
1156dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
1157dbe1a790S[email protected]             return;
115832ab9390Smatthias.ringwald         }
115932ab9390Smatthias.ringwald 
1160dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
1161dbe1a790S[email protected]             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
1162dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
1163dbe1a790S[email protected]             return;
1164dbe1a790S[email protected]         }
1165dbe1a790S[email protected] 
1166dbe1a790S[email protected]         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
1167dbe1a790S[email protected]             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
1168dbe1a790S[email protected]             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
1169dbe1a790S[email protected]             return;
1170dbe1a790S[email protected]         }
1171dbe1a790S[email protected]     }
1172c7e0c5f6Smatthias.ringwald 
11733429f56bSmatthias.ringwald     switch (hci_stack.state){
11743429f56bSmatthias.ringwald         case HCI_STATE_INITIALIZING:
11757b5fbe1fSmatthias.ringwald             // log_info("hci_init: substate %u\n", hci_stack.substate);
11763429f56bSmatthias.ringwald             if (hci_stack.substate % 2) {
11773429f56bSmatthias.ringwald                 // odd: waiting for command completion
117806b35ec0Smatthias.ringwald                 return;
11793429f56bSmatthias.ringwald             }
118090919203Smatthias.ringwald             switch (hci_stack.substate >> 1){
1181c7492964Smatthias.ringwald                 case 0: // RESET
118222909952Smatthias.ringwald                     hci_send_cmd(&hci_reset);
1183c7492964Smatthias.ringwald                     if (hci_stack.config == 0 || ((hci_uart_config_t *)hci_stack.config)->baudrate_main == 0){
1184c7492964Smatthias.ringwald                         // skip baud change
1185c7492964Smatthias.ringwald                         hci_stack.substate = 4; // >> 1 = 2
1186c7492964Smatthias.ringwald                     }
11873429f56bSmatthias.ringwald                     break;
1188c7492964Smatthias.ringwald                 case 1: // SEND BAUD CHANGE
11897dc17943Smatthias.ringwald                     hci_stack.control->baudrate_cmd(hci_stack.config, ((hci_uart_config_t *)hci_stack.config)->baudrate_main, hci_stack.hci_packet_buffer);
11907dc17943Smatthias.ringwald                     hci_send_cmd_packet(hci_stack.hci_packet_buffer, 3 + hci_stack.hci_packet_buffer[2]);
1191c7492964Smatthias.ringwald                     break;
1192c7492964Smatthias.ringwald                 case 2: // LOCAL BAUD CHANGE
1193c7492964Smatthias.ringwald                     hci_stack.hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack.config)->baudrate_main);
1194c7492964Smatthias.ringwald                     hci_stack.substate += 2;
1195c7492964Smatthias.ringwald                     // break missing here for fall through
1196c7492964Smatthias.ringwald 
1197c7492964Smatthias.ringwald                 case 3:
119890919203Smatthias.ringwald                     // custom initialization
1199db8946afSmatthias.ringwald                     if (hci_stack.control && hci_stack.control->next_cmd){
12007dc17943Smatthias.ringwald                         int valid_cmd = (*hci_stack.control->next_cmd)(hci_stack.config, hci_stack.hci_packet_buffer);
1201d62aca9fSmatthias.ringwald                         if (valid_cmd){
12027dc17943Smatthias.ringwald                             int size = 3 + hci_stack.hci_packet_buffer[2];
12037dc17943Smatthias.ringwald                             hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack.hci_packet_buffer, size);
1204c7492964Smatthias.ringwald                             hci_stack.substate = 4; // more init commands
120590919203Smatthias.ringwald                             break;
120690919203Smatthias.ringwald                         }
1207d62aca9fSmatthias.ringwald                         log_info("hci_run: init script done\n\r");
120890919203Smatthias.ringwald                     }
12092f6c30e1Smatthias.ringwald                     // otherwise continue
1210f432a6ddSmatthias.ringwald 					hci_send_cmd(&hci_read_bd_addr);
1211f432a6ddSmatthias.ringwald 					break;
1212c7492964Smatthias.ringwald 				case 4:
1213e2edc0c3Smatthias.ringwald 					hci_send_cmd(&hci_read_buffer_size);
1214e2edc0c3Smatthias.ringwald 					break;
1215c7492964Smatthias.ringwald                 case 5:
121665389bfcS[email protected]                     hci_send_cmd(&hci_read_local_supported_features);
12173429f56bSmatthias.ringwald                     break;
1218c7492964Smatthias.ringwald                 case 6:
1219f5d8d141S[email protected]                     hci_send_cmd(&hci_set_event_mask,0xffffffff, 0xFFFFFFFF); ///0x1DFFFFFF
1220f5d8d141S[email protected] 
1221f5d8d141S[email protected]                     // skip Classic init commands for LE only chipsets
1222f5d8d141S[email protected]                     if (hci_classic_supported()){
1223f5d8d141S[email protected]                         if (!hci_ssp_supported()){
1224f5d8d141S[email protected]                             hci_stack.substate = 7 << 1; // skip hci_write_simple_pairing_mode
1225f5d8d141S[email protected]                         }
1226f5d8d141S[email protected]                     }   else {
1227f5d8d141S[email protected]                         hci_stack.substate = 11 << 1;    // skip all classic command
1228f5d8d141S[email protected]                     }
1229f5d8d141S[email protected]                     break;
1230f5d8d141S[email protected]                 case 7:
1231f5d8d141S[email protected]                     hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack.ssp_enable);
1232f5d8d141S[email protected]                     break;
1233f5d8d141S[email protected]                 case 8:
123465389bfcS[email protected]                     // ca. 15 sec
123565389bfcS[email protected]                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
1236559e517eS[email protected]                     break;
1237f5d8d141S[email protected]                 case 9:
1238e2386ba1S[email protected]                     hci_send_cmd(&hci_write_class_of_device, hci_stack.class_of_device);
1239e2386ba1S[email protected]                     break;
1240f5d8d141S[email protected]                 case 10:
1241e2386ba1S[email protected]                     if (hci_stack.local_name){
1242e2386ba1S[email protected]                         hci_send_cmd(&hci_write_local_name, hci_stack.local_name);
1243e2386ba1S[email protected]                     } else {
12448a485f27Smatthias.ringwald                         char hostname[30];
1245e2386ba1S[email protected] #ifdef EMBEDDED
1246e2386ba1S[email protected]                         // BTstack-11:22:33:44:55:66
1247e2386ba1S[email protected]                         strcpy(hostname, "BTstack ");
1248e2386ba1S[email protected]                         strcat(hostname, bd_addr_to_str(hci_stack.local_bd_addr));
1249e2386ba1S[email protected]                         printf("---> Name %s\n", hostname);
1250e2386ba1S[email protected] #else
1251e2386ba1S[email protected]                         // hostname for POSIX systems
12528a485f27Smatthias.ringwald                         gethostname(hostname, 30);
12538a485f27Smatthias.ringwald                         hostname[29] = '\0';
1254e2386ba1S[email protected] #endif
12558a485f27Smatthias.ringwald                         hci_send_cmd(&hci_write_local_name, hostname);
12568a485f27Smatthias.ringwald                     }
12573c4d4b90Smatthias.ringwald                     break;
1258e0dbca83S[email protected]                 case 11:
1259a45d6b9fS[email protected] 					hci_send_cmd(&hci_write_scan_enable, (hci_stack.connectable << 1) | hci_stack.discoverable); // page scan
1260a45d6b9fS[email protected] 					break;
1261a45d6b9fS[email protected]                 case 12:
12623429f56bSmatthias.ringwald                     // done.
12633429f56bSmatthias.ringwald                     hci_stack.state = HCI_STATE_WORKING;
1264b360b6adSmatthias.ringwald                     hci_emit_state();
12653429f56bSmatthias.ringwald                     break;
12663429f56bSmatthias.ringwald                 default:
12673429f56bSmatthias.ringwald                     break;
1268475c8125Smatthias.ringwald             }
12693429f56bSmatthias.ringwald             hci_stack.substate++;
12703429f56bSmatthias.ringwald             break;
1271c7e0c5f6Smatthias.ringwald 
1272c7e0c5f6Smatthias.ringwald         case HCI_STATE_HALTING:
1273c7e0c5f6Smatthias.ringwald 
12747b5fbe1fSmatthias.ringwald             log_info("HCI_STATE_HALTING\n");
1275c7e0c5f6Smatthias.ringwald             // close all open connections
1276c7e0c5f6Smatthias.ringwald             connection =  (hci_connection_t *) hci_stack.connections;
1277c7e0c5f6Smatthias.ringwald             if (connection){
127832ab9390Smatthias.ringwald 
1279c7e0c5f6Smatthias.ringwald                 // send disconnect
128032ab9390Smatthias.ringwald                 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
128132ab9390Smatthias.ringwald 
128279bbfa0bSmatthias.ringwald                 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
12836ad890d3Smatthias.ringwald                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
1284c7e0c5f6Smatthias.ringwald 
1285c7e0c5f6Smatthias.ringwald                 // send disconnected event right away - causes higher layer connections to get closed, too.
1286c7e0c5f6Smatthias.ringwald                 hci_shutdown_connection(connection);
1287c7e0c5f6Smatthias.ringwald                 return;
1288c7e0c5f6Smatthias.ringwald             }
12897b5fbe1fSmatthias.ringwald             log_info("HCI_STATE_HALTING, calling off\n");
1290c7e0c5f6Smatthias.ringwald 
129172ea5239Smatthias.ringwald             // switch mode
1292c7e0c5f6Smatthias.ringwald             hci_power_control_off();
12939418f9c9Smatthias.ringwald 
12947b5fbe1fSmatthias.ringwald             log_info("HCI_STATE_HALTING, emitting state\n");
129572ea5239Smatthias.ringwald             hci_emit_state();
12967b5fbe1fSmatthias.ringwald             log_info("HCI_STATE_HALTING, done\n");
129772ea5239Smatthias.ringwald             break;
1298c7e0c5f6Smatthias.ringwald 
129972ea5239Smatthias.ringwald         case HCI_STATE_FALLING_ASLEEP:
130089db417bSmatthias.ringwald             switch(hci_stack.substate) {
130189db417bSmatthias.ringwald                 case 0:
13027b5fbe1fSmatthias.ringwald                     log_info("HCI_STATE_FALLING_ASLEEP\n");
130372ea5239Smatthias.ringwald                     // close all open connections
130472ea5239Smatthias.ringwald                     connection =  (hci_connection_t *) hci_stack.connections;
130566da7044Smatthias.ringwald 
130628171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
130766da7044Smatthias.ringwald                     // don't close connections, if H4 supports power management
130866da7044Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
130966da7044Smatthias.ringwald                         connection = NULL;
131066da7044Smatthias.ringwald                     }
131166da7044Smatthias.ringwald #endif
131272ea5239Smatthias.ringwald                     if (connection){
131332ab9390Smatthias.ringwald 
131472ea5239Smatthias.ringwald                         // send disconnect
131532ab9390Smatthias.ringwald                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
131632ab9390Smatthias.ringwald 
131779bbfa0bSmatthias.ringwald                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle);
13186ad890d3Smatthias.ringwald                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
131972ea5239Smatthias.ringwald 
132072ea5239Smatthias.ringwald                         // send disconnected event right away - causes higher layer connections to get closed, too.
132172ea5239Smatthias.ringwald                         hci_shutdown_connection(connection);
132272ea5239Smatthias.ringwald                         return;
132372ea5239Smatthias.ringwald                     }
132472ea5239Smatthias.ringwald 
1325*92368cd3S[email protected]                     if (hci_classic_supported()){
132689db417bSmatthias.ringwald                         // disable page and inquiry scan
132732ab9390Smatthias.ringwald                         if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return;
132832ab9390Smatthias.ringwald 
1329*92368cd3S[email protected]                         log_info("HCI_STATE_HALTING, disabling inq scans\n");
1330758b46ceSmatthias.ringwald                         hci_send_cmd(&hci_write_scan_enable, hci_stack.connectable << 1); // drop inquiry scan but keep page scan
133189db417bSmatthias.ringwald 
133289db417bSmatthias.ringwald                         // continue in next sub state
133389db417bSmatthias.ringwald                         hci_stack.substate++;
133489db417bSmatthias.ringwald                         break;
1335*92368cd3S[email protected]                     }
1336*92368cd3S[email protected]                     // fall through for ble-only chips
1337*92368cd3S[email protected] 
133889db417bSmatthias.ringwald                 case 2:
13397b5fbe1fSmatthias.ringwald                     log_info("HCI_STATE_HALTING, calling sleep\n");
134028171530Smatthias.ringwald #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
134128171530Smatthias.ringwald                     // don't actually go to sleep, if H4 supports power management
134228171530Smatthias.ringwald                     if (bt_control_iphone_power_management_enabled()){
134328171530Smatthias.ringwald                         // SLEEP MODE reached
134428171530Smatthias.ringwald                         hci_stack.state = HCI_STATE_SLEEPING;
134528171530Smatthias.ringwald                         hci_emit_state();
134628171530Smatthias.ringwald                         break;
134728171530Smatthias.ringwald                     }
134828171530Smatthias.ringwald #endif
134972ea5239Smatthias.ringwald                     // switch mode
135089db417bSmatthias.ringwald                     hci_power_control_sleep();  // changes hci_stack.state to SLEEP
1351c7e0c5f6Smatthias.ringwald                     hci_emit_state();
135228171530Smatthias.ringwald                     break;
135328171530Smatthias.ringwald 
135489db417bSmatthias.ringwald                 default:
135589db417bSmatthias.ringwald                     break;
135689db417bSmatthias.ringwald             }
1357c7e0c5f6Smatthias.ringwald             break;
1358c7e0c5f6Smatthias.ringwald 
13593429f56bSmatthias.ringwald         default:
13603429f56bSmatthias.ringwald             break;
13611f504dbdSmatthias.ringwald     }
13623429f56bSmatthias.ringwald }
136316833f0aSmatthias.ringwald 
136431452debSmatthias.ringwald int hci_send_cmd_packet(uint8_t *packet, int size){
1365c8e4258aSmatthias.ringwald     bd_addr_t addr;
1366c8e4258aSmatthias.ringwald     hci_connection_t * conn;
1367c8e4258aSmatthias.ringwald     // house-keeping
1368c8e4258aSmatthias.ringwald 
1369c8e4258aSmatthias.ringwald     // create_connection?
1370c8e4258aSmatthias.ringwald     if (IS_COMMAND(packet, hci_create_connection)){
1371c8e4258aSmatthias.ringwald         bt_flip_addr(addr, &packet[3]);
1372339b6768Smatthias.ringwald         log_info("Create_connection to %s\n", bd_addr_to_str(addr));
1373c8e4258aSmatthias.ringwald         conn = connection_for_address(addr);
1374c8e4258aSmatthias.ringwald         if (conn) {
1375c8e4258aSmatthias.ringwald             // if connection exists
1376c8e4258aSmatthias.ringwald             if (conn->state == OPEN) {
137717f1ba2aSmatthias.ringwald                 // and OPEN, emit connection complete command
137817f1ba2aSmatthias.ringwald                 hci_emit_connection_complete(conn, 0);
1379c8e4258aSmatthias.ringwald             }
138017f1ba2aSmatthias.ringwald             //    otherwise, just ignore as it is already in the open process
1381c8e4258aSmatthias.ringwald             return 0; // don't sent packet to controller
1382c8e4258aSmatthias.ringwald 
138317f1ba2aSmatthias.ringwald         }
1384c8e4258aSmatthias.ringwald         // create connection struct and register, state = SENT_CREATE_CONNECTION
138517f1ba2aSmatthias.ringwald         conn = create_connection_for_addr(addr);
138617f1ba2aSmatthias.ringwald         if (!conn){
138717f1ba2aSmatthias.ringwald             // notify client that alloc failed
138817f1ba2aSmatthias.ringwald             hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
138917f1ba2aSmatthias.ringwald             return 0; // don't sent packet to controller
139017f1ba2aSmatthias.ringwald         }
1391c8e4258aSmatthias.ringwald         conn->state = SENT_CREATE_CONNECTION;
1392c8e4258aSmatthias.ringwald     }
1393c8e4258aSmatthias.ringwald 
13947fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_reply)){
13957fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
13967fde4af9Smatthias.ringwald     }
13977fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
13987fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
13997fde4af9Smatthias.ringwald     }
14007fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_pin_code_request_reply)){
14017fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_REPLY);
14027fde4af9Smatthias.ringwald     }
14037fde4af9Smatthias.ringwald     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)){
14047fde4af9Smatthias.ringwald         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_PIN_CODE_NEGATIVE_REPLY);
14057fde4af9Smatthias.ringwald     }
14067fde4af9Smatthias.ringwald 
14078ef73945Smatthias.ringwald     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
14088ef73945Smatthias.ringwald         if (hci_stack.remote_device_db){
14098ef73945Smatthias.ringwald             bt_flip_addr(addr, &packet[3]);
14108ef73945Smatthias.ringwald             hci_stack.remote_device_db->delete_link_key(&addr);
14118ef73945Smatthias.ringwald         }
14128ef73945Smatthias.ringwald     }
1413c8e4258aSmatthias.ringwald 
141431452debSmatthias.ringwald     hci_stack.num_cmd_packets--;
1415622d0de9Smatthias.ringwald     return hci_stack.hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
141631452debSmatthias.ringwald }
14178adf0ddaSmatthias.ringwald 
1418dbe1a790S[email protected] // Configure Secure Simple Pairing
1419dbe1a790S[email protected] 
1420dbe1a790S[email protected] // enable will enable SSP during init
1421dbe1a790S[email protected] void hci_ssp_set_enable(int enable){
1422dbe1a790S[email protected]     hci_stack.ssp_enable = enable;
1423dbe1a790S[email protected] }
1424dbe1a790S[email protected] 
1425dbe1a790S[email protected] // if set, BTstack will respond to io capability request using authentication requirement
1426dbe1a790S[email protected] void hci_ssp_set_io_capability(int io_capability){
1427dbe1a790S[email protected]     hci_stack.ssp_io_capability = io_capability;
1428dbe1a790S[email protected] }
1429dbe1a790S[email protected] void hci_ssp_set_authentication_requirement(int authentication_requirement){
1430dbe1a790S[email protected]     hci_stack.ssp_authentication_requirement = authentication_requirement;
1431dbe1a790S[email protected] }
1432dbe1a790S[email protected] 
1433dbe1a790S[email protected] // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
1434dbe1a790S[email protected] void hci_ssp_set_auto_accept(int auto_accept){
1435dbe1a790S[email protected]     hci_stack.ssp_auto_accept = auto_accept;
1436dbe1a790S[email protected] }
1437dbe1a790S[email protected] 
14381cd208adSmatthias.ringwald /**
14391cd208adSmatthias.ringwald  * pre: numcmds >= 0 - it's allowed to send a command to the controller
14401cd208adSmatthias.ringwald  */
1441fe35119dSmatthias.ringwald int hci_send_cmd(const hci_cmd_t *cmd, ...){
14421cd208adSmatthias.ringwald     va_list argptr;
14431cd208adSmatthias.ringwald     va_start(argptr, cmd);
14447dc17943Smatthias.ringwald     uint16_t size = hci_create_cmd_internal(hci_stack.hci_packet_buffer, cmd, argptr);
14451cd208adSmatthias.ringwald     va_end(argptr);
14467dc17943Smatthias.ringwald     return hci_send_cmd_packet(hci_stack.hci_packet_buffer, size);
144793b8dc03Smatthias.ringwald }
1448c8e4258aSmatthias.ringwald 
1449ee091cf1Smatthias.ringwald // Create various non-HCI events.
1450ee091cf1Smatthias.ringwald // TODO: generalize, use table similar to hci_create_command
1451ee091cf1Smatthias.ringwald 
1452c8e4258aSmatthias.ringwald void hci_emit_state(){
1453e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_STATE %u", hci_stack.state);
1454425d1371Smatthias.ringwald     uint8_t event[3];
145580d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_STATE;
1456425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
1457c8e4258aSmatthias.ringwald     event[2] = hci_stack.state;
1458425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1459425d1371Smatthias.ringwald     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1460c8e4258aSmatthias.ringwald }
1461c8e4258aSmatthias.ringwald 
146217f1ba2aSmatthias.ringwald void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
1463425d1371Smatthias.ringwald     uint8_t event[13];
1464c8e4258aSmatthias.ringwald     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
1465425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
146617f1ba2aSmatthias.ringwald     event[2] = status;
1467c8e4258aSmatthias.ringwald     bt_store_16(event, 3, conn->con_handle);
1468c8e4258aSmatthias.ringwald     bt_flip_addr(&event[5], conn->address);
1469c8e4258aSmatthias.ringwald     event[11] = 1; // ACL connection
1470c8e4258aSmatthias.ringwald     event[12] = 0; // encryption disabled
1471425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1472425d1371Smatthias.ringwald     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1473c8e4258aSmatthias.ringwald }
1474c8e4258aSmatthias.ringwald 
14753c4d4b90Smatthias.ringwald void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
1476425d1371Smatthias.ringwald     uint8_t event[6];
14773c4d4b90Smatthias.ringwald     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
1478e518c4b8Smatthias.ringwald     event[1] = sizeof(event) - 2;
14793c4d4b90Smatthias.ringwald     event[2] = 0; // status = OK
14803c4d4b90Smatthias.ringwald     bt_store_16(event, 3, handle);
14813c4d4b90Smatthias.ringwald     event[5] = reason;
1482425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1483425d1371Smatthias.ringwald     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
14843c4d4b90Smatthias.ringwald }
14853c4d4b90Smatthias.ringwald 
1486ee091cf1Smatthias.ringwald void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
1487e0abb8e7S[email protected]     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
1488425d1371Smatthias.ringwald     uint8_t event[4];
148980d52d6bSmatthias.ringwald     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
1490425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
1491ee091cf1Smatthias.ringwald     bt_store_16(event, 2, conn->con_handle);
1492425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1493425d1371Smatthias.ringwald     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1494ee091cf1Smatthias.ringwald }
149543bfb1bdSmatthias.ringwald 
149643bfb1bdSmatthias.ringwald void hci_emit_nr_connections_changed(){
1497e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
1498425d1371Smatthias.ringwald     uint8_t event[3];
149980d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
1500425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
150143bfb1bdSmatthias.ringwald     event[2] = nr_hci_connections();
1502425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1503425d1371Smatthias.ringwald     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
150443bfb1bdSmatthias.ringwald }
1505038bc64cSmatthias.ringwald 
1506038bc64cSmatthias.ringwald void hci_emit_hci_open_failed(){
1507e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_POWERON_FAILED");
1508425d1371Smatthias.ringwald     uint8_t event[2];
150980d52d6bSmatthias.ringwald     event[0] = BTSTACK_EVENT_POWERON_FAILED;
1510425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
1511425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1512425d1371Smatthias.ringwald     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1513038bc64cSmatthias.ringwald }
15141b0e3922Smatthias.ringwald 
151509ba8edeSmatthias.ringwald #ifndef EMBEDDED
15161b0e3922Smatthias.ringwald void hci_emit_btstack_version() {
1517e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
1518425d1371Smatthias.ringwald     uint8_t event[6];
15191b0e3922Smatthias.ringwald     event[0] = BTSTACK_EVENT_VERSION;
1520425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
1521425d1371Smatthias.ringwald     event[2] = BTSTACK_MAJOR;
1522425d1371Smatthias.ringwald     event[3] = BTSTACK_MINOR;
1523425d1371Smatthias.ringwald     bt_store_16(event, 4, BTSTACK_REVISION);
1524425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1525425d1371Smatthias.ringwald     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
15261b0e3922Smatthias.ringwald }
152709ba8edeSmatthias.ringwald #endif
15281b0e3922Smatthias.ringwald 
15292ed6235cSmatthias.ringwald void hci_emit_system_bluetooth_enabled(uint8_t enabled){
1530e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
1531425d1371Smatthias.ringwald     uint8_t event[3];
15322ed6235cSmatthias.ringwald     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
1533425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
15342ed6235cSmatthias.ringwald     event[2] = enabled;
1535425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1536e518c4b8Smatthias.ringwald     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
15372ed6235cSmatthias.ringwald }
1538627c2f45Smatthias.ringwald 
1539627c2f45Smatthias.ringwald void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
1540e0abb8e7S[email protected]     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
1541627c2f45Smatthias.ringwald     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
1542e0abb8e7S[email protected]     event[1] = sizeof(event) - 2 - 1;
1543f653b6bdSmatthias.ringwald     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
15442f89d309Smatthias.ringwald     bt_flip_addr(&event[3], *addr);
1545f653b6bdSmatthias.ringwald     memcpy(&event[9], name, 248);
1546e0abb8e7S[email protected] 
1547e0abb8e7S[email protected]     event[9+248] = 0;   // assert \0 for log_info
1548e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
1549e0abb8e7S[email protected] 
1550e0abb8e7S[email protected]     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
1551e0abb8e7S[email protected]     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
1552627c2f45Smatthias.ringwald }
1553381fbed8Smatthias.ringwald 
1554381fbed8Smatthias.ringwald void hci_emit_discoverable_enabled(uint8_t enabled){
1555e0abb8e7S[email protected]     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
1556425d1371Smatthias.ringwald     uint8_t event[3];
1557381fbed8Smatthias.ringwald     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
1558425d1371Smatthias.ringwald     event[1] = sizeof(event) - 2;
1559381fbed8Smatthias.ringwald     event[2] = enabled;
1560425d1371Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1561425d1371Smatthias.ringwald     hci_stack.packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
1562381fbed8Smatthias.ringwald }
1563