xref: /btstack/src/classic/hfp.c (revision c435f47b63025db89c42b8ffaaa28b0cfbdcce6e)
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 BLUEKITCHEN
24  * GMBH 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 <string.h>
46 #include <inttypes.h>
47 
48 #include "bluetooth_sdp.h"
49 #include "btstack_debug.h"
50 #include "btstack_event.h"
51 #include "btstack_memory.h"
52 #include "btstack_run_loop.h"
53 #include "classic/sdp_client_rfcomm.h"
54 #include "classic/sdp_server.h"
55 #include "classic/sdp_util.h"
56 #include "classic/sdp_client.h"
57 #include "hci.h"
58 #include "hci_cmd.h"
59 #include "hci_dump.h"
60 
61 #if defined(ENABLE_CC256X_ASSISTED_HFP) && !defined(ENABLE_SCO_OVER_PCM)
62 #error "Assisted HFP is only possible over PCM/I2S. Please add define: ENABLE_SCO_OVER_PCM"
63 #endif
64 
65 #if defined(ENABLE_BCM_PCM_WBS) && !defined(ENABLE_SCO_OVER_PCM)
66 #error "WBS for PCM is only possible over PCM/I2S. Please add define: ENABLE_SCO_OVER_PCM"
67 #endif
68 
69 #define HFP_HF_FEATURES_SIZE 10
70 #define HFP_AG_FEATURES_SIZE 12
71 
72 typedef struct {
73     hfp_role_t local_role;
74     bd_addr_t  remote_address;
75 } hfp_sdp_query_context_t;
76 
77 // globals
78 
79 static btstack_linked_list_t hfp_connections ;
80 
81 static btstack_packet_handler_t hfp_hf_callback;
82 static btstack_packet_handler_t hfp_ag_callback;
83 
84 static btstack_packet_handler_t hfp_hf_rfcomm_packet_handler;
85 static btstack_packet_handler_t hfp_ag_rfcomm_packet_handler;
86 
87 static uint16_t hfp_allowed_sco_packet_types;
88 static hfp_connection_t * hfp_sco_establishment_active;
89 
90 static hfp_sdp_query_context_t                 hfp_sdp_query_context;
91 static btstack_context_callback_registration_t hfp_sdp_query_request;
92 
93 
94 
95 
96 
97 // custom commands
98 static btstack_linked_list_t hfp_custom_commands_ag;
99 
100 // prototypes
101 static hfp_link_settings_t hfp_next_link_setting_for_connection(hfp_link_settings_t current_setting, hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported);
102 static void parse_sequence(hfp_connection_t * context);
103 
104 static const char * hfp_hf_features[] = {
105         "EC and/or NR function",
106         "Three-way calling",
107         "CLI presentation capability",
108         "Voice recognition activation",
109         "Remote volume control",
110 
111         "Enhanced call status",
112         "Enhanced call control",
113 
114         "Codec negotiation",
115 
116         "HF Indicators",
117         "eSCO S4 (and T2) Settings Supported",
118         "Reserved for future definition"
119 };
120 
121 static const char * hfp_ag_features[] = {
122         "Three-way calling",
123         "EC and/or NR function",
124         "Voice recognition function",
125         "In-band ring tone capability",
126         "Attach a number to a voice tag",
127         "Ability to reject a call",
128         "Enhanced call status",
129         "Enhanced call control",
130         "Extended Error Result Codes",
131         "Codec negotiation",
132         "HF Indicators",
133         "eSCO S4 (and T2) Settings Supported",
134         "Reserved for future definition"
135 };
136 
137 static const char * hfp_enhanced_call_dir[] = {
138         "outgoing",
139         "incoming"
140 };
141 
142 static const char * hfp_enhanced_call_status[] = {
143         "active",
144         "held",
145         "outgoing dialing",
146         "outgoing alerting",
147         "incoming",
148         "incoming waiting",
149         "call held by response and hold"
150 };
151 
152 static const char * hfp_enhanced_call_mode[] = {
153         "voice",
154         "data",
155         "fax"
156 };
157 
158 static const char * hfp_enhanced_call_mpty[] = {
159         "not a conference call",
160         "conference call"
161 };
162 
163 const char * hfp_enhanced_call_dir2str(uint16_t index){
164     if (index <= HFP_ENHANCED_CALL_DIR_INCOMING) return hfp_enhanced_call_dir[index];
165     return "not defined";
166 }
167 
168 const char * hfp_enhanced_call_status2str(uint16_t index){
169     if (index <= HFP_ENHANCED_CALL_STATUS_CALL_HELD_BY_RESPONSE_AND_HOLD) return hfp_enhanced_call_status[index];
170     return "not defined";
171 }
172 
173 const char * hfp_enhanced_call_mode2str(uint16_t index){
174     if (index <= HFP_ENHANCED_CALL_MODE_FAX) return hfp_enhanced_call_mode[index];
175     return "not defined";
176 }
177 
178 const char * hfp_enhanced_call_mpty2str(uint16_t index){
179     if (index <= HFP_ENHANCED_CALL_MPTY_CONFERENCE_CALL) return hfp_enhanced_call_mpty[index];
180     return "not defined";
181 }
182 
183 static uint16_t hfp_parse_indicator_index(hfp_connection_t * hfp_connection){
184     uint16_t index = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
185 
186     if (index > HFP_MAX_NUM_INDICATORS){
187         log_info("ignoring invalid indicator index bigger then HFP_MAX_NUM_INDICATORS");
188         return HFP_MAX_NUM_INDICATORS - 1;
189     }
190 
191     // indicator index enumeration starts with 1, we substract 1 to store in array with starting index 0
192     if (index > 0){
193         index -= 1;
194     } else {
195         log_info("ignoring invalid indicator index 0");
196         return 0;
197     }
198     return index;
199 }
200 
201 static void hfp_next_indicators_index(hfp_connection_t * hfp_connection){
202     if (hfp_connection->parser_item_index < HFP_MAX_NUM_INDICATORS - 1){
203         hfp_connection->parser_item_index++;
204     } else {
205         log_info("Ignoring additional indicator");
206     }
207 }
208 
209 static void hfp_next_codec_index(hfp_connection_t * hfp_connection){
210     if (hfp_connection->parser_item_index < HFP_MAX_NUM_CODECS - 1){
211         hfp_connection->parser_item_index++;
212     } else {
213         log_info("Ignoring additional codec index");
214     }
215 }
216 
217 static void hfp_next_remote_call_services_index(hfp_connection_t * hfp_connection){
218     if (hfp_connection->remote_call_services_index < HFP_MAX_NUM_CALL_SERVICES - 1){
219         hfp_connection->remote_call_services_index++;
220     } else {
221         log_info("Ignoring additional remote_call_services");
222     }
223 }
224 
225 const char * hfp_hf_feature(int index){
226     if (index > HFP_HF_FEATURES_SIZE){
227         return hfp_hf_features[HFP_HF_FEATURES_SIZE];
228     }
229     return hfp_hf_features[index];
230 }
231 
232 const char * hfp_ag_feature(int index){
233     if (index > HFP_AG_FEATURES_SIZE){
234         return hfp_ag_features[HFP_AG_FEATURES_SIZE];
235     }
236     return hfp_ag_features[index];
237 }
238 
239 int send_str_over_rfcomm(uint16_t cid, const char * command){
240     if (!rfcomm_can_send_packet_now(cid)) return 1;
241     log_info("HFP_TX %s", command);
242     int err = rfcomm_send(cid, (uint8_t*) command, (uint16_t) strlen(command));
243     if (err){
244         log_error("rfcomm_send -> error 0x%02x \n", err);
245     }
246 #ifdef ENABLE_HFP_AT_MESSAGES
247     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_rfcomm_cid(cid);
248     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_SENT, command);
249 #endif
250     return 1;
251 }
252 
253 int hfp_supports_codec(uint8_t codec, int codecs_nr, uint8_t * codecs){
254 
255     // mSBC requires support for eSCO connections
256     if ((codec == HFP_CODEC_MSBC) && !hci_extended_sco_link_supported()) return 0;
257 
258     int i;
259     for (i = 0; i < codecs_nr; i++){
260         if (codecs[i] != codec) continue;
261         return 1;
262     }
263     return 0;
264 }
265 
266 void hfp_hf_drop_mSBC_if_eSCO_not_supported(uint8_t * codecs, uint8_t * codecs_nr){
267     if (hci_extended_sco_link_supported()) return;
268     uint8_t tmp_codecs[HFP_MAX_NUM_CODECS];
269     int i;
270     int tmp_codec_nr = 0;
271     for (i=0; i < *codecs_nr; i++){
272         if (codecs[i] == HFP_CODEC_MSBC) continue;
273         tmp_codecs[tmp_codec_nr++] = codecs[i];
274     }
275     *codecs_nr = tmp_codec_nr;
276     (void)memcpy(codecs, tmp_codecs, tmp_codec_nr);
277 }
278 
279 // UTILS
280 int get_bit(uint16_t bitmap, int position){
281     return (bitmap >> position) & 1;
282 }
283 
284 int store_bit(uint32_t bitmap, int position, uint8_t value){
285     if (value){
286         bitmap |= 1 << position;
287     } else {
288         bitmap &= ~ (1 << position);
289     }
290     return bitmap;
291 }
292 
293 int join(char * buffer, int buffer_size, uint8_t * values, int values_nr){
294     if (buffer_size < (values_nr * 3)) return 0;
295     int i;
296     int offset = 0;
297     for (i = 0; i < (values_nr-1); i++) {
298       offset += snprintf(buffer+offset, buffer_size-offset, "%d,", values[i]); // puts string into buffer
299     }
300     if (i<values_nr){
301         offset += snprintf(buffer+offset, buffer_size-offset, "%d", values[i]);
302     }
303     return offset;
304 }
305 
306 int join_bitmap(char * buffer, int buffer_size, uint32_t values, int values_nr){
307     if (buffer_size < (values_nr * 3)) return 0;
308 
309     int i;
310     int offset = 0;
311     for (i = 0; i < (values_nr-1); i++) {
312       offset += snprintf(buffer+offset, buffer_size-offset, "%d,", get_bit(values,i)); // puts string into buffer
313     }
314 
315     if (i<values_nr){
316         offset += snprintf(buffer+offset, buffer_size-offset, "%d", get_bit(values,i));
317     }
318     return offset;
319 }
320 static void hfp_emit_event_for_role(hfp_role_t local_role, uint8_t * packet, uint16_t size){
321     switch (local_role){
322         case HFP_ROLE_HF:
323             (*hfp_hf_callback)(HCI_EVENT_PACKET, 0, packet, size);
324             break;
325         case HFP_ROLE_AG:
326             (*hfp_ag_callback)(HCI_EVENT_PACKET, 0, packet, size);
327             break;
328         default:
329             btstack_unreachable();
330             break;
331     }
332 }
333 
334 static void hfp_emit_event_for_context(hfp_connection_t * hfp_connection, uint8_t * packet, uint16_t size){
335     if (!hfp_connection) return;
336     hfp_emit_event_for_role(hfp_connection->local_role, packet, size);
337 }
338 
339 void hfp_emit_simple_event(hfp_connection_t * hfp_connection, uint8_t event_subtype){
340     hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID;
341     uint8_t event[5];
342     event[0] = HCI_EVENT_HFP_META;
343     event[1] = sizeof(event) - 2;
344     event[2] = event_subtype;
345     little_endian_store_16(event, 3, acl_handle);
346     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
347 }
348 
349 void hfp_emit_event(hfp_connection_t * hfp_connection, uint8_t event_subtype, uint8_t value){
350     hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID;
351     uint8_t event[6];
352     event[0] = HCI_EVENT_HFP_META;
353     event[1] = sizeof(event) - 2;
354     event[2] = event_subtype;
355     little_endian_store_16(event, 3, acl_handle);
356     event[5] = value; // status 0 == OK
357     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
358 }
359 
360 void hfp_emit_voice_recognition_enabled(hfp_connection_t * hfp_connection, uint8_t status){
361     btstack_assert(hfp_connection != NULL);
362 
363     uint8_t event[7];
364     event[0] = HCI_EVENT_HFP_META;
365     event[1] = sizeof(event) - 2;
366     event[2] = HFP_SUBEVENT_VOICE_RECOGNITION_ACTIVATED;
367 
368     little_endian_store_16(event, 3, hfp_connection->acl_handle);
369     event[5] = status; // 0:success
370     event[6] = hfp_connection->enhanced_voice_recognition_enabled ? 1 : 0;
371     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
372 }
373 
374 void hfp_emit_voice_recognition_disabled(hfp_connection_t * hfp_connection, uint8_t status){
375     btstack_assert(hfp_connection != NULL);
376 
377     uint8_t event[6];
378     event[0] = HCI_EVENT_HFP_META;
379     event[1] = sizeof(event) - 2;
380     event[2] = HFP_SUBEVENT_VOICE_RECOGNITION_DEACTIVATED;
381 
382     little_endian_store_16(event, 3, hfp_connection->acl_handle);
383     event[5] = status; // 0:success
384     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
385 }
386 
387 void hfp_emit_enhanced_voice_recognition_hf_ready_for_audio_event(hfp_connection_t * hfp_connection, uint8_t status){
388     hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID;
389 
390     uint8_t event[6];
391     event[0] = HCI_EVENT_HFP_META;
392     event[1] = sizeof(event) - 2;
393     event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_HF_READY_FOR_AUDIO;
394     little_endian_store_16(event, 3, acl_handle);
395     event[5] = status;
396     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
397 }
398 
399 void hfp_emit_enhanced_voice_recognition_state_event(hfp_connection_t * hfp_connection, uint8_t status){
400     hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID;
401 
402     uint8_t event[6];
403     event[0] = HCI_EVENT_HFP_META;
404     event[1] = sizeof(event) - 2;
405     switch (hfp_connection->ag_vra_state){
406         case HFP_VOICE_RECOGNITION_STATE_AG_READY_TO_ACCEPT_AUDIO_INPUT:
407             event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_AG_READY_TO_ACCEPT_AUDIO_INPUT;
408             break;
409         case HFP_VOICE_RECOGNITION_STATE_AG_IS_STARTING_SOUND:
410             event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_AG_IS_STARTING_SOUND;
411             break;
412         case HFP_VOICE_RECOGNITION_STATE_AG_IS_PROCESSING_AUDIO_INPUT:
413             event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_AG_IS_PROCESSING_AUDIO_INPUT;
414             break;
415         default:
416             btstack_unreachable();
417             break;
418     }
419 
420     little_endian_store_16(event, 3, acl_handle);
421     event[5] = status;
422     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
423 }
424 
425 void hfp_emit_slc_connection_event(hfp_role_t local_role, uint8_t status, hci_con_handle_t con_handle, bd_addr_t addr){
426     uint8_t event[12];
427     int pos = 0;
428     event[pos++] = HCI_EVENT_HFP_META;
429     event[pos++] = sizeof(event) - 2;
430     event[pos++] = HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
431     little_endian_store_16(event, pos, con_handle);
432     pos += 2;
433     event[pos++] = status; // status 0 == OK
434     reverse_bd_addr(addr,&event[pos]);
435     pos += 6;
436     hfp_emit_event_for_role(local_role, event, sizeof(event));
437 }
438 
439 static void hfp_emit_audio_connection_released(hfp_connection_t * hfp_connection, hci_con_handle_t sco_handle){
440     btstack_assert(hfp_connection != NULL);
441     uint8_t event[7];
442     int pos = 0;
443     event[pos++] = HCI_EVENT_HFP_META;
444     event[pos++] = sizeof(event) - 2;
445     event[pos++] = HFP_SUBEVENT_AUDIO_CONNECTION_RELEASED;
446     little_endian_store_16(event, pos, hfp_connection->acl_handle);
447     pos += 2;
448     little_endian_store_16(event, pos, sco_handle);
449     pos += 2;
450     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
451 }
452 
453 void hfp_emit_sco_event(hfp_connection_t * hfp_connection, uint8_t status, hci_con_handle_t sco_handle, bd_addr_t addr, uint8_t  negotiated_codec){
454     btstack_assert(hfp_connection != NULL);
455     uint8_t event[15];
456     int pos = 0;
457     event[pos++] = HCI_EVENT_HFP_META;
458     event[pos++] = sizeof(event) - 2;
459     event[pos++] = HFP_SUBEVENT_AUDIO_CONNECTION_ESTABLISHED;
460     little_endian_store_16(event, pos, hfp_connection->acl_handle);
461     pos += 2;
462     event[pos++] = status; // status 0 == OK
463     little_endian_store_16(event, pos, sco_handle);
464     pos += 2;
465     reverse_bd_addr(addr,&event[pos]);
466     pos += 6;
467     event[pos++] = negotiated_codec;
468     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
469 }
470 
471 void hfp_emit_string_event(hfp_connection_t * hfp_connection, uint8_t event_subtype, const char * value){
472     btstack_assert(hfp_connection != NULL);
473 #ifdef ENABLE_HFP_AT_MESSAGES
474     uint8_t event[256];
475 #else
476     uint8_t event[40];
477 #endif
478     uint16_t string_len = btstack_min((uint16_t) strlen(value), sizeof(event) - 6);
479     event[0] = HCI_EVENT_HFP_META;
480     event[1] = 4 + string_len;
481     event[2] = event_subtype;
482     little_endian_store_16(event, 3, hfp_connection->acl_handle);
483     memcpy((char*)&event[5], value, string_len);
484     event[5 + string_len] = 0;
485     hfp_emit_event_for_context(hfp_connection, event, 6 + string_len);
486 }
487 
488 btstack_linked_list_t * hfp_get_connections(void){
489     return (btstack_linked_list_t *) &hfp_connections;
490 }
491 
492 hfp_connection_t * get_hfp_connection_context_for_rfcomm_cid(uint16_t cid){
493     btstack_linked_list_iterator_t it;
494     btstack_linked_list_iterator_init(&it, hfp_get_connections());
495     while (btstack_linked_list_iterator_has_next(&it)){
496         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
497         if (hfp_connection->rfcomm_cid == cid){
498             return hfp_connection;
499         }
500     }
501     return NULL;
502 }
503 
504 hfp_connection_t * get_hfp_connection_context_for_bd_addr(bd_addr_t bd_addr, hfp_role_t hfp_role){
505     btstack_linked_list_iterator_t it;
506     btstack_linked_list_iterator_init(&it, hfp_get_connections());
507     while (btstack_linked_list_iterator_has_next(&it)){
508         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
509         if ((memcmp(hfp_connection->remote_addr, bd_addr, 6) == 0) && (hfp_connection->local_role == hfp_role)) {
510             return hfp_connection;
511         }
512     }
513     return NULL;
514 }
515 
516 hfp_connection_t * get_hfp_connection_context_for_sco_handle(uint16_t handle, hfp_role_t hfp_role){
517     btstack_linked_list_iterator_t it;
518     btstack_linked_list_iterator_init(&it, hfp_get_connections());
519     while (btstack_linked_list_iterator_has_next(&it)){
520         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
521         if ((hfp_connection->sco_handle == handle) && (hfp_connection->local_role == hfp_role)){
522             return hfp_connection;
523         }
524     }
525     return NULL;
526 }
527 
528 hfp_connection_t * get_hfp_connection_context_for_acl_handle(uint16_t handle, hfp_role_t hfp_role){
529     btstack_linked_list_iterator_t it;
530     btstack_linked_list_iterator_init(&it, hfp_get_connections());
531     while (btstack_linked_list_iterator_has_next(&it)){
532         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
533         if ((hfp_connection->acl_handle == handle) && (hfp_connection->local_role == hfp_role)){
534             return hfp_connection;
535         }
536     }
537     return NULL;
538 }
539 
540 
541 static void hfp_reset_voice_recognition(hfp_connection_t * hfp_connection){
542     btstack_assert(hfp_connection != NULL);
543     hfp_voice_recognition_activation_status_t current_vra_state = hfp_connection->vra_state;
544     hfp_connection->vra_state = HFP_VRA_VOICE_RECOGNITION_OFF;
545 
546     if (current_vra_state != HFP_VRA_VOICE_RECOGNITION_OFF){
547         hfp_emit_voice_recognition_disabled(hfp_connection, ERROR_CODE_SUCCESS);
548     } else if (hfp_connection->vra_state_requested != HFP_VRA_VOICE_RECOGNITION_OFF){
549         hfp_emit_voice_recognition_disabled(hfp_connection, ERROR_CODE_SUCCESS);
550     }
551 
552     hfp_connection->vra_state_requested = HFP_VRA_VOICE_RECOGNITION_OFF;
553     hfp_connection->activate_voice_recognition = false;
554     hfp_connection->deactivate_voice_recognition = false;
555     hfp_connection->enhanced_voice_recognition_enabled = false;
556     hfp_connection->ag_vra_status = 0;
557     hfp_connection->ag_vra_state = HFP_VOICE_RECOGNITION_STATE_AG_READY;
558 }
559 
560 void hfp_reset_context_flags(hfp_connection_t * hfp_connection){
561     if (!hfp_connection) return;
562     hfp_connection->ok_pending = 0;
563     hfp_connection->send_error = 0;
564 
565     hfp_connection->found_equal_sign = false;
566 
567     hfp_connection->change_status_update_for_individual_ag_indicators = 0;
568     hfp_connection->operator_name_changed = 0;
569 
570     hfp_connection->enable_extended_audio_gateway_error_report = 0;
571     hfp_connection->extended_audio_gateway_error = 0;
572 
573     // establish codecs hfp_connection
574     hfp_connection->suggested_codec = 0;
575     hfp_connection->negotiated_codec = 0;
576     hfp_connection->codec_confirmed = 0;
577 
578     hfp_connection->establish_audio_connection = 0;
579     hfp_connection->call_waiting_notification_enabled = 0;
580     hfp_connection->command = HFP_CMD_NONE;
581     hfp_connection->enable_status_update_for_ag_indicators = 0xFF;
582     hfp_connection->clip_have_alpha = false;
583     hfp_reset_voice_recognition(hfp_connection);
584 }
585 
586 static hfp_connection_t * create_hfp_connection_context(void){
587     hfp_connection_t * hfp_connection = btstack_memory_hfp_connection_get();
588     if (!hfp_connection) return NULL;
589 
590     hfp_connection->state = HFP_IDLE;
591     hfp_connection->call_state = HFP_CALL_IDLE;
592     hfp_connection->codecs_state = HFP_CODECS_IDLE;
593 
594     hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
595 
596     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
597     hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID;
598 
599     hfp_reset_context_flags(hfp_connection);
600 
601     btstack_linked_list_add(&hfp_connections, (btstack_linked_item_t*)hfp_connection);
602     return hfp_connection;
603 }
604 
605 void hfp_finalize_connection_context(hfp_connection_t * hfp_connection){
606     btstack_linked_list_remove(&hfp_connections, (btstack_linked_item_t*) hfp_connection);
607     btstack_memory_hfp_connection_free(hfp_connection);
608 }
609 
610 static hfp_connection_t * hfp_create_connection(bd_addr_t bd_addr, hfp_role_t local_role){
611     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(bd_addr, local_role);
612     if (hfp_connection) return  hfp_connection;
613     hfp_connection = create_hfp_connection_context();
614     (void)memcpy(hfp_connection->remote_addr, bd_addr, 6);
615     hfp_connection->local_role = local_role;
616     log_info("Create HFP context %p: role %u, addr %s", hfp_connection, local_role, bd_addr_to_str(bd_addr));
617 
618     return hfp_connection;
619 }
620 
621 /* @param network.
622  * 0 == no ability to reject a call.
623  * 1 == ability to reject a call.
624  */
625 
626 /* @param suported_features
627  * HF bit 0: EC and/or NR function (yes/no, 1 = yes, 0 = no)
628  * HF bit 1: Call waiting or three-way calling(yes/no, 1 = yes, 0 = no)
629  * HF bit 2: CLI presentation capability (yes/no, 1 = yes, 0 = no)
630  * HF bit 3: Voice recognition activation (yes/no, 1= yes, 0 = no)
631  * HF bit 4: Remote volume control (yes/no, 1 = yes, 0 = no)
632  * HF bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
633  */
634  /* Bit position:
635  * AG bit 0: Three-way calling (yes/no, 1 = yes, 0 = no)
636  * AG bit 1: EC and/or NR function (yes/no, 1 = yes, 0 = no)
637  * AG bit 2: Voice recognition function (yes/no, 1 = yes, 0 = no)
638  * AG bit 3: In-band ring tone capability (yes/no, 1 = yes, 0 = no)
639  * AG bit 4: Attach a phone number to a voice tag (yes/no, 1 = yes, 0 = no)
640  * AG bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
641  */
642 
643 void hfp_create_sdp_record(uint8_t * service, uint32_t service_record_handle, uint16_t service_uuid, int rfcomm_channel_nr, const char * name){
644     uint8_t* attribute;
645     de_create_sequence(service);
646 
647     // 0x0000 "Service Record Handle"
648     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
649     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
650 
651     // 0x0001 "Service Class ID List"
652     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
653     attribute = de_push_sequence(service);
654     {
655         //  "UUID for Service"
656         de_add_number(attribute, DE_UUID, DE_SIZE_16, service_uuid);
657         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_GENERIC_AUDIO);
658     }
659     de_pop_sequence(service, attribute);
660 
661     // 0x0004 "Protocol Descriptor List"
662     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
663     attribute = de_push_sequence(service);
664     {
665         uint8_t* l2cpProtocol = de_push_sequence(attribute);
666         {
667             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
668         }
669         de_pop_sequence(attribute, l2cpProtocol);
670 
671         uint8_t* rfcomm = de_push_sequence(attribute);
672         {
673             de_add_number(rfcomm,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_RFCOMM);  // rfcomm_service
674             de_add_number(rfcomm,  DE_UINT, DE_SIZE_8,  rfcomm_channel_nr);  // rfcomm channel
675         }
676         de_pop_sequence(attribute, rfcomm);
677     }
678     de_pop_sequence(service, attribute);
679 
680 
681     // 0x0005 "Public Browse Group"
682     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
683     attribute = de_push_sequence(service);
684     {
685         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
686     }
687     de_pop_sequence(service, attribute);
688 
689     // 0x0009 "Bluetooth Profile Descriptor List"
690     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
691     attribute = de_push_sequence(service);
692     {
693         uint8_t *sppProfile = de_push_sequence(attribute);
694         {
695             de_add_number(sppProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HANDSFREE);
696             de_add_number(sppProfile,  DE_UINT, DE_SIZE_16, 0x0108); // Verision 1.8
697         }
698         de_pop_sequence(attribute, sppProfile);
699     }
700     de_pop_sequence(service, attribute);
701 
702     // 0x0100 "Service Name"
703     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
704     de_add_data(service,  DE_STRING, (uint16_t) strlen(name), (uint8_t *) name);
705 }
706 
707 static void hfp_handle_slc_setup_error(hfp_connection_t * hfp_connection, uint8_t status){
708     // cache fields for event
709     hfp_role_t local_role = hfp_connection->local_role;
710     bd_addr_t remote_addr;
711     (void)memcpy(remote_addr, hfp_connection->remote_addr, 6);
712     // finalize connection struct
713     hfp_finalize_connection_context(hfp_connection);
714     // emit event
715     hfp_emit_slc_connection_event(local_role, status, HCI_CON_HANDLE_INVALID, remote_addr);
716 }
717 
718 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
719     UNUSED(packet_type);    // ok: handling own sdp events
720     UNUSED(channel);        // ok: no channel
721     UNUSED(size);           // ok: handling own sdp events
722 
723     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(hfp_sdp_query_context.remote_address, hfp_sdp_query_context.local_role);
724     if (hfp_connection == NULL) {
725         log_info("connection with %s and local role %d not found", hfp_sdp_query_context.remote_address, hfp_sdp_query_context.local_role);
726         return;
727     }
728 
729     switch (hci_event_packet_get_type(packet)){
730         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
731             hfp_connection->rfcomm_channel_nr = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
732             break;
733         case SDP_EVENT_QUERY_COMPLETE:
734             if (hfp_connection->rfcomm_channel_nr > 0){
735                 hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
736                 btstack_packet_handler_t packet_handler;
737                 switch (hfp_connection->local_role){
738                     case HFP_ROLE_AG:
739                         packet_handler = hfp_ag_rfcomm_packet_handler;
740                         break;
741                     case HFP_ROLE_HF:
742                         packet_handler = hfp_hf_rfcomm_packet_handler;
743                         break;
744                     default:
745                         btstack_assert(false);
746                         return;
747                 }
748 
749                 rfcomm_create_channel(packet_handler, hfp_connection->remote_addr, hfp_connection->rfcomm_channel_nr, NULL);
750 
751             } else {
752                 uint8_t status = sdp_event_query_complete_get_status(packet);
753                 if (status == ERROR_CODE_SUCCESS){
754                     // report service not found
755                     status = SDP_SERVICE_NOT_FOUND;
756                 }
757                 hfp_handle_slc_setup_error(hfp_connection, status);
758                 log_info("rfcomm service not found, status 0x%02x", status);
759             }
760 
761             // register the SDP Query request to check if there is another connection waiting for the query
762             // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
763             (void) sdp_client_register_query_callback(&hfp_sdp_query_request);
764             break;
765         default:
766             break;
767     }
768 }
769 
770 // returns 0 if unexpected error or no other link options remained, otherwise 1
771 static int hfp_handle_failed_sco_connection(uint8_t status){
772 
773     if (!hfp_sco_establishment_active){
774         log_info("(e)SCO Connection failed but not started by us");
775         return 0;
776     }
777 
778     log_info("(e)SCO Connection failed 0x%02x", status);
779     switch (status){
780         case ERROR_CODE_SCO_AIR_MODE_REJECTED:
781         case ERROR_CODE_SCO_INTERVAL_REJECTED:
782         case ERROR_CODE_SCO_OFFSET_REJECTED:
783         case ERROR_CODE_UNSPECIFIED_ERROR:
784         case ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE:
785         case ERROR_CODE_UNSUPPORTED_REMOTE_FEATURE_UNSUPPORTED_LMP_FEATURE:
786             break;
787         default:
788             return 0;
789     }
790 
791     // note: eSCO_S4 supported flag not available, but it's only relevant for highest CVSD link setting (and the current failed)
792     hfp_link_settings_t next_setting = hfp_next_link_setting_for_connection(hfp_sco_establishment_active->link_setting, hfp_sco_establishment_active, false);
793 
794     // handle no valid setting found
795     if (next_setting == HFP_LINK_SETTINGS_NONE) {
796         if (hfp_sco_establishment_active->negotiated_codec == HFP_CODEC_MSBC){
797             log_info("T2/T1 failed, fallback to CVSD - D1");
798             hfp_sco_establishment_active->negotiated_codec = HFP_CODEC_CVSD;
799             hfp_sco_establishment_active->sco_for_msbc_failed = 1;
800             hfp_sco_establishment_active->ag_send_common_codec = true;
801             hfp_sco_establishment_active->link_setting = HFP_LINK_SETTINGS_D1;
802         } else {
803             // no other options
804             return 0;
805         }
806     }
807 
808     log_info("e)SCO Connection: try new link_setting %d", next_setting);
809     hfp_sco_establishment_active->establish_audio_connection = 1;
810     hfp_sco_establishment_active->link_setting = next_setting;
811     hfp_sco_establishment_active = NULL;
812     return 1;
813 }
814 
815 void hfp_handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
816     UNUSED(packet_type);
817     UNUSED(channel);    // ok: no channel
818     UNUSED(size);
819 
820     bd_addr_t event_addr;
821     hci_con_handle_t handle;
822     hfp_connection_t * hfp_connection = NULL;
823     uint8_t status;
824 
825     log_debug("HFP HCI event handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
826 
827     switch (hci_event_packet_get_type(packet)) {
828 
829         case HCI_EVENT_CONNECTION_REQUEST:
830             switch(hci_event_connection_request_get_link_type(packet)){
831                 case 0: //  SCO
832                 case 2: // eSCO
833                     hci_event_connection_request_get_bd_addr(packet, event_addr);
834                     hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
835                     if (!hfp_connection) break;
836                     if (hci_event_connection_request_get_link_type(packet) == 2){
837                         hfp_connection->accept_sco = 2;
838                     } else {
839                         hfp_connection->accept_sco = 1;
840                     }
841 #ifdef ENABLE_CC256X_ASSISTED_HFP
842                     hfp_cc256x_prepare_for_sco(hfp_connection);
843 #endif
844 #ifdef ENABLE_BCM_PCM_WBS
845                     hfp_bcm_prepare_for_sco(hfp_connection);
846 #endif
847 #ifdef ENABLE_RTK_PCM_WBS
848                     hfp_connection->rtk_send_sco_config = true;
849 #endif
850                     log_info("accept sco %u\n", hfp_connection->accept_sco);
851                     hfp_sco_establishment_active = hfp_connection;
852                     break;
853                 default:
854                     break;
855             }
856             break;
857 
858         case HCI_EVENT_COMMAND_STATUS:
859             if (hci_event_command_status_get_command_opcode(packet) == hci_setup_synchronous_connection.opcode) {
860                 if (hfp_sco_establishment_active == NULL) break;
861                 status = hci_event_command_status_get_status(packet);
862                 if (status == ERROR_CODE_SUCCESS) break;
863 
864                 hfp_connection = hfp_sco_establishment_active;
865                 if (hfp_handle_failed_sco_connection(status)) break;
866                 hfp_connection->establish_audio_connection = 0;
867                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
868                 hfp_emit_sco_event(hfp_connection, status, 0, hfp_connection->remote_addr, hfp_connection->negotiated_codec);
869             }
870             break;
871 
872         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
873             if (hfp_sco_establishment_active == NULL) break;
874             hci_event_synchronous_connection_complete_get_bd_addr(packet, event_addr);
875             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
876             if (!hfp_connection) {
877                 log_error("HFP: connection does not exist for remote with addr %s.", bd_addr_to_str(event_addr));
878                 return;
879             }
880 
881             status = hci_event_synchronous_connection_complete_get_status(packet);
882             if (status != ERROR_CODE_SUCCESS){
883                 hfp_connection->accept_sco = 0;
884                 if (hfp_handle_failed_sco_connection(status)) break;
885 
886                 hfp_connection->establish_audio_connection = 0;
887                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
888                 hfp_emit_sco_event(hfp_connection, status, 0, event_addr, hfp_connection->negotiated_codec);
889                 break;
890             }
891 
892             uint16_t sco_handle = hci_event_synchronous_connection_complete_get_handle(packet);
893             uint8_t  link_type = hci_event_synchronous_connection_complete_get_link_type(packet);
894             uint8_t  transmission_interval = hci_event_synchronous_connection_complete_get_transmission_interval(packet);  // measured in slots
895             uint8_t  retransmission_interval = hci_event_synchronous_connection_complete_get_retransmission_interval(packet);// measured in slots
896             uint16_t rx_packet_length = hci_event_synchronous_connection_complete_get_rx_packet_length(packet); // measured in bytes
897             uint16_t tx_packet_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet); // measured in bytes
898 
899             switch (link_type){
900                 case 0x00:
901                     log_info("SCO Connection established.");
902                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
903                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
904                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
905                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
906                     break;
907                 case 0x02:
908                     log_info("eSCO Connection established. \n");
909                     break;
910                 default:
911                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
912                     break;
913             }
914 
915             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
916                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)\n", sco_handle,
917                  bd_addr_to_str(event_addr), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length,
918                  hci_event_synchronous_connection_complete_get_air_mode(packet));
919 
920             if (hfp_connection->state == HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){
921                 log_info("SCO about to disconnect: HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN");
922                 hfp_connection->state = HFP_W2_DISCONNECT_SCO;
923                 break;
924             }
925             hfp_connection->sco_handle = sco_handle;
926             hfp_connection->establish_audio_connection = 0;
927 
928             hfp_connection->state = HFP_AUDIO_CONNECTION_ESTABLISHED;
929 
930             switch (hfp_connection->vra_state){
931                 case HFP_VRA_VOICE_RECOGNITION_ACTIVATED:
932                     hfp_connection->ag_audio_connection_opened_before_vra = false;
933                     break;
934                 default:
935                     hfp_connection->ag_audio_connection_opened_before_vra = true;
936                     break;
937             }
938             hfp_emit_sco_event(hfp_connection, status, sco_handle, event_addr, hfp_connection->negotiated_codec);
939             break;
940         }
941 
942         case HCI_EVENT_DISCONNECTION_COMPLETE:
943             handle = little_endian_read_16(packet,3);
944             hfp_connection = get_hfp_connection_context_for_sco_handle(handle, local_role);
945 
946             if (!hfp_connection) break;
947 
948 #ifdef ENABLE_CC256X_ASSISTED_HFP
949             hfp_connection->cc256x_send_wbs_disassociate = true;
950 #endif
951 #ifdef ENABLE_BCM_PCM_WBS
952             hfp_connection->bcm_send_disable_wbs = true;
953 #endif
954             if (hfp_connection->sco_handle == handle){
955                 hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID;
956                 hfp_connection->release_audio_connection = 0;
957                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
958                 hfp_emit_audio_connection_released(hfp_connection, handle);
959 
960                 hfp_connection->ag_audio_connection_opened_before_vra = false;
961 
962                 if (hfp_connection->acl_handle == HCI_CON_HANDLE_INVALID){
963                     hfp_reset_voice_recognition(hfp_connection);
964                     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
965                     hfp_finalize_connection_context(hfp_connection);
966                     break;
967                 } else if (hfp_connection->release_slc_connection == 1){
968                     hfp_connection->release_slc_connection = 0;
969                     hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
970                     rfcomm_disconnect(hfp_connection->acl_handle);
971                 }
972             }
973 
974             if (hfp_connection->state == HFP_W4_SCO_DISCONNECTED_TO_SHUTDOWN){
975                 // RFCOMM already closed -> remote power off
976 #if defined(ENABLE_CC256X_ASSISTED_HFP) || defined (ENABLE_BCM_PCM_WBS)
977                 hfp_connection->state = HFP_W4_WBS_SHUTDOWN;
978 #else
979                 hfp_finalize_connection_context(hfp_connection);
980 #endif
981                 break;
982             }
983             break;
984 
985         default:
986             break;
987     }
988 }
989 
990 
991 void hfp_handle_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
992     UNUSED(packet_type);
993     UNUSED(channel);    // ok: no channel
994     UNUSED(size);
995 
996     bd_addr_t event_addr;
997     uint16_t rfcomm_cid;
998     hfp_connection_t * hfp_connection = NULL;
999     uint8_t status;
1000 
1001     log_debug("HFP packet_handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
1002 
1003     switch (hci_event_packet_get_type(packet)) {
1004 
1005         case RFCOMM_EVENT_INCOMING_CONNECTION:
1006             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
1007             rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
1008             hfp_connection = hfp_create_connection(event_addr, local_role);
1009             if (!hfp_connection){
1010                 log_info("hfp: no memory to accept incoming connection - decline");
1011                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
1012                 return;
1013             }
1014             if (hfp_connection->state != HFP_IDLE) {
1015                 log_error("hfp: incoming connection but not idle, reject");
1016                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
1017                 return;
1018             }
1019 
1020             hfp_connection->rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
1021             hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
1022             rfcomm_accept_connection(hfp_connection->rfcomm_cid);
1023             break;
1024 
1025         case RFCOMM_EVENT_CHANNEL_OPENED:
1026             rfcomm_event_channel_opened_get_bd_addr(packet, event_addr);
1027 
1028             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
1029             btstack_assert(hfp_connection != NULL);
1030 
1031             if (hfp_connection->state != HFP_W4_RFCOMM_CONNECTED){
1032                 break;
1033             }
1034 
1035             status = rfcomm_event_channel_opened_get_status(packet);
1036             if (status != ERROR_CODE_SUCCESS) {
1037                 hfp_handle_slc_setup_error(hfp_connection, status);
1038                 break;
1039             }
1040 
1041             hfp_connection->acl_handle = rfcomm_event_channel_opened_get_con_handle(packet);
1042             hfp_connection->rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
1043             hfp_connection->rfcomm_mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
1044             bd_addr_copy(hfp_connection->remote_addr, event_addr);
1045             hfp_connection->state = HFP_EXCHANGE_SUPPORTED_FEATURES;
1046 
1047             rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1048             break;
1049 
1050         case RFCOMM_EVENT_CHANNEL_CLOSED:
1051             rfcomm_cid = little_endian_read_16(packet,2);
1052             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
1053             if (!hfp_connection) break;
1054             switch (hfp_connection->state){
1055                 case HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART:
1056                     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
1057                     hfp_connection->state = HFP_IDLE;
1058                     hfp_establish_service_level_connection(hfp_connection->remote_addr, hfp_connection->service_uuid, local_role);
1059                     break;
1060 
1061                 case HFP_AUDIO_CONNECTION_ESTABLISHED:
1062                     // service connection was released, this implicitly releases audio connection as well
1063                     hfp_connection->release_audio_connection = 0;
1064                     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
1065                     hfp_connection->state = HFP_W4_SCO_DISCONNECTED_TO_SHUTDOWN;
1066                     gap_disconnect(hfp_connection->sco_handle);
1067                     break;
1068 
1069                 default:
1070                     // regular case
1071                     hfp_reset_voice_recognition(hfp_connection);
1072                     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
1073                     hfp_finalize_connection_context(hfp_connection);
1074                     break;
1075             }
1076             break;
1077 
1078         default:
1079             break;
1080     }
1081 }
1082 // translates command string into hfp_command_t CMD
1083 
1084 typedef struct {
1085     const char * command;
1086     hfp_command_t command_id;
1087 } hfp_command_entry_t;
1088 
1089 static hfp_command_entry_t hfp_ag_commmand_table[] = {
1090     { "AT+BAC=",   HFP_CMD_AVAILABLE_CODECS },
1091     { "AT+BCC",    HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP },
1092     { "AT+BCS=",   HFP_CMD_HF_CONFIRMED_CODEC },
1093     { "AT+BIA=",   HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE, }, // +BIA:<enabled>,,<enabled>,,,<enabled>
1094     { "AT+BIEV=",  HFP_CMD_HF_INDICATOR_STATUS },
1095     { "AT+BIND=",  HFP_CMD_LIST_GENERIC_STATUS_INDICATORS },
1096     { "AT+BIND=?", HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS },
1097     { "AT+BIND?",  HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE },
1098     { "AT+BINP=",  HFP_CMD_HF_REQUEST_PHONE_NUMBER },
1099     { "AT+BLDN",   HFP_CMD_REDIAL_LAST_NUMBER },
1100     { "AT+BRSF=",  HFP_CMD_SUPPORTED_FEATURES },
1101     { "AT+BTRH=",  HFP_CMD_RESPONSE_AND_HOLD_COMMAND },
1102     { "AT+BTRH?",  HFP_CMD_RESPONSE_AND_HOLD_QUERY },
1103     { "AT+BVRA=",  HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION },
1104     { "AT+CCWA=",  HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION},
1105     { "AT+CHLD=",  HFP_CMD_CALL_HOLD },
1106     { "AT+CHLD=?", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
1107     { "AT+CHUP",   HFP_CMD_HANG_UP_CALL },
1108     { "AT+CIND=?", HFP_CMD_RETRIEVE_AG_INDICATORS },
1109     { "AT+CIND?",  HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS },
1110     { "AT+CLCC",   HFP_CMD_LIST_CURRENT_CALLS },
1111     { "AT+CLIP=",  HFP_CMD_ENABLE_CLIP},
1112     { "AT+CMEE=",  HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR},
1113     { "AT+CMER=",  HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE },
1114     { "AT+CNUM",   HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION },
1115     { "AT+COPS=",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT },
1116     { "AT+COPS?",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
1117     { "AT+NREC=",  HFP_CMD_TURN_OFF_EC_AND_NR, },
1118     { "AT+VGM=",   HFP_CMD_SET_MICROPHONE_GAIN },
1119     { "AT+VGS=",   HFP_CMD_SET_SPEAKER_GAIN },
1120     { "AT+VTS=",   HFP_CMD_TRANSMIT_DTMF_CODES },
1121     { "ATA",       HFP_CMD_CALL_ANSWERED },
1122 };
1123 
1124 static hfp_command_entry_t hfp_hf_commmand_table[] = {
1125     { "+BCS:",  HFP_CMD_AG_SUGGESTED_CODEC },
1126     { "+BIND:", HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS },
1127     { "+BINP:", HFP_CMD_AG_SENT_PHONE_NUMBER },
1128     { "+BRSF:", HFP_CMD_SUPPORTED_FEATURES },
1129     { "+BSIR:", HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING },
1130     { "+BTRH:", HFP_CMD_RESPONSE_AND_HOLD_STATUS },
1131     { "+BVRA:", HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION },
1132     { "+CCWA:", HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE, },
1133     { "+CHLD:", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
1134     { "+CIEV:", HFP_CMD_TRANSFER_AG_INDICATOR_STATUS},
1135     { "+CIND:", HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC },
1136     { "+CLCC:", HFP_CMD_LIST_CURRENT_CALLS },
1137     { "+CLIP:", HFP_CMD_AG_SENT_CLIP_INFORMATION },
1138     { "+CME ERROR:", HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR },
1139     { "+CNUM:", HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION},
1140     { "+COPS:", HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
1141     { "+VGM:",  HFP_CMD_SET_MICROPHONE_GAIN },
1142     { "+VGM=",  HFP_CMD_SET_MICROPHONE_GAIN },
1143     { "+VGS:",  HFP_CMD_SET_SPEAKER_GAIN},
1144     { "+VGS=",  HFP_CMD_SET_SPEAKER_GAIN},
1145     { "ERROR",  HFP_CMD_ERROR},
1146     { "NOP",    HFP_CMD_NONE}, // dummy command used by unit tests
1147     { "OK",     HFP_CMD_OK },
1148     { "RING",   HFP_CMD_RING },
1149 };
1150 
1151 static const hfp_custom_at_command_t * hfp_custom_command_lookup(const char * text){
1152     btstack_linked_list_iterator_t it;
1153     btstack_linked_list_iterator_init(&it, &hfp_custom_commands_ag);
1154     while (btstack_linked_list_iterator_has_next(&it)) {
1155         hfp_custom_at_command_t *at_command = (hfp_custom_at_command_t *) btstack_linked_list_iterator_next(&it);
1156         int match = strcmp(text, at_command->command);
1157         if (match == 0) {
1158             return at_command;
1159         }
1160     }
1161     return NULL;
1162 }
1163 
1164 static hfp_command_t parse_command(const char * line_buffer, int isHandsFree){
1165 
1166     // table lookup based on role
1167     uint16_t num_entries;
1168     hfp_command_entry_t * table;
1169     if (isHandsFree == 0){
1170         table = hfp_ag_commmand_table;
1171         num_entries = sizeof(hfp_ag_commmand_table) / sizeof(hfp_command_entry_t);
1172     } else {
1173         table = hfp_hf_commmand_table;
1174         num_entries = sizeof(hfp_hf_commmand_table) / sizeof(hfp_command_entry_t);
1175     }
1176     // binary search
1177     uint16_t left = 0;
1178     uint16_t right = num_entries - 1;
1179     while (left <= right){
1180         uint16_t middle = left + (right - left) / 2;
1181         hfp_command_entry_t *entry = &table[middle];
1182         int match = strcmp(line_buffer, entry->command);
1183         if (match < 0){
1184             // search term is lower than middle element
1185             if (right == 0) break;
1186             right = middle - 1;
1187         } else if (match == 0){
1188             return entry->command_id;
1189         } else {
1190             // search term is higher than middle element
1191             left = middle + 1;
1192         }
1193     }
1194 
1195     // note: if parser in CMD_HEADER state would treats digits and maybe '+' as separator, match on "ATD" would work.
1196     // note: phone number is currently expected in line_buffer[3..]
1197     // prefix match on 'ATD', AG only
1198     if ((isHandsFree == 0) && (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0)){
1199         return HFP_CMD_CALL_PHONE_NUMBER;
1200     }
1201 
1202     // check for custom commands, AG only
1203     if (isHandsFree == 0) {
1204         const hfp_custom_at_command_t * custom_at_command = hfp_custom_command_lookup(line_buffer);
1205         if (custom_at_command != NULL){
1206             return HFP_CMD_CUSTOM_MESSAGE;
1207         }
1208     }
1209 
1210     // Valid looking, but unknown commands/responses
1211     if ((isHandsFree == 0) && (strncmp(line_buffer, "AT+", 3) == 0)){
1212         return HFP_CMD_UNKNOWN;
1213     }
1214 
1215     if ((isHandsFree != 0) && (strncmp(line_buffer, "+", 1) == 0)){
1216         return HFP_CMD_UNKNOWN;
1217     }
1218 
1219     return HFP_CMD_NONE;
1220 }
1221 
1222 static void hfp_parser_store_byte(hfp_connection_t * hfp_connection, uint8_t byte){
1223     if ((hfp_connection->line_size + 1) >= HFP_MAX_VR_TEXT_SIZE) return;
1224     hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
1225     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1226 }
1227 static int hfp_parser_is_buffer_empty(hfp_connection_t * hfp_connection){
1228     return hfp_connection->line_size == 0;
1229 }
1230 
1231 static int hfp_parser_is_end_of_line(uint8_t byte){
1232     return (byte == '\n') || (byte == '\r');
1233 }
1234 
1235 void hfp_parser_reset_line_buffer(hfp_connection_t *hfp_connection) {
1236     hfp_connection->line_size = 0;
1237     // we don't set the first byte to '\0' to allow access to last argument e.g. in hfp_hf_handle_rfcommand
1238 }
1239 
1240 static void hfp_parser_store_if_token(hfp_connection_t * hfp_connection, uint8_t byte){
1241     switch (byte){
1242         case ',':
1243 		case '-':
1244         case ';':
1245         case '(':
1246         case ')':
1247         case '\n':
1248         case '\r':
1249             break;
1250         default:
1251             hfp_parser_store_byte(hfp_connection, byte);
1252             break;
1253     }
1254 }
1255 
1256 static bool hfp_parser_is_separator( uint8_t byte){
1257     switch (byte){
1258         case ',':
1259 		case '-':
1260         case ';':
1261         case '\n':
1262         case '\r':
1263             return true;
1264         default:
1265             return false;
1266     }
1267 }
1268 
1269 static bool hfp_parse_byte(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1270 
1271     // handle doubles quotes
1272     if (byte == '"'){
1273         hfp_connection->parser_quoted = !hfp_connection->parser_quoted;
1274         return true;
1275     }
1276     if (hfp_connection->parser_quoted) {
1277         hfp_parser_store_byte(hfp_connection, byte);
1278         return true;
1279     }
1280 
1281     // ignore spaces outside command or double quotes (required e.g. for '+CME ERROR:..") command
1282     if ((byte == ' ') && (hfp_connection->parser_state != HFP_PARSER_CMD_HEADER)) return true;
1283 
1284     bool processed = true;
1285 
1286     switch (hfp_connection->parser_state) {
1287         case HFP_PARSER_CMD_HEADER:
1288             switch (byte) {
1289                 case '\n':
1290                 case '\r':
1291                 case ';':
1292                     // ignore separator
1293                     break;
1294                 case ':':
1295                 case '?':
1296                     // store separator
1297                     hfp_parser_store_byte(hfp_connection, byte);
1298                     break;
1299                 case '=':
1300                     // equal sign: remember and wait for next char to decided between '=?' and '=\?'
1301                     hfp_connection->found_equal_sign = true;
1302                     hfp_parser_store_byte(hfp_connection, byte);
1303                     return true;
1304                 default:
1305                     // store if not lookahead
1306                     if (!hfp_connection->found_equal_sign) {
1307                         hfp_parser_store_byte(hfp_connection, byte);
1308                         return true;
1309                     }
1310                     // mark as lookahead
1311                     processed = false;
1312                     break;
1313             }
1314 
1315             // ignore empty tokens
1316             if (hfp_parser_is_buffer_empty(hfp_connection)) return true;
1317 
1318             // parse
1319             hfp_connection->command = parse_command((char *)hfp_connection->line_buffer, isHandsFree);
1320 
1321             // pick +CIND version based on connection state: descriptions during SLC vs. states later
1322             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC){
1323                 switch(hfp_connection->state){
1324                     case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1325                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
1326                         break;
1327                     case HFP_W4_RETRIEVE_INDICATORS:
1328                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS;
1329                         break;
1330                     default:
1331                         hfp_connection->command = HFP_CMD_UNKNOWN;
1332                         break;
1333                 }
1334             }
1335 
1336             log_info("command string '%s', handsfree %u -> cmd id %u", (char *)hfp_connection->line_buffer, isHandsFree, hfp_connection->command);
1337 
1338             // store command id for custom command and just store rest of line
1339             if (hfp_connection->command == HFP_CMD_CUSTOM_MESSAGE){
1340                 const hfp_custom_at_command_t * at_command = hfp_custom_command_lookup((const char *)hfp_connection->line_buffer);
1341                 hfp_connection->ag_custom_at_command_id = at_command->command_id;
1342                 hfp_connection->parser_state = HFP_PARSER_CUSTOM_COMMAND;
1343                 return true;
1344             }
1345 
1346             // next state
1347             hfp_connection->found_equal_sign = false;
1348             hfp_parser_reset_line_buffer(hfp_connection);
1349             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1350 
1351             return processed;
1352 
1353         case HFP_PARSER_CMD_SEQUENCE:
1354             // handle empty fields
1355             if ((byte == ',' ) && (hfp_connection->line_size == 0)){
1356                 hfp_connection->line_buffer[0] = 0;
1357                 hfp_connection->ignore_value = 1;
1358                 parse_sequence(hfp_connection);
1359                 return true;
1360             }
1361 
1362             hfp_parser_store_if_token(hfp_connection, byte);
1363             if (!hfp_parser_is_separator(byte)) return true;
1364 
1365             // ignore empty tokens
1366             switch (hfp_connection->command){
1367                 case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1368                     // don't ignore empty string
1369                     break;
1370                 default:
1371                     if (hfp_parser_is_buffer_empty(hfp_connection) && (hfp_connection->ignore_value == 0)) {
1372                         return true;
1373                     }
1374                     break;
1375             }
1376 
1377             parse_sequence(hfp_connection);
1378 
1379             hfp_parser_reset_line_buffer(hfp_connection);
1380 
1381             switch (hfp_connection->command){
1382                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1383                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1384                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1385                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1386                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1387                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1388                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1389                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1390                 case HFP_CMD_HF_INDICATOR_STATUS:
1391                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
1392                     break;
1393                 default:
1394                     break;
1395             }
1396             return true;
1397 
1398         case HFP_PARSER_SECOND_ITEM:
1399 
1400             hfp_parser_store_if_token(hfp_connection, byte);
1401             if (!hfp_parser_is_separator(byte)) return true;
1402 
1403             switch (hfp_connection->command){
1404                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1405                     log_info("format %s, ", hfp_connection->line_buffer);
1406                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1407                     break;
1408                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1409                     log_info("format %s \n", hfp_connection->line_buffer);
1410                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1411                     break;
1412                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1413                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1414                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1415                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1416                     break;
1417                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1418                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1419                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1420                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1421                     break;
1422                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1423                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer);
1424                     log_info("%s, ", hfp_connection->line_buffer);
1425                     break;
1426                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1427                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1428                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1429                     hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1430                     break;
1431                 case HFP_CMD_HF_INDICATOR_STATUS:
1432                     hfp_connection->parser_indicator_value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1433                     break;
1434                 default:
1435                     break;
1436             }
1437 
1438             hfp_parser_reset_line_buffer(hfp_connection);
1439 
1440             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
1441 
1442             return true;
1443 
1444         case HFP_PARSER_THIRD_ITEM:
1445 
1446             hfp_parser_store_if_token(hfp_connection, byte);
1447             if (!hfp_parser_is_separator(byte)) return true;
1448 
1449             switch (hfp_connection->command){
1450                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1451                     btstack_strcpy(hfp_connection->network_operator.name, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE,  (char *)hfp_connection->line_buffer);
1452                     break;
1453                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1454                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer);
1455                     hfp_next_indicators_index(hfp_connection);
1456                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1457                     break;
1458                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1459                     // track if last argument exists
1460                     hfp_connection->clip_have_alpha = hfp_connection->line_size != 0;
1461                     break;
1462                 default:
1463                     break;
1464             }
1465 
1466             hfp_parser_reset_line_buffer(hfp_connection);
1467 
1468             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){
1469                 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1470             }
1471             return true;
1472 
1473         case HFP_PARSER_CUSTOM_COMMAND:
1474             hfp_parser_store_byte(hfp_connection, byte);
1475             return true;
1476 
1477         default:
1478             btstack_assert(false);
1479             return true;
1480     }
1481 }
1482 
1483 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1484     bool processed = false;
1485     while (!processed){
1486         processed = hfp_parse_byte(hfp_connection, byte, isHandsFree);
1487     }
1488     // reset parser state on end-of-line
1489     if (hfp_parser_is_end_of_line(byte)){
1490         hfp_connection->parser_item_index = 0;
1491         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1492     }
1493 }
1494 
1495 static void parse_sequence(hfp_connection_t * hfp_connection){
1496     int value;
1497     switch (hfp_connection->command){
1498         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1499             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1500             int i;
1501             switch (hfp_connection->parser_item_index){
1502                 case 0:
1503                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1504                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1505                             hfp_connection->parser_indicator_index = i;
1506                             break;
1507                         }
1508                     }
1509                     break;
1510                 case 1:
1511                     if (hfp_connection->parser_indicator_index <0) break;
1512                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1513                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1514                      hfp_connection->parser_item_index, value);
1515                     break;
1516                 default:
1517                     break;
1518             }
1519             hfp_next_indicators_index(hfp_connection);
1520             break;
1521 
1522         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1523             switch(hfp_connection->parser_item_index){
1524                 case 0:
1525                     // <alpha>: This optional field is not supported, and shall be left blank.
1526                     break;
1527                 case 1:
1528                     // <number>: Quoted string containing the phone number in the format specified by <type>.
1529                     btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1530                     break;
1531                 case 2:
1532                     /*
1533                       <type> field specifies the format of the phone number provided, and can be one of the following values:
1534                       - values 128-143: The phone number format may be a national or international format, and may contain prefix and/or escape digits. No changes on the number presentation are required.
1535                      - values 144-159: The phone number format is an international number, including the country code prefix. If the plus sign ("+") is not included as part of the number and shall be added by the AG as needed.
1536                      - values 160-175: National number. No prefix nor escape digits included.
1537                      */
1538                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1539                     hfp_connection->bnip_type = value;
1540                     break;
1541                 case 3:
1542                     // <speed>: This optional field is not supported, and shall be left blank.
1543                     break;
1544                 case 4:
1545                     // <service>: Indicates which service this phone number relates to. Shall be either 4 (voice) or 5 (fax).
1546                 default:
1547                     break;
1548             }
1549             // index > 2 are ignored in switch above
1550             hfp_connection->parser_item_index++;
1551             break;
1552         case HFP_CMD_LIST_CURRENT_CALLS:
1553             switch(hfp_connection->parser_item_index){
1554                 case 0:
1555                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1556                     hfp_connection->clcc_idx = value;
1557                     break;
1558                 case 1:
1559                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1560                     hfp_connection->clcc_dir = value;
1561                     break;
1562                 case 2:
1563                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1564                     hfp_connection->clcc_status = value;
1565                     break;
1566                 case 3:
1567                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1568                     hfp_connection->clcc_mode = value;
1569                     break;
1570                 case 4:
1571                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1572                     hfp_connection->clcc_mpty = value;
1573                     break;
1574                 case 5:
1575                     btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1576                     break;
1577                 case 6:
1578                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1579                     hfp_connection->bnip_type = value;
1580                     break;
1581                 default:
1582                     break;
1583             }
1584             // index > 6 are ignored in switch above
1585             hfp_connection->parser_item_index++;
1586             break;
1587         case HFP_CMD_SET_MICROPHONE_GAIN:
1588             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1589             hfp_connection->microphone_gain = value;
1590             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1591             break;
1592         case HFP_CMD_SET_SPEAKER_GAIN:
1593             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1594             hfp_connection->speaker_gain = value;
1595             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1596             break;
1597         case HFP_CMD_TURN_OFF_EC_AND_NR:
1598             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1599             hfp_connection->ag_echo_and_noise_reduction = value;
1600             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1601             break;
1602         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1603             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1604             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1605             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1606             break;
1607         case HFP_CMD_HF_CONFIRMED_CODEC:
1608             hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer);
1609             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1610             break;
1611         case HFP_CMD_AG_SUGGESTED_CODEC:
1612             hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer);
1613             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1614             break;
1615         case HFP_CMD_SUPPORTED_FEATURES:
1616             hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer);
1617             log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features);
1618             break;
1619         case HFP_CMD_AVAILABLE_CODECS:
1620             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1621             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1622             hfp_next_codec_index(hfp_connection);
1623             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1624             break;
1625         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1626             btstack_strcpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, HFP_MAX_INDICATOR_DESC_SIZE, (char *)hfp_connection->line_buffer);
1627             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1628             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1629             break;
1630         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1631             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1632             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer);
1633             hfp_next_indicators_index(hfp_connection);
1634             break;
1635         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1636             hfp_next_indicators_index(hfp_connection);
1637             if (hfp_connection->parser_item_index != 4) break;
1638             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1639             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1640             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1641             break;
1642         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1643             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1644             if (hfp_connection->line_size > 2 ) break;
1645             memcpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE-1);
1646             hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name[HFP_CALL_SERVICE_SIZE - 1] = 0;
1647             hfp_next_remote_call_services_index(hfp_connection);
1648             break;
1649         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1650         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1651             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1652             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1653             hfp_next_indicators_index(hfp_connection);
1654             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1655             break;
1656         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1657             // HF parses inital AG gen. ind. state
1658             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1659             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1660             break;
1661         case HFP_CMD_HF_INDICATOR_STATUS:
1662             hfp_connection->parser_indicator_index = hfp_parse_indicator_index(hfp_connection);
1663             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1664             break;
1665         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1666             // AG parses new gen. ind. state
1667             if (hfp_connection->ignore_value){
1668                 hfp_connection->ignore_value = 0;
1669                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1670                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1671             }
1672             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1673                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1674                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1675             } else {
1676                 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1677                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1678                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1679                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1680             }
1681             hfp_next_indicators_index(hfp_connection);
1682             break;
1683         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1684             // indicators are indexed starting with 1
1685             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1686             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1687             break;
1688         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1689             hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1690             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1691             break;
1692         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1693             if (hfp_connection->line_buffer[0] == '3'){
1694                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1695                 break;
1696             }
1697             // TODO emit ERROR, wrong format
1698             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1699             break;
1700         case HFP_CMD_ERROR:
1701             break;
1702         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1703             hfp_connection->extended_audio_gateway_error = 1;
1704             hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1705             break;
1706         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1707             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1708             hfp_connection->ok_pending = 1;
1709             hfp_connection->extended_audio_gateway_error = 0;
1710             break;
1711         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1712         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1713         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1714             btstack_strcpy((char *)hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1715             break;
1716         case HFP_CMD_CALL_HOLD:
1717             hfp_connection->ag_call_hold_action = hfp_connection->line_buffer[0] - '0';
1718             if (hfp_connection->line_buffer[1] != '\0'){
1719                 hfp_connection->call_index = btstack_atoi((char *)&hfp_connection->line_buffer[1]);
1720             }
1721             break;
1722         case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1723             hfp_connection->ag_response_and_hold_action = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1724             break;
1725         case HFP_CMD_TRANSMIT_DTMF_CODES:
1726             hfp_connection->ag_dtmf_code = hfp_connection->line_buffer[0];
1727             break;
1728         case HFP_CMD_ENABLE_CLIP:
1729             hfp_connection->clip_enabled = hfp_connection->line_buffer[0] != '0';
1730             break;
1731         case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1732             hfp_connection->call_waiting_notification_enabled = hfp_connection->line_buffer[0] != '0';
1733             break;
1734         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1735             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1736             hfp_connection->ag_activate_voice_recognition_value = value;
1737             break;
1738         case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1739             switch(hfp_connection->parser_item_index){
1740                 case 0:
1741                     hfp_connection->ag_vra_status = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1742                     break;
1743                 case 1:
1744                     hfp_connection->ag_vra_state = (hfp_voice_recognition_state_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1745                     break;
1746                 case 2:
1747                     hfp_connection->ag_msg.text_id = 0;
1748                     for (i = 0 ; i < 4; i++){
1749                         hfp_connection->ag_msg.text_id = (hfp_connection->ag_msg.text_id << 4) | nibble_for_char(hfp_connection->line_buffer[i]);
1750                     }
1751                     break;
1752                 case 3:
1753                     hfp_connection->ag_msg.text_type = (hfp_text_type_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1754                     break;
1755                 case 4:
1756                     hfp_connection->ag_msg.text_operation = (hfp_text_operation_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1757                     break;
1758                 case 5:
1759                     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1760                     hfp_connection->ag_vra_msg_length = hfp_connection->line_size + 1;
1761                     break;
1762                 default:
1763                     break;
1764             }
1765             hfp_connection->parser_item_index++;
1766             break;
1767         default:
1768             break;
1769     }
1770 }
1771 
1772 static void hfp_handle_start_sdp_client_query(void * context){
1773     UNUSED(context);
1774 
1775     btstack_linked_list_iterator_t it;
1776     btstack_linked_list_iterator_init(&it, &hfp_connections);
1777     while (btstack_linked_list_iterator_has_next(&it)){
1778         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1779 
1780         if (connection->state != HFP_W2_SEND_SDP_QUERY) continue;
1781 
1782         connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1783         hfp_sdp_query_context.local_role = connection->local_role;
1784         (void)memcpy(hfp_sdp_query_context.remote_address, connection->remote_addr, 6);
1785         sdp_client_query_rfcomm_channel_and_name_for_service_class_uuid(&handle_query_rfcomm_event, connection->remote_addr, connection->service_uuid);
1786         return;
1787     }
1788 }
1789 
1790 uint8_t hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){
1791     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr, local_role);
1792     if (connection){
1793         return ERROR_CODE_COMMAND_DISALLOWED;
1794     }
1795 
1796     connection = hfp_create_connection(bd_addr, local_role);
1797     if (!connection){
1798         return BTSTACK_MEMORY_ALLOC_FAILED;
1799     }
1800 
1801     connection->state = HFP_W2_SEND_SDP_QUERY;
1802 
1803     bd_addr_copy(connection->remote_addr, bd_addr);
1804     connection->service_uuid = service_uuid;
1805 
1806     hfp_sdp_query_request.callback = &hfp_handle_start_sdp_client_query;
1807     // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1808     (void) sdp_client_register_query_callback(&hfp_sdp_query_request);
1809     return ERROR_CODE_SUCCESS;
1810 }
1811 
1812 void hfp_trigger_release_service_level_connection(hfp_connection_t * hfp_connection){
1813     // called internally, NULL check already performed
1814     btstack_assert(hfp_connection != NULL);
1815 
1816     hfp_trigger_release_audio_connection(hfp_connection);
1817     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1818         hfp_connection->state = HFP_IDLE;
1819         return;
1820     }
1821 
1822     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1823         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1824         return;
1825     }
1826     hfp_connection->release_slc_connection = 1;
1827     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1828         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1829         return;
1830     }
1831 
1832     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1833         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1834         hfp_connection->release_audio_connection = 1;
1835         return;
1836     }
1837 }
1838 
1839 uint8_t hfp_trigger_release_audio_connection(hfp_connection_t * hfp_connection){
1840     // called internally, NULL check already performed
1841     btstack_assert(hfp_connection != NULL);
1842     if (hfp_connection->state <= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
1843         return ERROR_CODE_COMMAND_DISALLOWED;
1844     }
1845     switch (hfp_connection->state) {
1846         case HFP_W2_CONNECT_SCO:
1847             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1848             break;
1849         case HFP_W4_SCO_CONNECTED:
1850         case HFP_AUDIO_CONNECTION_ESTABLISHED:
1851             hfp_connection->release_audio_connection = 1;
1852             break;
1853         default:
1854             return ERROR_CODE_COMMAND_DISALLOWED;
1855     }
1856     return ERROR_CODE_SUCCESS;
1857 }
1858 
1859 static const struct link_settings {
1860     const uint16_t max_latency;
1861     const uint8_t  retransmission_effort;
1862     const uint16_t packet_types;
1863     const bool     eSCO;
1864     const uint8_t  codec;
1865 } hfp_link_settings [] = {
1866     { 0xffff, 0xff, SCO_PACKET_TYPES_HV1,  false, HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_D0
1867     { 0xffff, 0xff, SCO_PACKET_TYPES_HV3,  false, HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_D1
1868     { 0x0007, 0x01, SCO_PACKET_TYPES_EV3,  true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S1
1869     { 0x0007, 0x01, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S2
1870     { 0x000a, 0x01, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S3
1871     { 0x000c, 0x02, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S4
1872     { 0x0008, 0x02, SCO_PACKET_TYPES_EV3,  true,  HFP_CODEC_MSBC }, // HFP_LINK_SETTINGS_T1
1873     { 0x000d, 0x02, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_MSBC }  // HFP_LINK_SETTINGS_T2
1874 };
1875 
1876 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){
1877     // all packet types, fixed bandwidth
1878     int setting = hfp_connection->link_setting;
1879     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1880     hfp_sco_establishment_active = hfp_connection;
1881     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1882     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1883 #ifdef ENABLE_BCM_PCM_WBS
1884         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
1885 #else
1886         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
1887 #endif
1888     }
1889     // get packet types - bits 6-9 are 'don't allow'
1890     uint16_t packet_types = hfp_link_settings[setting].packet_types ^ 0x03c0;
1891     hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency,
1892         sco_voice_setting, hfp_link_settings[setting].retransmission_effort, packet_types);
1893 }
1894 
1895 void hfp_accept_synchronous_connection(hfp_connection_t * hfp_connection, bool incoming_eSCO){
1896 
1897     // remote supported feature eSCO is set if link type is eSCO
1898     // eSCO: S4 - max latency == transmission interval = 0x000c == 12 ms,
1899     uint16_t max_latency;
1900     uint8_t  retransmission_effort;
1901     uint16_t packet_types;
1902 
1903     if (incoming_eSCO && hci_extended_sco_link_supported() && hci_remote_esco_supported(hfp_connection->acl_handle)){
1904         max_latency = 0x000c;
1905         retransmission_effort = 0x02;
1906         // eSCO: EV3 and 2-EV3
1907         packet_types = 0x0048;
1908     } else {
1909         max_latency = 0xffff;
1910         retransmission_effort = 0xff;
1911         // sco: HV1 and HV3
1912         packet_types = 0x005;
1913     }
1914 
1915     // mSBC only allows for transparent data
1916     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1917     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1918 #ifdef ENABLE_BCM_PCM_WBS
1919         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
1920 #else
1921         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
1922 #endif
1923     }
1924 
1925     // filter packet types
1926     packet_types &= hfp_get_sco_packet_types();
1927 
1928     // bits 6-9 are 'don't allow'
1929     packet_types ^= 0x3c0;
1930 
1931     log_info("HFP: sending hci_accept_connection_request, packet types 0x%04x, sco_voice_setting 0x%02x", packet_types, sco_voice_setting);
1932     hci_send_cmd(&hci_accept_synchronous_connection, hfp_connection->remote_addr, 8000, 8000, max_latency,
1933                  sco_voice_setting, retransmission_effort, packet_types);
1934 }
1935 
1936 #ifdef ENABLE_CC256X_ASSISTED_HFP
1937 void hfp_cc256x_prepare_for_sco(hfp_connection_t * hfp_connection){
1938     hfp_connection->cc256x_send_write_codec_config = true;
1939     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1940         hfp_connection->cc256x_send_wbs_associate = true;
1941     }
1942 }
1943 
1944 void hfp_cc256x_write_codec_config(hfp_connection_t * hfp_connection){
1945     uint32_t sample_rate_hz;
1946     uint16_t clock_rate_khz;
1947     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1948         clock_rate_khz = 512;
1949         sample_rate_hz = 16000;
1950     } else {
1951         clock_rate_khz = 256;
1952         sample_rate_hz = 8000;
1953     }
1954     uint8_t clock_direction = 0;        // master
1955     uint16_t frame_sync_duty_cycle = 0; // i2s with 50%
1956     uint8_t  frame_sync_edge = 1;       // rising edge
1957     uint8_t  frame_sync_polarity = 0;   // active high
1958     uint8_t  reserved = 0;
1959     uint16_t size = 16;
1960     uint16_t chan_1_offset = 1;
1961     uint16_t chan_2_offset = chan_1_offset + size;
1962     uint8_t  out_edge = 1;              // rising
1963     uint8_t  in_edge = 0;               // falling
1964     hci_send_cmd(&hci_ti_write_codec_config, clock_rate_khz, clock_direction, sample_rate_hz, frame_sync_duty_cycle,
1965                  frame_sync_edge, frame_sync_polarity, reserved,
1966                  size, chan_1_offset, out_edge, size, chan_1_offset, in_edge, reserved,
1967                  size, chan_2_offset, out_edge, size, chan_2_offset, in_edge, reserved);
1968 }
1969 #endif
1970 
1971 #ifdef ENABLE_BCM_PCM_WBS
1972 void hfp_bcm_prepare_for_sco(hfp_connection_t * hfp_connection){
1973     hfp_connection->bcm_send_write_i2spcm_interface_param = true;
1974     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1975         hfp_connection->bcm_send_enable_wbs = true;
1976     }
1977 }
1978 void hfp_bcm_write_i2spcm_interface_param(hfp_connection_t * hfp_connection){
1979     uint8_t sample_rate = (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? 1 : 0;
1980     // i2s enable, master, 8/16 kHz, 512 kHz
1981     hci_send_cmd(&hci_bcm_write_i2spcm_interface_paramhci_bcm_write_i2spcm_interface_param, 1, 1, sample_rate, 2);
1982 }
1983 #endif
1984 
1985 void hfp_set_hf_callback(btstack_packet_handler_t callback){
1986     hfp_hf_callback = callback;
1987 }
1988 
1989 void hfp_set_ag_callback(btstack_packet_handler_t callback){
1990     hfp_ag_callback = callback;
1991 }
1992 
1993 void hfp_set_ag_rfcomm_packet_handler(btstack_packet_handler_t handler){
1994     hfp_ag_rfcomm_packet_handler = handler;
1995 }
1996 
1997 void hfp_set_hf_rfcomm_packet_handler(btstack_packet_handler_t handler){
1998     hfp_hf_rfcomm_packet_handler = handler;
1999 }
2000 
2001 void hfp_init(void){
2002     hfp_allowed_sco_packet_types = SCO_PACKET_TYPES_ALL;
2003 }
2004 
2005 void hfp_deinit(void){
2006     hfp_allowed_sco_packet_types = 0;
2007     hfp_connections = NULL;
2008     hfp_hf_callback = NULL;
2009     hfp_ag_callback = NULL;
2010     hfp_hf_rfcomm_packet_handler = NULL;
2011     hfp_ag_rfcomm_packet_handler = NULL;
2012     hfp_sco_establishment_active = NULL;
2013     hfp_custom_commands_ag = NULL;
2014     (void) memset(&hfp_sdp_query_context, 0, sizeof(hfp_sdp_query_context_t));
2015     (void) memset(&hfp_sdp_query_request, 0, sizeof(btstack_context_callback_registration_t));
2016 }
2017 
2018 void hfp_set_sco_packet_types(uint16_t packet_types){
2019     hfp_allowed_sco_packet_types = packet_types;
2020 }
2021 
2022 uint16_t hfp_get_sco_packet_types(void){
2023     return hfp_allowed_sco_packet_types;
2024 }
2025 
2026 hfp_link_settings_t hfp_next_link_setting(hfp_link_settings_t current_setting, bool local_eSCO_supported, bool remote_eSCO_supported, bool eSCO_S4_supported, uint8_t negotiated_codec){
2027     int8_t setting = (int8_t) current_setting;
2028     bool can_use_eSCO = local_eSCO_supported && remote_eSCO_supported;
2029     while (setting > 0){
2030         setting--;
2031         // skip if eSCO required but not available
2032         if (hfp_link_settings[setting].eSCO && !can_use_eSCO) continue;
2033         // skip if S4 but not supported
2034         if ((setting == (int8_t) HFP_LINK_SETTINGS_S4) && !eSCO_S4_supported) continue;
2035         // skip wrong codec
2036         if ( hfp_link_settings[setting].codec != negotiated_codec) continue;
2037         // skip disabled packet types
2038         uint16_t required_packet_types = hfp_link_settings[setting].packet_types;
2039         uint16_t allowed_packet_types  = hfp_allowed_sco_packet_types;
2040         if ((required_packet_types & allowed_packet_types) == 0) continue;
2041 
2042         // found matching setting
2043         return (hfp_link_settings_t) setting;
2044     }
2045     return HFP_LINK_SETTINGS_NONE;
2046 }
2047 
2048 static hfp_link_settings_t hfp_next_link_setting_for_connection(hfp_link_settings_t current_setting, hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported){
2049     bool local_eSCO_supported  = hci_extended_sco_link_supported();
2050     bool remote_eSCO_supported = hci_remote_esco_supported(hfp_connection->acl_handle);
2051     uint8_t negotiated_codec   = hfp_connection->negotiated_codec;
2052     return  hfp_next_link_setting(current_setting, local_eSCO_supported, remote_eSCO_supported, eSCO_S4_supported, negotiated_codec);
2053 }
2054 
2055 void hfp_init_link_settings(hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported){
2056     // get highest possible link setting
2057     hfp_connection->link_setting = hfp_next_link_setting_for_connection(HFP_LINK_SETTINGS_NONE, hfp_connection, eSCO_S4_supported);
2058     log_info("hfp_init_link_settings: %u", hfp_connection->link_setting);
2059 }
2060 
2061 #define HFP_HF_RX_DEBUG_PRINT_LINE 80
2062 
2063 void hfp_log_rfcomm_message(const char * tag, uint8_t * packet, uint16_t size){
2064 #ifdef ENABLE_LOG_INFO
2065     // encode \n\r
2066     char printable[HFP_HF_RX_DEBUG_PRINT_LINE+2];
2067     int i = 0;
2068     int pos;
2069     for (pos=0 ; (pos < size) && (i < (HFP_HF_RX_DEBUG_PRINT_LINE - 3)) ; pos++){
2070         switch (packet[pos]){
2071             case '\n':
2072                 printable[i++] = '\\';
2073                 printable[i++] = 'n';
2074                 break;
2075             case '\r':
2076                 printable[i++] = '\\';
2077                 printable[i++] = 'r';
2078                 break;
2079             default:
2080                 printable[i++] = packet[pos];
2081                 break;
2082         }
2083     }
2084     printable[i] = 0;
2085     log_info("%s: '%s'", tag, printable);
2086 #endif
2087 }
2088 
2089 void hfp_register_custom_ag_command(hfp_custom_at_command_t * custom_at_command){
2090     btstack_linked_list_add(&hfp_custom_commands_ag, (btstack_linked_item_t *) custom_at_command);
2091 }
2092