xref: /btstack/src/classic/hfp.c (revision 671f1aa2bc4ae3a024cb7e767ca67a16d7eb3055)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "hfp.c"
39 
40 
41 #include "btstack_config.h"
42 
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <inttypes.h>
48 
49 #include "bluetooth_sdp.h"
50 #include "btstack_debug.h"
51 #include "btstack_event.h"
52 #include "btstack_memory.h"
53 #include "btstack_run_loop.h"
54 #include "classic/core.h"
55 #include "classic/sdp_client_rfcomm.h"
56 #include "classic/sdp_server.h"
57 #include "classic/sdp_util.h"
58 #include "hci.h"
59 #include "hci_cmd.h"
60 #include "hci_dump.h"
61 #include "l2cap.h"
62 
63 #define HFP_HF_FEATURES_SIZE 10
64 #define HFP_AG_FEATURES_SIZE 12
65 
66 
67 static const char * hfp_hf_features[] = {
68     "EC and/or NR function",
69     "Three-way calling",
70     "CLI presentation capability",
71     "Voice recognition activation",
72     "Remote volume control",
73 
74     "Enhanced call status",
75     "Enhanced call control",
76 
77     "Codec negotiation",
78 
79     "HF Indicators",
80     "eSCO S4 (and T2) Settings Supported",
81     "Reserved for future definition"
82 };
83 
84 static const char * hfp_ag_features[] = {
85     "Three-way calling",
86     "EC and/or NR function",
87     "Voice recognition function",
88     "In-band ring tone capability",
89     "Attach a number to a voice tag",
90     "Ability to reject a call",
91     "Enhanced call status",
92     "Enhanced call control",
93     "Extended Error Result Codes",
94     "Codec negotiation",
95     "HF Indicators",
96     "eSCO S4 (and T2) Settings Supported",
97     "Reserved for future definition"
98 };
99 
100 static btstack_linked_list_t hfp_connections = NULL;
101 static void parse_sequence(hfp_connection_t * context);
102 
103 static btstack_packet_handler_t hfp_hf_callback;
104 static btstack_packet_handler_t hfp_ag_callback;
105 
106 static btstack_packet_handler_t hfp_hf_rfcomm_packet_handler;
107 static btstack_packet_handler_t hfp_ag_rfcomm_packet_handler;
108 
109 static hfp_connection_t * sco_establishment_active;
110 
111 void hfp_set_hf_callback(btstack_packet_handler_t callback){
112     hfp_hf_callback = callback;
113 }
114 
115 void hfp_set_ag_callback(btstack_packet_handler_t callback){
116     hfp_ag_callback = callback;
117 }
118 
119 const char * hfp_hf_feature(int index){
120     if (index > HFP_HF_FEATURES_SIZE){
121         return hfp_hf_features[HFP_HF_FEATURES_SIZE];
122     }
123     return hfp_hf_features[index];
124 }
125 
126 const char * hfp_ag_feature(int index){
127     if (index > HFP_AG_FEATURES_SIZE){
128         return hfp_ag_features[HFP_AG_FEATURES_SIZE];
129     }
130     return hfp_ag_features[index];
131 }
132 
133 int send_str_over_rfcomm(uint16_t cid, char * command){
134     if (!rfcomm_can_send_packet_now(cid)) return 1;
135     log_info("HFP_TX %s", command);
136     int err = rfcomm_send(cid, (uint8_t*) command, strlen(command));
137     if (err){
138         log_error("rfcomm_send -> error 0x%02x \n", err);
139     }
140     return 1;
141 }
142 
143 int hfp_supports_codec(uint8_t codec, int codecs_nr, uint8_t * codecs){
144 
145     // mSBC requires support for eSCO connections
146     if (codec == HFP_CODEC_MSBC && !hci_extended_sco_link_supported()) return 0;
147 
148     int i;
149     for (i = 0; i < codecs_nr; i++){
150         if (codecs[i] != codec) continue;
151         return 1;
152     }
153     return 0;
154 }
155 
156 void hfp_hf_drop_mSBC_if_eSCO_not_supported(uint8_t * codecs, uint8_t * codecs_nr){
157     if (hci_extended_sco_link_supported()) return;
158     uint8_t tmp_codecs[HFP_MAX_NUM_CODECS];
159     int i;
160     int tmp_codec_nr = 0;
161     for (i=0; i < *codecs_nr; i++){
162         if (codecs[i] == HFP_CODEC_MSBC) continue;
163         tmp_codecs[tmp_codec_nr++] = codecs[i];
164     }
165     *codecs_nr = tmp_codec_nr;
166     memcpy(codecs, tmp_codecs, tmp_codec_nr);
167 }
168 
169 // UTILS
170 int get_bit(uint16_t bitmap, int position){
171     return (bitmap >> position) & 1;
172 }
173 
174 int store_bit(uint32_t bitmap, int position, uint8_t value){
175     if (value){
176         bitmap |= 1 << position;
177     } else {
178         bitmap &= ~ (1 << position);
179     }
180     return bitmap;
181 }
182 
183 int join(char * buffer, int buffer_size, uint8_t * values, int values_nr){
184     if (buffer_size < values_nr * 3) return 0;
185     int i;
186     int offset = 0;
187     for (i = 0; i < values_nr-1; i++) {
188       offset += snprintf(buffer+offset, buffer_size-offset, "%d,", values[i]); // puts string into buffer
189     }
190     if (i<values_nr){
191         offset += snprintf(buffer+offset, buffer_size-offset, "%d", values[i]);
192     }
193     return offset;
194 }
195 
196 int join_bitmap(char * buffer, int buffer_size, uint32_t values, int values_nr){
197     if (buffer_size < values_nr * 3) return 0;
198 
199     int i;
200     int offset = 0;
201     for (i = 0; i < values_nr-1; i++) {
202       offset += snprintf(buffer+offset, buffer_size-offset, "%d,", get_bit(values,i)); // puts string into buffer
203     }
204 
205     if (i<values_nr){
206         offset += snprintf(buffer+offset, buffer_size-offset, "%d", get_bit(values,i));
207     }
208     return offset;
209 }
210 
211 static void hfp_emit_event_for_context(hfp_connection_t * hfp_connection, uint8_t * packet, uint16_t size){
212     if (!hfp_connection) return;
213     btstack_packet_handler_t callback = NULL;
214     switch (hfp_connection->local_role){
215         case HFP_ROLE_HF:
216             callback = hfp_hf_callback;
217             break;
218         case HFP_ROLE_AG:
219             callback = hfp_ag_callback;
220             break;
221         default:
222             return;
223     }
224     (*callback)(HCI_EVENT_PACKET, 0, packet, size);
225 }
226 
227 void hfp_emit_simple_event(hfp_connection_t * hfp_connection, uint8_t event_subtype){
228     uint8_t event[3];
229     event[0] = HCI_EVENT_HFP_META;
230     event[1] = sizeof(event) - 2;
231     event[2] = event_subtype;
232     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
233 }
234 
235 void hfp_emit_event(hfp_connection_t * hfp_connection, uint8_t event_subtype, uint8_t value){
236     uint8_t event[4];
237     event[0] = HCI_EVENT_HFP_META;
238     event[1] = sizeof(event) - 2;
239     event[2] = event_subtype;
240     event[3] = value; // status 0 == OK
241     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
242 }
243 
244 void hfp_emit_slc_connection_event(hfp_connection_t * hfp_connection, uint8_t status, hci_con_handle_t con_handle, bd_addr_t addr){
245     uint8_t event[12];
246     int pos = 0;
247     event[pos++] = HCI_EVENT_HFP_META;
248     event[pos++] = sizeof(event) - 2;
249     event[pos++] = HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
250     event[pos++] = status; // status 0 == OK
251     little_endian_store_16(event, pos, con_handle);
252     pos += 2;
253     reverse_bd_addr(addr,&event[pos]);
254     pos += 6;
255     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
256 }
257 
258 static void hfp_emit_sco_event(hfp_connection_t * hfp_connection, uint8_t status, hci_con_handle_t con_handle, bd_addr_t addr, uint8_t  negotiated_codec){
259     uint8_t event[13];
260     int pos = 0;
261     event[pos++] = HCI_EVENT_HFP_META;
262     event[pos++] = sizeof(event) - 2;
263     event[pos++] = HFP_SUBEVENT_AUDIO_CONNECTION_ESTABLISHED;
264     event[pos++] = status; // status 0 == OK
265     little_endian_store_16(event, pos, con_handle);
266     pos += 2;
267     reverse_bd_addr(addr,&event[pos]);
268     pos += 6;
269     event[pos++] = negotiated_codec;
270     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
271 }
272 
273 void hfp_emit_string_event(hfp_connection_t * hfp_connection, uint8_t event_subtype, const char * value){
274     uint8_t event[40];
275     event[0] = HCI_EVENT_HFP_META;
276     event[1] = sizeof(event) - 2;
277     event[2] = event_subtype;
278     int size = ( strlen(value) < sizeof(event) - 4) ? (int) strlen(value) : (int) sizeof(event) - 4;
279     strncpy((char*)&event[3], value, size);
280     event[3 + size] = 0;
281     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
282 }
283 
284 btstack_linked_list_t * hfp_get_connections(void){
285     return (btstack_linked_list_t *) &hfp_connections;
286 }
287 
288 hfp_connection_t * get_hfp_connection_context_for_rfcomm_cid(uint16_t cid){
289     btstack_linked_list_iterator_t it;
290     btstack_linked_list_iterator_init(&it, hfp_get_connections());
291     while (btstack_linked_list_iterator_has_next(&it)){
292         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
293         if (hfp_connection->rfcomm_cid == cid){
294             return hfp_connection;
295         }
296     }
297     return NULL;
298 }
299 
300 hfp_connection_t * get_hfp_connection_context_for_bd_addr(bd_addr_t bd_addr){
301     btstack_linked_list_iterator_t it;
302     btstack_linked_list_iterator_init(&it, hfp_get_connections());
303     while (btstack_linked_list_iterator_has_next(&it)){
304         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
305         if (memcmp(hfp_connection->remote_addr, bd_addr, 6) == 0) {
306             return hfp_connection;
307         }
308     }
309     return NULL;
310 }
311 
312 hfp_connection_t * get_hfp_connection_context_for_sco_handle(uint16_t handle){
313     btstack_linked_list_iterator_t it;
314     btstack_linked_list_iterator_init(&it, hfp_get_connections());
315     while (btstack_linked_list_iterator_has_next(&it)){
316         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
317         if (hfp_connection->sco_handle == handle){
318             return hfp_connection;
319         }
320     }
321     return NULL;
322 }
323 
324 hfp_connection_t * get_hfp_connection_context_for_acl_handle(uint16_t handle){
325     btstack_linked_list_iterator_t it;
326     btstack_linked_list_iterator_init(&it, hfp_get_connections());
327     while (btstack_linked_list_iterator_has_next(&it)){
328         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
329         if (hfp_connection->acl_handle == handle){
330             return hfp_connection;
331         }
332     }
333     return NULL;
334 }
335 
336 void hfp_reset_context_flags(hfp_connection_t * hfp_connection){
337     if (!hfp_connection) return;
338     hfp_connection->ok_pending = 0;
339     hfp_connection->send_error = 0;
340 
341     hfp_connection->keep_byte = 0;
342 
343     hfp_connection->change_status_update_for_individual_ag_indicators = 0;
344     hfp_connection->operator_name_changed = 0;
345 
346     hfp_connection->enable_extended_audio_gateway_error_report = 0;
347     hfp_connection->extended_audio_gateway_error = 0;
348 
349     // establish codecs hfp_connection
350     hfp_connection->suggested_codec = 0;
351     hfp_connection->negotiated_codec = 0;
352     hfp_connection->codec_confirmed = 0;
353 
354     hfp_connection->establish_audio_connection = 0;
355     hfp_connection->call_waiting_notification_enabled = 0;
356     hfp_connection->command = HFP_CMD_NONE;
357     hfp_connection->enable_status_update_for_ag_indicators = 0xFF;
358 }
359 
360 static hfp_connection_t * create_hfp_connection_context(void){
361     hfp_connection_t * hfp_connection = btstack_memory_hfp_connection_get();
362     if (!hfp_connection) return NULL;
363     // init state
364     memset(hfp_connection,0, sizeof(hfp_connection_t));
365 
366     hfp_connection->state = HFP_IDLE;
367     hfp_connection->call_state = HFP_CALL_IDLE;
368     hfp_connection->codecs_state = HFP_CODECS_IDLE;
369 
370     hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
371     hfp_connection->command = HFP_CMD_NONE;
372 
373     hfp_reset_context_flags(hfp_connection);
374 
375     btstack_linked_list_add(&hfp_connections, (btstack_linked_item_t*)hfp_connection);
376     return hfp_connection;
377 }
378 
379 static void remove_hfp_connection_context(hfp_connection_t * hfp_connection){
380     btstack_linked_list_remove(&hfp_connections, (btstack_linked_item_t*) hfp_connection);
381     btstack_memory_hfp_connection_free(hfp_connection);
382 }
383 
384 static hfp_connection_t * provide_hfp_connection_context_for_bd_addr(bd_addr_t bd_addr, hfp_role_t local_role){
385     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(bd_addr);
386     if (hfp_connection) return  hfp_connection;
387     hfp_connection = create_hfp_connection_context();
388     memcpy(hfp_connection->remote_addr, bd_addr, 6);
389     hfp_connection->local_role = local_role;
390     return hfp_connection;
391 }
392 
393 /* @param network.
394  * 0 == no ability to reject a call.
395  * 1 == ability to reject a call.
396  */
397 
398 /* @param suported_features
399  * HF bit 0: EC and/or NR function (yes/no, 1 = yes, 0 = no)
400  * HF bit 1: Call waiting or three-way calling(yes/no, 1 = yes, 0 = no)
401  * HF bit 2: CLI presentation capability (yes/no, 1 = yes, 0 = no)
402  * HF bit 3: Voice recognition activation (yes/no, 1= yes, 0 = no)
403  * HF bit 4: Remote volume control (yes/no, 1 = yes, 0 = no)
404  * HF bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
405  */
406  /* Bit position:
407  * AG bit 0: Three-way calling (yes/no, 1 = yes, 0 = no)
408  * AG bit 1: EC and/or NR function (yes/no, 1 = yes, 0 = no)
409  * AG bit 2: Voice recognition function (yes/no, 1 = yes, 0 = no)
410  * AG bit 3: In-band ring tone capability (yes/no, 1 = yes, 0 = no)
411  * AG bit 4: Attach a phone number to a voice tag (yes/no, 1 = yes, 0 = no)
412  * AG bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
413  */
414 
415 void hfp_create_sdp_record(uint8_t * service, uint32_t service_record_handle, uint16_t service_uuid, int rfcomm_channel_nr, const char * name){
416     uint8_t* attribute;
417     de_create_sequence(service);
418 
419     // 0x0000 "Service Record Handle"
420     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
421     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
422 
423     // 0x0001 "Service Class ID List"
424     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
425     attribute = de_push_sequence(service);
426     {
427         //  "UUID for Service"
428         de_add_number(attribute, DE_UUID, DE_SIZE_16, service_uuid);
429         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_GENERIC_AUDIO);
430     }
431     de_pop_sequence(service, attribute);
432 
433     // 0x0004 "Protocol Descriptor List"
434     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
435     attribute = de_push_sequence(service);
436     {
437         uint8_t* l2cpProtocol = de_push_sequence(attribute);
438         {
439             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
440         }
441         de_pop_sequence(attribute, l2cpProtocol);
442 
443         uint8_t* rfcomm = de_push_sequence(attribute);
444         {
445             de_add_number(rfcomm,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_RFCOMM);  // rfcomm_service
446             de_add_number(rfcomm,  DE_UINT, DE_SIZE_8,  rfcomm_channel_nr);  // rfcomm channel
447         }
448         de_pop_sequence(attribute, rfcomm);
449     }
450     de_pop_sequence(service, attribute);
451 
452 
453     // 0x0005 "Public Browse Group"
454     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
455     attribute = de_push_sequence(service);
456     {
457         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
458     }
459     de_pop_sequence(service, attribute);
460 
461     // 0x0009 "Bluetooth Profile Descriptor List"
462     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
463     attribute = de_push_sequence(service);
464     {
465         uint8_t *sppProfile = de_push_sequence(attribute);
466         {
467             de_add_number(sppProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HANDSFREE);
468             de_add_number(sppProfile,  DE_UINT, DE_SIZE_16, 0x0107); // Verision 1.7
469         }
470         de_pop_sequence(attribute, sppProfile);
471     }
472     de_pop_sequence(service, attribute);
473 
474     // 0x0100 "Service Name"
475     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
476     de_add_data(service,  DE_STRING, strlen(name), (uint8_t *) name);
477 }
478 
479 static hfp_connection_t * connection_doing_sdp_query = NULL;
480 
481 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
482     UNUSED(packet_type);    // ok: handling own sdp events
483     UNUSED(channel);        // ok: no channel
484     UNUSED(size);           // ok: handling own sdp events
485 
486     hfp_connection_t * hfp_connection = connection_doing_sdp_query;
487     if (!hfp_connection) {
488         log_error("handle_query_rfcomm_event, no connection");
489         return;
490     }
491 
492     switch (hci_event_packet_get_type(packet)){
493         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
494             hfp_connection->rfcomm_channel_nr = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
495             break;
496         case SDP_EVENT_QUERY_COMPLETE:
497             connection_doing_sdp_query = NULL;
498             if (hfp_connection->rfcomm_channel_nr > 0){
499                 hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
500                 log_info("HFP: SDP_EVENT_QUERY_COMPLETE context %p, addr %s, state %d", hfp_connection, bd_addr_to_str( hfp_connection->remote_addr),  hfp_connection->state);
501                 btstack_packet_handler_t packet_handler = hfp_connection->local_role == HFP_ROLE_AG ? hfp_ag_rfcomm_packet_handler : hfp_hf_rfcomm_packet_handler;
502                 rfcomm_create_channel(packet_handler, hfp_connection->remote_addr, hfp_connection->rfcomm_channel_nr, NULL);
503                 break;
504             }
505             hfp_connection->state = HFP_IDLE;
506             hfp_emit_slc_connection_event(hfp_connection, sdp_event_query_complete_get_status(packet), HCI_CON_HANDLE_INVALID, hfp_connection->remote_addr);
507             log_info("rfcomm service not found, status %u.", sdp_event_query_complete_get_status(packet));
508             break;
509         default:
510             break;
511     }
512 }
513 
514 static void hfp_handle_failed_sco_connection(uint8_t status){
515 
516     if (!sco_establishment_active){
517         log_error("(e)SCO Connection failed but not started by us");
518         return;
519     }
520     log_error("(e)SCO Connection failed status 0x%02x", status);
521 
522     // invalid params / unspecified error
523     if (status != 0x11 && status != 0x1f) return;
524 
525      switch (sco_establishment_active->link_setting){
526         case HFP_LINK_SETTINGS_D0:
527             return; // no other option left
528         case HFP_LINK_SETTINGS_D1:
529             sco_establishment_active->link_setting = HFP_LINK_SETTINGS_D0;
530             break;
531         case HFP_LINK_SETTINGS_S1:
532             sco_establishment_active->link_setting = HFP_LINK_SETTINGS_D1;
533             break;
534         case HFP_LINK_SETTINGS_S2:
535             sco_establishment_active->link_setting = HFP_LINK_SETTINGS_S1;
536             break;
537         case HFP_LINK_SETTINGS_S3:
538             sco_establishment_active->link_setting = HFP_LINK_SETTINGS_S2;
539             break;
540         case HFP_LINK_SETTINGS_S4:
541             sco_establishment_active->link_setting = HFP_LINK_SETTINGS_S3;
542             break;
543         case HFP_LINK_SETTINGS_T1:
544             log_info("T1 failed, fallback to CVSD - D1");
545             sco_establishment_active->negotiated_codec = HFP_CODEC_CVSD;
546             sco_establishment_active->sco_for_msbc_failed = 1;
547             sco_establishment_active->command = HFP_CMD_AG_SEND_COMMON_CODEC;
548             sco_establishment_active->link_setting = HFP_LINK_SETTINGS_D1;
549             break;
550         case HFP_LINK_SETTINGS_T2:
551             sco_establishment_active->link_setting = HFP_LINK_SETTINGS_T1;
552             break;
553     }
554     sco_establishment_active->establish_audio_connection = 1;
555     sco_establishment_active = 0;
556 }
557 
558 
559 void hfp_handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
560     UNUSED(channel);    // ok: no channel
561 
562     bd_addr_t event_addr;
563     uint16_t rfcomm_cid, handle;
564     hfp_connection_t * hfp_connection = NULL;
565     uint8_t status;
566 
567     log_debug("HFP packet_handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
568 
569     switch (hci_event_packet_get_type(packet)) {
570         case HCI_EVENT_CONNECTION_REQUEST:
571             // printf("hfp HCI_EVENT_CONNECTION_REQUEST\n");
572             switch(hci_event_connection_request_get_link_type(packet)){
573                 case 0: //  SCO
574                 case 2: // eSCO
575                     hci_event_connection_request_get_bd_addr(packet, event_addr);
576                     hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr);
577                     if (!hfp_connection) break;
578                     hfp_connection->hf_accept_sco = 1;
579                     break;
580                 default:
581                     break;
582             }
583             break;
584 
585         case RFCOMM_EVENT_INCOMING_CONNECTION:
586             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
587             rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
588             hfp_connection = provide_hfp_connection_context_for_bd_addr(event_addr, local_role);
589             if (!hfp_connection){
590                 log_info("hfp: no memory to accept incoming connection - decline");
591                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
592                 return;
593             }
594             if (hfp_connection->state != HFP_IDLE) {
595                 log_error("hfp: incoming connection but state != HFP_IDLE");
596                 return;
597             }
598 
599             hfp_connection->rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
600             hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
601             // printf("RFCOMM channel %u requested for %s\n", hfp_connection->rfcomm_cid, bd_addr_to_str(hfp_connection->remote_addr));
602             rfcomm_accept_connection(hfp_connection->rfcomm_cid);
603             break;
604 
605         case RFCOMM_EVENT_CHANNEL_OPENED:
606             // data: event(8), len(8), status (8), address (48), handle(16), server channel(8), rfcomm_cid(16), max frame size(16)
607 
608             rfcomm_event_channel_opened_get_bd_addr(packet, event_addr);
609             status = rfcomm_event_channel_opened_get_status(packet);
610 
611             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr);
612             if (!hfp_connection || hfp_connection->state != HFP_W4_RFCOMM_CONNECTED) return;
613 
614             if (status) {
615                 hfp_emit_slc_connection_event(hfp_connection, status, rfcomm_event_channel_opened_get_con_handle(packet), event_addr);
616                 remove_hfp_connection_context(hfp_connection);
617             } else {
618                 hfp_connection->acl_handle = rfcomm_event_channel_opened_get_con_handle(packet);
619                 hfp_connection->rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
620                 bd_addr_copy(hfp_connection->remote_addr, event_addr);
621                 // uint16_t mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
622                 // printf("RFCOMM channel open succeeded. hfp_connection %p, RFCOMM Channel ID 0x%02x, max frame size %u\n", hfp_connection, hfp_connection->rfcomm_cid, mtu);
623 
624                 switch (hfp_connection->state){
625                     case HFP_W4_RFCOMM_CONNECTED:
626                         hfp_connection->state = HFP_EXCHANGE_SUPPORTED_FEATURES;
627                         break;
628                     case HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN:
629                         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
630                         // printf("Shutting down RFCOMM.\n");
631                         break;
632                     default:
633                         break;
634                 }
635                 rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
636             }
637             break;
638 
639         case HCI_EVENT_COMMAND_STATUS:
640             if (hci_event_command_status_get_command_opcode(packet) == hci_setup_synchronous_connection.opcode) {
641                 status = hci_event_command_status_get_status(packet);
642                 if (status) {
643                     hfp_handle_failed_sco_connection(hci_event_command_status_get_status(packet));
644                }
645             }
646             break;
647 
648         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
649             hci_event_synchronous_connection_complete_get_bd_addr(packet, event_addr);
650             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr);
651             if (!hfp_connection) {
652                 log_error("HFP: connection does not exist for remote with addr %s.", bd_addr_to_str(event_addr));
653                 return;
654             }
655 
656             status = hci_event_synchronous_connection_complete_get_status(packet);
657             if (status != 0){
658                 hfp_connection->hf_accept_sco = 0;
659                 hfp_handle_failed_sco_connection(status);
660                 break;
661             }
662 
663             uint16_t sco_handle = hci_event_synchronous_connection_complete_get_handle(packet);
664             uint8_t  link_type = hci_event_synchronous_connection_complete_get_link_type(packet);
665             uint8_t  transmission_interval = hci_event_synchronous_connection_complete_get_transmission_interval(packet);  // measured in slots
666             uint8_t  retransmission_interval = hci_event_synchronous_connection_complete_get_retransmission_interval(packet);// measured in slots
667             uint16_t rx_packet_length = hci_event_synchronous_connection_complete_get_rx_packet_length(packet); // measured in bytes
668             uint16_t tx_packet_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet); // measured in bytes
669             uint8_t  air_mode = hci_event_synchronous_connection_complete_get_air_mode(packet);
670 
671             switch (link_type){
672                 case 0x00:
673                     log_info("SCO Connection established.");
674                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
675                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
676                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
677                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
678                     break;
679                 case 0x02:
680                     log_info("eSCO Connection established. \n");
681                     break;
682                 default:
683                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
684                     break;
685             }
686             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
687                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)\n", sco_handle,
688                  bd_addr_to_str(event_addr), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length, air_mode);
689 
690             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr);
691 
692             if (!hfp_connection) {
693                 log_error("SCO link created, hfp_connection for address %s not found.", bd_addr_to_str(event_addr));
694                 break;
695             }
696 
697             if (hfp_connection->state == HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){
698                 log_info("SCO about to disconnect: HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN");
699                 hfp_connection->state = HFP_W2_DISCONNECT_SCO;
700                 break;
701             }
702             hfp_connection->sco_handle = sco_handle;
703             hfp_connection->establish_audio_connection = 0;
704             hfp_connection->state = HFP_AUDIO_CONNECTION_ESTABLISHED;
705             hfp_emit_sco_event(hfp_connection, packet[2], sco_handle, event_addr, hfp_connection->negotiated_codec);
706             break;
707         }
708 
709         case RFCOMM_EVENT_CHANNEL_CLOSED:
710             rfcomm_cid = little_endian_read_16(packet,2);
711             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
712             if (!hfp_connection) break;
713             if (hfp_connection->state == HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART){
714                 hfp_connection->state = HFP_IDLE;
715                 hfp_establish_service_level_connection(hfp_connection->remote_addr, hfp_connection->service_uuid, local_role);
716                 break;
717             }
718 
719             hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
720             remove_hfp_connection_context(hfp_connection);
721             break;
722 
723         case HCI_EVENT_DISCONNECTION_COMPLETE:
724             handle = little_endian_read_16(packet,3);
725             hfp_connection = get_hfp_connection_context_for_sco_handle(handle);
726 
727             if (!hfp_connection) break;
728 
729             if (hfp_connection->state != HFP_W4_SCO_DISCONNECTED){
730                 log_info("Received gap disconnect in wrong hfp state");
731             }
732             log_info("Check SCO handle: incoming 0x%02x, hfp_connection 0x%02x\n", handle, hfp_connection->sco_handle);
733 
734             if (handle == hfp_connection->sco_handle){
735                 log_info("SCO disconnected, w2 disconnect RFCOMM\n");
736                 hfp_connection->sco_handle = 0;
737                 hfp_connection->release_audio_connection = 0;
738                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
739                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_AUDIO_CONNECTION_RELEASED, 0);
740                 break;
741             }
742             break;
743 
744         default:
745             break;
746     }
747 }
748 
749 // translates command string into hfp_command_t CMD
750 static hfp_command_t parse_command(const char * line_buffer, int isHandsFree){
751     int offset = isHandsFree ? 0 : 2;
752 
753     if (strncmp(line_buffer+offset, HFP_LIST_CURRENT_CALLS, strlen(HFP_LIST_CURRENT_CALLS)) == 0){
754         return HFP_CMD_LIST_CURRENT_CALLS;
755     }
756 
757     if (strncmp(line_buffer+offset, HFP_SUBSCRIBER_NUMBER_INFORMATION, strlen(HFP_SUBSCRIBER_NUMBER_INFORMATION)) == 0){
758         return HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION;
759     }
760 
761     if (strncmp(line_buffer+offset, HFP_PHONE_NUMBER_FOR_VOICE_TAG, strlen(HFP_PHONE_NUMBER_FOR_VOICE_TAG)) == 0){
762         if (isHandsFree) return HFP_CMD_AG_SENT_PHONE_NUMBER;
763         return HFP_CMD_HF_REQUEST_PHONE_NUMBER;
764     }
765 
766     if (strncmp(line_buffer+offset, HFP_TRANSMIT_DTMF_CODES, strlen(HFP_TRANSMIT_DTMF_CODES)) == 0){
767         return HFP_CMD_TRANSMIT_DTMF_CODES;
768     }
769 
770     if (strncmp(line_buffer+offset, HFP_SET_MICROPHONE_GAIN, strlen(HFP_SET_MICROPHONE_GAIN)) == 0){
771         return HFP_CMD_SET_MICROPHONE_GAIN;
772     }
773 
774     if (strncmp(line_buffer+offset, HFP_SET_SPEAKER_GAIN, strlen(HFP_SET_SPEAKER_GAIN)) == 0){
775         return HFP_CMD_SET_SPEAKER_GAIN;
776     }
777 
778     if (strncmp(line_buffer+offset, HFP_ACTIVATE_VOICE_RECOGNITION, strlen(HFP_ACTIVATE_VOICE_RECOGNITION)) == 0){
779         if (isHandsFree) return HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
780         return HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION;
781     }
782 
783     if (strncmp(line_buffer+offset, HFP_TURN_OFF_EC_AND_NR, strlen(HFP_TURN_OFF_EC_AND_NR)) == 0){
784         return HFP_CMD_TURN_OFF_EC_AND_NR;
785     }
786 
787     if (strncmp(line_buffer, HFP_CALL_ANSWERED, strlen(HFP_CALL_ANSWERED)) == 0){
788         return HFP_CMD_CALL_ANSWERED;
789     }
790 
791     if (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0){
792         return HFP_CMD_CALL_PHONE_NUMBER;
793     }
794 
795     if (strncmp(line_buffer+offset, HFP_REDIAL_LAST_NUMBER, strlen(HFP_REDIAL_LAST_NUMBER)) == 0){
796         return HFP_CMD_REDIAL_LAST_NUMBER;
797     }
798 
799     if (strncmp(line_buffer+offset, HFP_CHANGE_IN_BAND_RING_TONE_SETTING, strlen(HFP_CHANGE_IN_BAND_RING_TONE_SETTING)) == 0){
800         return HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING;
801     }
802 
803     if (strncmp(line_buffer+offset, HFP_HANG_UP_CALL, strlen(HFP_HANG_UP_CALL)) == 0){
804         return HFP_CMD_HANG_UP_CALL;
805     }
806 
807     if (strncmp(line_buffer+offset, HFP_ERROR, strlen(HFP_ERROR)) == 0){
808         return HFP_CMD_ERROR;
809     }
810 
811     if (strncmp(line_buffer+offset, HFP_RING, strlen(HFP_RING)) == 0){
812         return HFP_CMD_RING;
813     }
814 
815     if (isHandsFree && strncmp(line_buffer+offset, HFP_OK, strlen(HFP_OK)) == 0){
816         return HFP_CMD_OK;
817     }
818 
819     if (strncmp(line_buffer+offset, HFP_SUPPORTED_FEATURES, strlen(HFP_SUPPORTED_FEATURES)) == 0){
820         return HFP_CMD_SUPPORTED_FEATURES;
821     }
822 
823     if (strncmp(line_buffer+offset, HFP_TRANSFER_HF_INDICATOR_STATUS, strlen(HFP_TRANSFER_HF_INDICATOR_STATUS)) == 0){
824         return HFP_CMD_HF_INDICATOR_STATUS;
825     }
826 
827     if (strncmp(line_buffer+offset, HFP_RESPONSE_AND_HOLD, strlen(HFP_RESPONSE_AND_HOLD)) == 0){
828         if (strncmp(line_buffer+strlen(HFP_RESPONSE_AND_HOLD)+offset, "?", 1) == 0){
829             return HFP_CMD_RESPONSE_AND_HOLD_QUERY;
830         }
831         if (strncmp(line_buffer+strlen(HFP_RESPONSE_AND_HOLD)+offset, "=", 1) == 0){
832             return HFP_CMD_RESPONSE_AND_HOLD_COMMAND;
833         }
834         return HFP_CMD_RESPONSE_AND_HOLD_STATUS;
835     }
836 
837     if (strncmp(line_buffer+offset, HFP_INDICATOR, strlen(HFP_INDICATOR)) == 0){
838         if (strncmp(line_buffer+strlen(HFP_INDICATOR)+offset, "?", 1) == 0){
839             return HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
840         }
841 
842         if (strncmp(line_buffer+strlen(HFP_INDICATOR)+offset, "=?", 2) == 0){
843             return HFP_CMD_RETRIEVE_AG_INDICATORS;
844         }
845     }
846 
847     if (strncmp(line_buffer+offset, HFP_AVAILABLE_CODECS, strlen(HFP_AVAILABLE_CODECS)) == 0){
848         return HFP_CMD_AVAILABLE_CODECS;
849     }
850 
851     if (strncmp(line_buffer+offset, HFP_ENABLE_STATUS_UPDATE_FOR_AG_INDICATORS, strlen(HFP_ENABLE_STATUS_UPDATE_FOR_AG_INDICATORS)) == 0){
852         return HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE;
853     }
854 
855     if (strncmp(line_buffer+offset, HFP_ENABLE_CLIP, strlen(HFP_ENABLE_CLIP)) == 0){
856         if (isHandsFree) return HFP_CMD_AG_SENT_CLIP_INFORMATION;
857         return HFP_CMD_ENABLE_CLIP;
858     }
859 
860     if (strncmp(line_buffer+offset, HFP_ENABLE_CALL_WAITING_NOTIFICATION, strlen(HFP_ENABLE_CALL_WAITING_NOTIFICATION)) == 0){
861         if (isHandsFree) return HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE;
862         return HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION;
863     }
864 
865     if (strncmp(line_buffer+offset, HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES, strlen(HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES)) == 0){
866 
867         if (isHandsFree) return HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES;
868 
869         if (strncmp(line_buffer+strlen(HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES)+offset, "=?", 2) == 0){
870             return HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES;
871         }
872         if (strncmp(line_buffer+strlen(HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES)+offset, "=", 1) == 0){
873             return HFP_CMD_CALL_HOLD;
874         }
875 
876         return HFP_CMD_UNKNOWN;
877     }
878 
879     if (strncmp(line_buffer+offset, HFP_GENERIC_STATUS_INDICATOR, strlen(HFP_GENERIC_STATUS_INDICATOR)) == 0){
880         if (isHandsFree) {
881             return HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS;
882         }
883         if (strncmp(line_buffer+strlen(HFP_GENERIC_STATUS_INDICATOR)+offset, "=?", 2) == 0){
884             return HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS;
885         }
886         if (strncmp(line_buffer+strlen(HFP_GENERIC_STATUS_INDICATOR)+offset, "=", 1) == 0){
887             return HFP_CMD_LIST_GENERIC_STATUS_INDICATORS;
888         }
889         return HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE;
890     }
891 
892     if (strncmp(line_buffer+offset, HFP_UPDATE_ENABLE_STATUS_FOR_INDIVIDUAL_AG_INDICATORS, strlen(HFP_UPDATE_ENABLE_STATUS_FOR_INDIVIDUAL_AG_INDICATORS)) == 0){
893         return HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE;
894     }
895 
896 
897     if (strncmp(line_buffer+offset, HFP_QUERY_OPERATOR_SELECTION, strlen(HFP_QUERY_OPERATOR_SELECTION)) == 0){
898         if (strncmp(line_buffer+strlen(HFP_QUERY_OPERATOR_SELECTION)+offset, "=", 1) == 0){
899             return HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT;
900         }
901         return HFP_CMD_QUERY_OPERATOR_SELECTION_NAME;
902     }
903 
904     if (strncmp(line_buffer+offset, HFP_TRANSFER_AG_INDICATOR_STATUS, strlen(HFP_TRANSFER_AG_INDICATOR_STATUS)) == 0){
905         return HFP_CMD_TRANSFER_AG_INDICATOR_STATUS;
906     }
907 
908     if (isHandsFree && strncmp(line_buffer+offset, HFP_EXTENDED_AUDIO_GATEWAY_ERROR, strlen(HFP_EXTENDED_AUDIO_GATEWAY_ERROR)) == 0){
909         return HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR;
910     }
911 
912     if (!isHandsFree && strncmp(line_buffer+offset, HFP_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR, strlen(HFP_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR)) == 0){
913         return HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR;
914     }
915 
916     if (strncmp(line_buffer+offset, HFP_TRIGGER_CODEC_CONNECTION_SETUP, strlen(HFP_TRIGGER_CODEC_CONNECTION_SETUP)) == 0){
917         return HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP;
918     }
919 
920     if (strncmp(line_buffer+offset, HFP_CONFIRM_COMMON_CODEC, strlen(HFP_CONFIRM_COMMON_CODEC)) == 0){
921         if (isHandsFree){
922             return HFP_CMD_AG_SUGGESTED_CODEC;
923         } else {
924             return HFP_CMD_HF_CONFIRMED_CODEC;
925         }
926     }
927 
928     if (strncmp(line_buffer+offset, "AT+", 3) == 0){
929         log_info("process unknown HF command %s \n", line_buffer);
930         return HFP_CMD_UNKNOWN;
931     }
932 
933     if (strncmp(line_buffer+offset, "+", 1) == 0){
934         log_info(" process unknown AG command %s \n", line_buffer);
935         return HFP_CMD_UNKNOWN;
936     }
937 
938     if (strncmp(line_buffer+offset, "NOP", 3) == 0){
939         return HFP_CMD_NONE;
940     }
941 
942     return HFP_CMD_NONE;
943 }
944 
945 static void hfp_parser_store_byte(hfp_connection_t * hfp_connection, uint8_t byte){
946     // printf("hfp_parser_store_byte %c at pos %u\n", (char) byte, context->line_size);
947     // TODO: add limit
948     hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
949     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
950 }
951 static int hfp_parser_is_buffer_empty(hfp_connection_t * hfp_connection){
952     return hfp_connection->line_size == 0;
953 }
954 
955 static int hfp_parser_is_end_of_line(uint8_t byte){
956     return byte == '\n' || byte == '\r';
957 }
958 
959 static int hfp_parser_is_end_of_header(uint8_t byte){
960     return hfp_parser_is_end_of_line(byte) || byte == ':' || byte == '?';
961 }
962 
963 static int hfp_parser_found_separator(hfp_connection_t * hfp_connection, uint8_t byte){
964     if (hfp_connection->keep_byte == 1) return 1;
965 
966     int found_separator =   byte == ',' || byte == '\n'|| byte == '\r'||
967                             byte == ')' || byte == '(' || byte == ':' ||
968                             byte == '-' || byte == '"' ||  byte == '?'|| byte == '=';
969     return found_separator;
970 }
971 
972 static void hfp_parser_next_state(hfp_connection_t * hfp_connection, uint8_t byte){
973     hfp_connection->line_size = 0;
974     if (hfp_parser_is_end_of_line(byte)){
975         hfp_connection->parser_item_index = 0;
976         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
977         return;
978     }
979     switch (hfp_connection->parser_state){
980         case HFP_PARSER_CMD_HEADER:
981             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
982             if (hfp_connection->keep_byte == 1){
983                 hfp_parser_store_byte(hfp_connection, byte);
984                 hfp_connection->keep_byte = 0;
985             }
986             break;
987         case HFP_PARSER_CMD_SEQUENCE:
988             switch (hfp_connection->command){
989                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
990                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
991                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
992                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
993                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
994                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
995                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
996                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
997                 case HFP_CMD_HF_INDICATOR_STATUS:
998                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
999                     break;
1000                 default:
1001                     break;
1002             }
1003             break;
1004         case HFP_PARSER_SECOND_ITEM:
1005             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
1006             break;
1007         case HFP_PARSER_THIRD_ITEM:
1008             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){
1009                 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1010                 break;
1011             }
1012             hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1013             break;
1014     }
1015 }
1016 
1017 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1018     // handle ATD<dial_string>;
1019     if (strncmp((const char*)hfp_connection->line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0){
1020         // check for end-of-line or ';'
1021         if (byte == ';' || hfp_parser_is_end_of_line(byte)){
1022             hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1023             hfp_connection->line_size = 0;
1024             hfp_connection->command = HFP_CMD_CALL_PHONE_NUMBER;
1025         } else {
1026             hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
1027         }
1028         return;
1029     }
1030 
1031     // TODO: handle space inside word
1032     if (byte == ' ' && hfp_connection->parser_state > HFP_PARSER_CMD_HEADER) return;
1033 
1034     if (byte == ',' && hfp_connection->command == HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE){
1035         if (hfp_connection->line_size == 0){
1036             hfp_connection->line_buffer[0] = 0;
1037             hfp_connection->ignore_value = 1;
1038             parse_sequence(hfp_connection);
1039             return;
1040         }
1041     }
1042 
1043     if (!hfp_parser_found_separator(hfp_connection, byte)){
1044         hfp_parser_store_byte(hfp_connection, byte);
1045         return;
1046     }
1047 
1048     if (hfp_parser_is_end_of_line(byte)) {
1049         if (hfp_parser_is_buffer_empty(hfp_connection)){
1050             hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1051         }
1052     }
1053     if (hfp_parser_is_buffer_empty(hfp_connection)) return;
1054 
1055     switch (hfp_connection->parser_state){
1056         case HFP_PARSER_CMD_HEADER: // header
1057             if (byte == '='){
1058                 hfp_connection->keep_byte = 1;
1059                 hfp_parser_store_byte(hfp_connection, byte);
1060                 return;
1061             }
1062 
1063             if (byte == '?'){
1064                 hfp_connection->keep_byte = 0;
1065                 hfp_parser_store_byte(hfp_connection, byte);
1066                 return;
1067             }
1068 
1069             if (byte == ','){
1070                 hfp_connection->resolve_byte = 1;
1071             }
1072 
1073             // printf(" parse header 2 %s, keep separator $ %d\n", hfp_connection->line_buffer, hfp_connection->keep_byte);
1074             if (hfp_parser_is_end_of_header(byte) || hfp_connection->keep_byte == 1){
1075                 // printf(" parse header 3 %s, keep separator $ %d\n", hfp_connection->line_buffer, hfp_connection->keep_byte);
1076                 char * line_buffer = (char *)hfp_connection->line_buffer;
1077                 hfp_connection->command = parse_command(line_buffer, isHandsFree);
1078 
1079                 /* resolve command name according to hfp_connection */
1080                 if (hfp_connection->command == HFP_CMD_UNKNOWN){
1081                     switch(hfp_connection->state){
1082                         case HFP_W4_LIST_GENERIC_STATUS_INDICATORS:
1083                             hfp_connection->command = HFP_CMD_LIST_GENERIC_STATUS_INDICATORS;
1084                             break;
1085                         case HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS:
1086                             hfp_connection->command = HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS;
1087                             break;
1088                         case HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS:
1089                             hfp_connection->command = HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE;
1090                             break;
1091                         case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1092                             hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
1093                             break;
1094                         case HFP_W4_RETRIEVE_INDICATORS:
1095                             hfp_connection->send_ag_indicators_segment = 0;
1096                             hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS;
1097                             break;
1098                         default:
1099                             break;
1100                     }
1101                 }
1102             }
1103             break;
1104 
1105         case HFP_PARSER_CMD_SEQUENCE:
1106             parse_sequence(hfp_connection);
1107             break;
1108         case HFP_PARSER_SECOND_ITEM:
1109             switch (hfp_connection->command){
1110                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1111                     log_info("format %s, ", hfp_connection->line_buffer);
1112                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1113                     break;
1114                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1115                     log_info("format %s \n", hfp_connection->line_buffer);
1116                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1117                     break;
1118                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1119                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1120                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1121                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1122                     break;
1123                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1124                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1125                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1126                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1127                     break;
1128                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1129                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer);
1130                     log_info("%s, ", hfp_connection->line_buffer);
1131                     break;
1132                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1133                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1134                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1135                     hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1136                     break;
1137                 default:
1138                     break;
1139             }
1140             break;
1141 
1142         case HFP_PARSER_THIRD_ITEM:
1143              switch (hfp_connection->command){
1144                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1145                     strncpy(hfp_connection->network_operator.name, (char *)hfp_connection->line_buffer, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE);
1146                     hfp_connection->network_operator.name[HFP_MAX_NETWORK_OPERATOR_NAME_SIZE - 1] = 0;
1147                     log_info("name %s\n", hfp_connection->line_buffer);
1148                     break;
1149                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1150                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer);
1151                     hfp_connection->parser_item_index++;
1152                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1153                     log_info("%s)\n", hfp_connection->line_buffer);
1154                     break;
1155                 default:
1156                     break;
1157             }
1158             break;
1159     }
1160     hfp_parser_next_state(hfp_connection, byte);
1161 
1162     if (hfp_connection->resolve_byte && hfp_connection->command == HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE){
1163         hfp_connection->resolve_byte = 0;
1164         hfp_connection->ignore_value = 1;
1165         parse_sequence(hfp_connection);
1166         hfp_connection->line_buffer[0] = 0;
1167         hfp_connection->line_size = 0;
1168     }
1169 }
1170 
1171 static void parse_sequence(hfp_connection_t * hfp_connection){
1172     int value;
1173     switch (hfp_connection->command){
1174         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1175             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1176             int i;
1177             switch (hfp_connection->parser_item_index){
1178                 case 0:
1179                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1180                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1181                             hfp_connection->parser_indicator_index = i;
1182                             break;
1183                         }
1184                     }
1185                     break;
1186                 case 1:
1187                     if (hfp_connection->parser_indicator_index <0) break;
1188                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1189                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1190                      hfp_connection->parser_item_index, value);
1191                     break;
1192                 default:
1193                     break;
1194             }
1195             hfp_connection->parser_item_index++;
1196             break;
1197 
1198         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1199             switch(hfp_connection->parser_item_index){
1200                 case 0:
1201                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1202                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1203                     break;
1204                 case 1:
1205                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1206                     hfp_connection->bnip_type = value;
1207                     break;
1208                 default:
1209                     break;
1210             }
1211             hfp_connection->parser_item_index++;
1212             break;
1213         case HFP_CMD_LIST_CURRENT_CALLS:
1214             switch(hfp_connection->parser_item_index){
1215                 case 0:
1216                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1217                     hfp_connection->clcc_idx = value;
1218                     break;
1219                 case 1:
1220                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1221                     hfp_connection->clcc_dir = value;
1222                     break;
1223                 case 2:
1224                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1225                     hfp_connection->clcc_status = value;
1226                     break;
1227                 case 3:
1228                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1229                     hfp_connection->clcc_mpty = value;
1230                     break;
1231                 case 4:
1232                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1233                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1234                     break;
1235                 case 5:
1236                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1237                     hfp_connection->bnip_type = value;
1238                     break;
1239                 default:
1240                     break;
1241             }
1242             hfp_connection->parser_item_index++;
1243             break;
1244         case HFP_CMD_SET_MICROPHONE_GAIN:
1245             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1246             hfp_connection->microphone_gain = value;
1247             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1248             break;
1249         case HFP_CMD_SET_SPEAKER_GAIN:
1250             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1251             hfp_connection->speaker_gain = value;
1252             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1253             break;
1254         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1255             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1256             hfp_connection->ag_activate_voice_recognition = value;
1257             log_info("hfp parse HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION %d\n", value);
1258             break;
1259         case HFP_CMD_TURN_OFF_EC_AND_NR:
1260             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1261             hfp_connection->ag_echo_and_noise_reduction = value;
1262             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1263             break;
1264         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1265             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1266             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1267             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1268             break;
1269         case HFP_CMD_HF_CONFIRMED_CODEC:
1270             hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer);
1271             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1272             break;
1273         case HFP_CMD_AG_SUGGESTED_CODEC:
1274             hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer);
1275             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1276             break;
1277         case HFP_CMD_SUPPORTED_FEATURES:
1278             hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer);
1279             log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features);
1280             break;
1281         case HFP_CMD_AVAILABLE_CODECS:
1282             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1283             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1284             hfp_connection->parser_item_index++;
1285             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1286             break;
1287         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1288             strncpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name,  (char *)hfp_connection->line_buffer, HFP_MAX_INDICATOR_DESC_SIZE);
1289             hfp_connection->ag_indicators[hfp_connection->parser_item_index].name[HFP_MAX_INDICATOR_DESC_SIZE-1] = 0;
1290             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1291             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1292             break;
1293         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1294             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1295             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer);
1296             hfp_connection->parser_item_index++;
1297             break;
1298         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1299             hfp_connection->parser_item_index++;
1300             if (hfp_connection->parser_item_index != 4) break;
1301             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1302             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1303             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1304             break;
1305         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1306             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1307             if (hfp_connection->line_size > 2 ) break;
1308             strncpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_nr].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE);
1309             hfp_connection->remote_call_services[hfp_connection->remote_call_services_nr].name[HFP_CALL_SERVICE_SIZE - 1] = 0;
1310             hfp_connection->remote_call_services_nr++;
1311             break;
1312         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1313         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1314             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1315             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1316             hfp_connection->parser_item_index++;
1317             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1318             break;
1319         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1320             // HF parses inital AG gen. ind. state
1321             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1322             hfp_connection->parser_item_index = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1323             break;
1324         case HFP_CMD_HF_INDICATOR_STATUS:
1325             hfp_connection->parser_indicator_index = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1326             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1327             break;
1328         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1329             // AG parses new gen. ind. state
1330             if (hfp_connection->ignore_value){
1331                 hfp_connection->ignore_value = 0;
1332                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1333                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1334             }
1335             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1336                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1337                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1338             } else {
1339                 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1340                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1341                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1342                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1343             }
1344             hfp_connection->parser_item_index++;
1345             break;
1346         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1347             // indicators are indexed starting with 1
1348             hfp_connection->parser_item_index = btstack_atoi((char *)&hfp_connection->line_buffer[0]) - 1;
1349             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1350             break;
1351         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1352             hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1353             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1354             break;
1355         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1356             if (hfp_connection->line_buffer[0] == '3'){
1357                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1358                 break;
1359             }
1360             // TODO emit ERROR, wrong format
1361             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1362             break;
1363         case HFP_CMD_ERROR:
1364             break;
1365         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1366             hfp_connection->extended_audio_gateway_error = 1;
1367             hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1368             break;
1369         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1370             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1371             hfp_connection->ok_pending = 1;
1372             hfp_connection->extended_audio_gateway_error = 0;
1373             break;
1374         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1375         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1376         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1377             strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1378             hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1379             break;
1380         default:
1381             break;
1382     }
1383 }
1384 
1385 void hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){
1386     hfp_connection_t * hfp_connection = provide_hfp_connection_context_for_bd_addr(bd_addr, local_role);
1387     log_info("hfp_connect %s, hfp_connection %p", bd_addr_to_str(bd_addr), hfp_connection);
1388 
1389     if (!hfp_connection) {
1390         log_error("hfp_establish_service_level_connection for addr %s failed", bd_addr_to_str(bd_addr));
1391         return;
1392     }
1393 
1394     switch (hfp_connection->state){
1395         case HFP_W2_DISCONNECT_RFCOMM:
1396             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1397             return;
1398         case HFP_W4_RFCOMM_DISCONNECTED:
1399             hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART;
1400             return;
1401         case HFP_IDLE:
1402             memcpy(hfp_connection->remote_addr, bd_addr, 6);
1403             hfp_connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1404             connection_doing_sdp_query = hfp_connection;
1405             hfp_connection->service_uuid = service_uuid;
1406             sdp_client_query_rfcomm_channel_and_name_for_uuid(&handle_query_rfcomm_event, hfp_connection->remote_addr, service_uuid);
1407             break;
1408         default:
1409             break;
1410     }
1411 }
1412 
1413 void hfp_release_service_level_connection(hfp_connection_t * hfp_connection){
1414     if (!hfp_connection) return;
1415     hfp_release_audio_connection(hfp_connection);
1416 
1417     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1418         hfp_connection->state = HFP_IDLE;
1419         return;
1420     }
1421 
1422     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1423         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1424         return;
1425     }
1426 
1427     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1428         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1429         return;
1430     }
1431 
1432     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1433         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1434         return;
1435     }
1436 
1437     return;
1438 }
1439 
1440 void hfp_release_audio_connection(hfp_connection_t * hfp_connection){
1441     if (!hfp_connection) return;
1442     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
1443     hfp_connection->release_audio_connection = 1;
1444 }
1445 
1446 static const struct link_settings {
1447     const uint16_t max_latency;
1448     const uint8_t  retransmission_effort;
1449     const uint16_t packet_types;
1450 } hfp_link_settings [] = {
1451     { 0xffff, 0xff, 0x03c1 }, // HFP_LINK_SETTINGS_D0,   HV1
1452     { 0xffff, 0xff, 0x03c4 }, // HFP_LINK_SETTINGS_D1,   HV3
1453     { 0x0007, 0x01, 0x03c8 }, // HFP_LINK_SETTINGS_S1,   EV3
1454     { 0x0007, 0x01, 0x0380 }, // HFP_LINK_SETTINGS_S2, 2-EV3
1455     { 0x000a, 0x01, 0x0380 }, // HFP_LINK_SETTINGS_S3, 2-EV3
1456     { 0x000c, 0x02, 0x0380 }, // HFP_LINK_SETTINGS_S4, 2-EV3
1457     { 0x0008, 0x02, 0x03c8 }, // HFP_LINK_SETTINGS_T1,   EV3
1458     { 0x000d, 0x02, 0x0380 }  // HFP_LINK_SETTINGS_T2, 2-EV3
1459 };
1460 
1461 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){
1462     // all packet types, fixed bandwidth
1463     int setting = hfp_connection->link_setting;
1464     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1465     sco_establishment_active = hfp_connection;
1466     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1467     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1468         sco_voice_setting = 0x0043; // Transparent data
1469     }
1470     hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency,
1471         sco_voice_setting, hfp_link_settings[setting].retransmission_effort, hfp_link_settings[setting].packet_types); // all types 0x003f, only 2-ev3 0x380
1472 }
1473 
1474 void hfp_set_ag_rfcomm_packet_handler(btstack_packet_handler_t handler){
1475     hfp_ag_rfcomm_packet_handler = handler;
1476 }
1477 void hfp_set_hf_rfcomm_packet_handler(btstack_packet_handler_t handler){
1478     hfp_hf_rfcomm_packet_handler = handler;
1479 }
1480 
1481