xref: /btstack/src/classic/hfp.c (revision c824d78c0a34df89b57d535abafcc7dacf30bb06)
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     // check for custom commands, AG only
1167     if (isHandsFree == 0) {
1168         const hfp_custom_at_command_t * custom_at_command = hfp_custom_command_lookup(line_buffer);
1169         if (custom_at_command != NULL){
1170             return HFP_CMD_CUSTOM_MESSAGE;
1171         }
1172     }
1173 
1174     // table lookup based on role
1175     uint16_t num_entries;
1176     hfp_command_entry_t * table;
1177     if (isHandsFree == 0){
1178         table = hfp_ag_commmand_table;
1179         num_entries = sizeof(hfp_ag_commmand_table) / sizeof(hfp_command_entry_t);
1180     } else {
1181         table = hfp_hf_commmand_table;
1182         num_entries = sizeof(hfp_hf_commmand_table) / sizeof(hfp_command_entry_t);
1183     }
1184     // binary search
1185     uint16_t left = 0;
1186     uint16_t right = num_entries - 1;
1187     while (left <= right){
1188         uint16_t middle = left + (right - left) / 2;
1189         hfp_command_entry_t *entry = &table[middle];
1190         int match = strcmp(line_buffer, entry->command);
1191         if (match < 0){
1192             // search term is lower than middle element
1193             if (right == 0) break;
1194             right = middle - 1;
1195         } else if (match == 0){
1196             return entry->command_id;
1197         } else {
1198             // search term is higher than middle element
1199             left = middle + 1;
1200         }
1201     }
1202 
1203     // note: if parser in CMD_HEADER state would treats digits and maybe '+' as separator, match on "ATD" would work.
1204     // note: phone number is currently expected in line_buffer[3..]
1205     // prefix match on 'ATD', AG only
1206     if ((isHandsFree == 0) && (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0)){
1207         return HFP_CMD_CALL_PHONE_NUMBER;
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_parser_reset_line_buffer(hfp_connection);
1348             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1349 
1350             return processed;
1351 
1352         case HFP_PARSER_CMD_SEQUENCE:
1353             // handle empty fields
1354             if ((byte == ',' ) && (hfp_connection->line_size == 0)){
1355                 hfp_connection->line_buffer[0] = 0;
1356                 hfp_connection->ignore_value = 1;
1357                 parse_sequence(hfp_connection);
1358                 return true;
1359             }
1360 
1361             hfp_parser_store_if_token(hfp_connection, byte);
1362             if (!hfp_parser_is_separator(byte)) return true;
1363 
1364             // ignore empty tokens
1365             switch (hfp_connection->command){
1366                 case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1367                     // don't ignore empty string
1368                     break;
1369                 default:
1370                     if (hfp_parser_is_buffer_empty(hfp_connection) && (hfp_connection->ignore_value == 0)) {
1371                         return true;
1372                     }
1373                     break;
1374             }
1375 
1376             parse_sequence(hfp_connection);
1377 
1378             hfp_parser_reset_line_buffer(hfp_connection);
1379 
1380             switch (hfp_connection->command){
1381                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1382                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1383                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1384                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1385                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1386                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1387                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1388                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1389                 case HFP_CMD_HF_INDICATOR_STATUS:
1390                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
1391                     break;
1392                 default:
1393                     break;
1394             }
1395             return true;
1396 
1397         case HFP_PARSER_SECOND_ITEM:
1398 
1399             hfp_parser_store_if_token(hfp_connection, byte);
1400             if (!hfp_parser_is_separator(byte)) return true;
1401 
1402             switch (hfp_connection->command){
1403                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1404                     log_info("format %s, ", hfp_connection->line_buffer);
1405                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1406                     break;
1407                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1408                     log_info("format %s \n", hfp_connection->line_buffer);
1409                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1410                     break;
1411                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1412                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1413                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1414                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1415                     break;
1416                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1417                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1418                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1419                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1420                     break;
1421                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1422                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer);
1423                     log_info("%s, ", hfp_connection->line_buffer);
1424                     break;
1425                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1426                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1427                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1428                     hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1429                     break;
1430                 case HFP_CMD_HF_INDICATOR_STATUS:
1431                     hfp_connection->parser_indicator_value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1432                     break;
1433                 default:
1434                     break;
1435             }
1436 
1437             hfp_parser_reset_line_buffer(hfp_connection);
1438 
1439             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
1440 
1441             return true;
1442 
1443         case HFP_PARSER_THIRD_ITEM:
1444 
1445             hfp_parser_store_if_token(hfp_connection, byte);
1446             if (!hfp_parser_is_separator(byte)) return true;
1447 
1448             switch (hfp_connection->command){
1449                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1450                     btstack_strcpy(hfp_connection->network_operator.name, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE,  (char *)hfp_connection->line_buffer);
1451                     break;
1452                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1453                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer);
1454                     hfp_next_indicators_index(hfp_connection);
1455                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1456                     break;
1457                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1458                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
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->found_equal_sign = false;
1491         hfp_connection->parser_item_index = 0;
1492         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1493     }
1494 }
1495 
1496 static void parse_sequence(hfp_connection_t * hfp_connection){
1497     int value;
1498     switch (hfp_connection->command){
1499         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1500             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1501             int i;
1502             switch (hfp_connection->parser_item_index){
1503                 case 0:
1504                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1505                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1506                             hfp_connection->parser_indicator_index = i;
1507                             break;
1508                         }
1509                     }
1510                     break;
1511                 case 1:
1512                     if (hfp_connection->parser_indicator_index <0) break;
1513                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1514                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1515                      hfp_connection->parser_item_index, value);
1516                     break;
1517                 default:
1518                     break;
1519             }
1520             hfp_next_indicators_index(hfp_connection);
1521             break;
1522 
1523         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1524             switch(hfp_connection->parser_item_index){
1525                 case 0:
1526                     // <alpha>: This optional field is not supported, and shall be left blank.
1527                     break;
1528                 case 1:
1529                     // <number>: Quoted string containing the phone number in the format specified by <type>.
1530                     btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1531                     break;
1532                 case 2:
1533                     /*
1534                       <type> field specifies the format of the phone number provided, and can be one of the following values:
1535                       - 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.
1536                      - 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.
1537                      - values 160-175: National number. No prefix nor escape digits included.
1538                      */
1539                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1540                     hfp_connection->bnip_type = value;
1541                     break;
1542                 case 3:
1543                     // <speed>: This optional field is not supported, and shall be left blank.
1544                     break;
1545                 case 4:
1546                     // <service>: Indicates which service this phone number relates to. Shall be either 4 (voice) or 5 (fax).
1547                 default:
1548                     break;
1549             }
1550             // index > 2 are ignored in switch above
1551             hfp_connection->parser_item_index++;
1552             break;
1553         case HFP_CMD_LIST_CURRENT_CALLS:
1554             switch(hfp_connection->parser_item_index){
1555                 case 0:
1556                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1557                     hfp_connection->clcc_idx = value;
1558                     break;
1559                 case 1:
1560                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1561                     hfp_connection->clcc_dir = value;
1562                     break;
1563                 case 2:
1564                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1565                     hfp_connection->clcc_status = value;
1566                     break;
1567                 case 3:
1568                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1569                     hfp_connection->clcc_mode = value;
1570                     break;
1571                 case 4:
1572                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1573                     hfp_connection->clcc_mpty = value;
1574                     break;
1575                 case 5:
1576                     btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1577                     break;
1578                 case 6:
1579                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1580                     hfp_connection->bnip_type = value;
1581                     break;
1582                 default:
1583                     break;
1584             }
1585             // index > 6 are ignored in switch above
1586             hfp_connection->parser_item_index++;
1587             break;
1588         case HFP_CMD_SET_MICROPHONE_GAIN:
1589             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1590             hfp_connection->microphone_gain = value;
1591             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1592             break;
1593         case HFP_CMD_SET_SPEAKER_GAIN:
1594             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1595             hfp_connection->speaker_gain = value;
1596             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1597             break;
1598         case HFP_CMD_TURN_OFF_EC_AND_NR:
1599             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1600             hfp_connection->ag_echo_and_noise_reduction = value;
1601             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1602             break;
1603         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1604             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1605             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1606             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1607             break;
1608         case HFP_CMD_HF_CONFIRMED_CODEC:
1609             hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer);
1610             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1611             break;
1612         case HFP_CMD_AG_SUGGESTED_CODEC:
1613             hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer);
1614             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1615             break;
1616         case HFP_CMD_SUPPORTED_FEATURES:
1617             hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer);
1618             log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features);
1619             break;
1620         case HFP_CMD_AVAILABLE_CODECS:
1621             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1622             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1623             hfp_next_codec_index(hfp_connection);
1624             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1625             break;
1626         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1627             btstack_strcpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, HFP_MAX_INDICATOR_DESC_SIZE, (char *)hfp_connection->line_buffer);
1628             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1629             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1630             break;
1631         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1632             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1633             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer);
1634             hfp_next_indicators_index(hfp_connection);
1635             break;
1636         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1637             hfp_next_indicators_index(hfp_connection);
1638             if (hfp_connection->parser_item_index != 4) break;
1639             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1640             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1641             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1642             break;
1643         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1644             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1645             if (hfp_connection->line_size > 2 ) break;
1646             memcpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE-1);
1647             hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name[HFP_CALL_SERVICE_SIZE - 1] = 0;
1648             hfp_next_remote_call_services_index(hfp_connection);
1649             break;
1650         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1651         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1652             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1653             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1654             hfp_next_indicators_index(hfp_connection);
1655             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1656             break;
1657         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1658             // HF parses inital AG gen. ind. state
1659             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1660             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1661             break;
1662         case HFP_CMD_HF_INDICATOR_STATUS:
1663             hfp_connection->parser_indicator_index = hfp_parse_indicator_index(hfp_connection);
1664             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1665             break;
1666         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1667             // AG parses new gen. ind. state
1668             if (hfp_connection->ignore_value){
1669                 hfp_connection->ignore_value = 0;
1670                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1671                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1672             }
1673             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1674                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1675                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1676             } else {
1677                 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1678                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1679                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1680                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1681             }
1682             hfp_next_indicators_index(hfp_connection);
1683             break;
1684         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1685             // indicators are indexed starting with 1
1686             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1687             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1688             break;
1689         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1690             hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1691             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1692             break;
1693         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1694             if (hfp_connection->line_buffer[0] == '3'){
1695                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1696                 break;
1697             }
1698             // TODO emit ERROR, wrong format
1699             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1700             break;
1701         case HFP_CMD_ERROR:
1702             break;
1703         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1704             hfp_connection->extended_audio_gateway_error = 1;
1705             hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1706             break;
1707         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1708             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1709             hfp_connection->ok_pending = 1;
1710             hfp_connection->extended_audio_gateway_error = 0;
1711             break;
1712         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1713         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1714         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1715             btstack_strcpy((char *)hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1716             break;
1717         case HFP_CMD_CALL_HOLD:
1718             hfp_connection->ag_call_hold_action = hfp_connection->line_buffer[0] - '0';
1719             if (hfp_connection->line_buffer[1] != '\0'){
1720                 hfp_connection->call_index = btstack_atoi((char *)&hfp_connection->line_buffer[1]);
1721             }
1722             break;
1723         case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1724             hfp_connection->ag_response_and_hold_action = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1725             break;
1726         case HFP_CMD_TRANSMIT_DTMF_CODES:
1727             hfp_connection->ag_dtmf_code = hfp_connection->line_buffer[0];
1728             break;
1729         case HFP_CMD_ENABLE_CLIP:
1730             hfp_connection->clip_enabled = hfp_connection->line_buffer[0] != '0';
1731             break;
1732         case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1733             hfp_connection->call_waiting_notification_enabled = hfp_connection->line_buffer[0] != '0';
1734             break;
1735         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1736             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1737             hfp_connection->ag_activate_voice_recognition_value = value;
1738             break;
1739         case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1740             switch(hfp_connection->parser_item_index){
1741                 case 0:
1742                     hfp_connection->ag_vra_status = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1743                     break;
1744                 case 1:
1745                     hfp_connection->ag_vra_state = (hfp_voice_recognition_state_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1746                     break;
1747                 case 2:
1748                     hfp_connection->ag_msg.text_id = 0;
1749                     for (i = 0 ; i < 4; i++){
1750                         hfp_connection->ag_msg.text_id = (hfp_connection->ag_msg.text_id << 4) | nibble_for_char(hfp_connection->line_buffer[i]);
1751                     }
1752                     break;
1753                 case 3:
1754                     hfp_connection->ag_msg.text_type = (hfp_text_type_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1755                     break;
1756                 case 4:
1757                     hfp_connection->ag_msg.text_operation = (hfp_text_operation_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1758                     break;
1759                 case 5:
1760                     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1761                     hfp_connection->ag_vra_msg_length = hfp_connection->line_size + 1;
1762                     break;
1763                 default:
1764                     break;
1765             }
1766             hfp_connection->parser_item_index++;
1767             break;
1768         default:
1769             break;
1770     }
1771 }
1772 
1773 static void hfp_handle_start_sdp_client_query(void * context){
1774     UNUSED(context);
1775 
1776     btstack_linked_list_iterator_t it;
1777     btstack_linked_list_iterator_init(&it, &hfp_connections);
1778     while (btstack_linked_list_iterator_has_next(&it)){
1779         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1780 
1781         if (connection->state != HFP_W2_SEND_SDP_QUERY) continue;
1782 
1783         connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1784         hfp_sdp_query_context.local_role = connection->local_role;
1785         (void)memcpy(hfp_sdp_query_context.remote_address, connection->remote_addr, 6);
1786         sdp_client_query_rfcomm_channel_and_name_for_service_class_uuid(&handle_query_rfcomm_event, connection->remote_addr, connection->service_uuid);
1787         return;
1788     }
1789 }
1790 
1791 uint8_t hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){
1792     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr, local_role);
1793     if (connection){
1794         return ERROR_CODE_COMMAND_DISALLOWED;
1795     }
1796 
1797     connection = hfp_create_connection(bd_addr, local_role);
1798     if (!connection){
1799         return BTSTACK_MEMORY_ALLOC_FAILED;
1800     }
1801 
1802     connection->state = HFP_W2_SEND_SDP_QUERY;
1803 
1804     bd_addr_copy(connection->remote_addr, bd_addr);
1805     connection->service_uuid = service_uuid;
1806 
1807     hfp_sdp_query_request.callback = &hfp_handle_start_sdp_client_query;
1808     // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1809     (void) sdp_client_register_query_callback(&hfp_sdp_query_request);
1810     return ERROR_CODE_SUCCESS;
1811 }
1812 
1813 void hfp_trigger_release_service_level_connection(hfp_connection_t * hfp_connection){
1814     // called internally, NULL check already performed
1815     btstack_assert(hfp_connection != NULL);
1816 
1817     hfp_trigger_release_audio_connection(hfp_connection);
1818     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1819         hfp_connection->state = HFP_IDLE;
1820         return;
1821     }
1822 
1823     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1824         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1825         return;
1826     }
1827     hfp_connection->release_slc_connection = 1;
1828     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1829         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1830         return;
1831     }
1832 
1833     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1834         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1835         hfp_connection->release_audio_connection = 1;
1836         return;
1837     }
1838 }
1839 
1840 uint8_t hfp_trigger_release_audio_connection(hfp_connection_t * hfp_connection){
1841     // called internally, NULL check already performed
1842     btstack_assert(hfp_connection != NULL);
1843     if (hfp_connection->state <= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
1844         return ERROR_CODE_COMMAND_DISALLOWED;
1845     }
1846     switch (hfp_connection->state) {
1847         case HFP_W2_CONNECT_SCO:
1848             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1849             break;
1850         case HFP_W4_SCO_CONNECTED:
1851         case HFP_AUDIO_CONNECTION_ESTABLISHED:
1852             hfp_connection->release_audio_connection = 1;
1853             break;
1854         default:
1855             return ERROR_CODE_COMMAND_DISALLOWED;
1856     }
1857     return ERROR_CODE_SUCCESS;
1858 }
1859 
1860 static const struct link_settings {
1861     const uint16_t max_latency;
1862     const uint8_t  retransmission_effort;
1863     const uint16_t packet_types;
1864     const bool     eSCO;
1865     const uint8_t  codec;
1866 } hfp_link_settings [] = {
1867     { 0xffff, 0xff, SCO_PACKET_TYPES_HV1,  false, HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_D0
1868     { 0xffff, 0xff, SCO_PACKET_TYPES_HV3,  false, HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_D1
1869     { 0x0007, 0x01, SCO_PACKET_TYPES_EV3,  true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S1
1870     { 0x0007, 0x01, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S2
1871     { 0x000a, 0x01, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S3
1872     { 0x000c, 0x02, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S4
1873     { 0x0008, 0x02, SCO_PACKET_TYPES_EV3,  true,  HFP_CODEC_MSBC }, // HFP_LINK_SETTINGS_T1
1874     { 0x000d, 0x02, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_MSBC }  // HFP_LINK_SETTINGS_T2
1875 };
1876 
1877 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){
1878     // all packet types, fixed bandwidth
1879     int setting = hfp_connection->link_setting;
1880     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1881     hfp_sco_establishment_active = hfp_connection;
1882     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1883     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1884 #ifdef ENABLE_BCM_PCM_WBS
1885         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
1886 #else
1887         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
1888 #endif
1889     }
1890     // get packet types - bits 6-9 are 'don't allow'
1891     uint16_t packet_types = hfp_link_settings[setting].packet_types ^ 0x03c0;
1892     hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency,
1893         sco_voice_setting, hfp_link_settings[setting].retransmission_effort, packet_types);
1894 }
1895 
1896 void hfp_accept_synchronous_connection(hfp_connection_t * hfp_connection, bool incoming_eSCO){
1897 
1898     // remote supported feature eSCO is set if link type is eSCO
1899     // eSCO: S4 - max latency == transmission interval = 0x000c == 12 ms,
1900     uint16_t max_latency;
1901     uint8_t  retransmission_effort;
1902     uint16_t packet_types;
1903 
1904     if (incoming_eSCO && hci_extended_sco_link_supported() && hci_remote_esco_supported(hfp_connection->acl_handle)){
1905         max_latency = 0x000c;
1906         retransmission_effort = 0x02;
1907         // eSCO: EV3 and 2-EV3
1908         packet_types = 0x0048;
1909     } else {
1910         max_latency = 0xffff;
1911         retransmission_effort = 0xff;
1912         // sco: HV1 and HV3
1913         packet_types = 0x005;
1914     }
1915 
1916     // mSBC only allows for transparent data
1917     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1918     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1919 #ifdef ENABLE_BCM_PCM_WBS
1920         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
1921 #else
1922         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
1923 #endif
1924     }
1925 
1926     // filter packet types
1927     packet_types &= hfp_get_sco_packet_types();
1928 
1929     // bits 6-9 are 'don't allow'
1930     packet_types ^= 0x3c0;
1931 
1932     log_info("HFP: sending hci_accept_connection_request, packet types 0x%04x, sco_voice_setting 0x%02x", packet_types, sco_voice_setting);
1933     hci_send_cmd(&hci_accept_synchronous_connection, hfp_connection->remote_addr, 8000, 8000, max_latency,
1934                  sco_voice_setting, retransmission_effort, packet_types);
1935 }
1936 
1937 #ifdef ENABLE_CC256X_ASSISTED_HFP
1938 void hfp_cc256x_prepare_for_sco(hfp_connection_t * hfp_connection){
1939     hfp_connection->cc256x_send_write_codec_config = true;
1940     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1941         hfp_connection->cc256x_send_wbs_associate = true;
1942     }
1943 }
1944 
1945 void hfp_cc256x_write_codec_config(hfp_connection_t * hfp_connection){
1946     uint32_t sample_rate_hz;
1947     uint16_t clock_rate_khz;
1948     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1949         clock_rate_khz = 512;
1950         sample_rate_hz = 16000;
1951     } else {
1952         clock_rate_khz = 256;
1953         sample_rate_hz = 8000;
1954     }
1955     uint8_t clock_direction = 0;        // master
1956     uint16_t frame_sync_duty_cycle = 0; // i2s with 50%
1957     uint8_t  frame_sync_edge = 1;       // rising edge
1958     uint8_t  frame_sync_polarity = 0;   // active high
1959     uint8_t  reserved = 0;
1960     uint16_t size = 16;
1961     uint16_t chan_1_offset = 1;
1962     uint16_t chan_2_offset = chan_1_offset + size;
1963     uint8_t  out_edge = 1;              // rising
1964     uint8_t  in_edge = 0;               // falling
1965     hci_send_cmd(&hci_ti_write_codec_config, clock_rate_khz, clock_direction, sample_rate_hz, frame_sync_duty_cycle,
1966                  frame_sync_edge, frame_sync_polarity, reserved,
1967                  size, chan_1_offset, out_edge, size, chan_1_offset, in_edge, reserved,
1968                  size, chan_2_offset, out_edge, size, chan_2_offset, in_edge, reserved);
1969 }
1970 #endif
1971 
1972 #ifdef ENABLE_BCM_PCM_WBS
1973 void hfp_bcm_prepare_for_sco(hfp_connection_t * hfp_connection){
1974     hfp_connection->bcm_send_write_i2spcm_interface_param = true;
1975     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1976         hfp_connection->bcm_send_enable_wbs = true;
1977     }
1978 }
1979 void hfp_bcm_write_i2spcm_interface_param(hfp_connection_t * hfp_connection){
1980     uint8_t sample_rate = (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? 1 : 0;
1981     // i2s enable, master, 8/16 kHz, 512 kHz
1982     hci_send_cmd(&hci_bcm_write_i2spcm_interface_paramhci_bcm_write_i2spcm_interface_param, 1, 1, sample_rate, 2);
1983 }
1984 #endif
1985 
1986 void hfp_set_hf_callback(btstack_packet_handler_t callback){
1987     hfp_hf_callback = callback;
1988 }
1989 
1990 void hfp_set_ag_callback(btstack_packet_handler_t callback){
1991     hfp_ag_callback = callback;
1992 }
1993 
1994 void hfp_set_ag_rfcomm_packet_handler(btstack_packet_handler_t handler){
1995     hfp_ag_rfcomm_packet_handler = handler;
1996 }
1997 
1998 void hfp_set_hf_rfcomm_packet_handler(btstack_packet_handler_t handler){
1999     hfp_hf_rfcomm_packet_handler = handler;
2000 }
2001 
2002 void hfp_init(void){
2003     hfp_allowed_sco_packet_types = SCO_PACKET_TYPES_ALL;
2004 }
2005 
2006 void hfp_deinit(void){
2007     hfp_allowed_sco_packet_types = 0;
2008     hfp_connections = NULL;
2009     hfp_hf_callback = NULL;
2010     hfp_ag_callback = NULL;
2011     hfp_hf_rfcomm_packet_handler = NULL;
2012     hfp_ag_rfcomm_packet_handler = NULL;
2013     hfp_sco_establishment_active = NULL;
2014     hfp_custom_commands_ag = NULL;
2015     (void) memset(&hfp_sdp_query_context, 0, sizeof(hfp_sdp_query_context_t));
2016     (void) memset(&hfp_sdp_query_request, 0, sizeof(btstack_context_callback_registration_t));
2017 }
2018 
2019 void hfp_set_sco_packet_types(uint16_t packet_types){
2020     hfp_allowed_sco_packet_types = packet_types;
2021 }
2022 
2023 uint16_t hfp_get_sco_packet_types(void){
2024     return hfp_allowed_sco_packet_types;
2025 }
2026 
2027 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){
2028     int8_t setting = (int8_t) current_setting;
2029     bool can_use_eSCO = local_eSCO_supported && remote_eSCO_supported;
2030     while (setting > 0){
2031         setting--;
2032         // skip if eSCO required but not available
2033         if (hfp_link_settings[setting].eSCO && !can_use_eSCO) continue;
2034         // skip if S4 but not supported
2035         if ((setting == (int8_t) HFP_LINK_SETTINGS_S4) && !eSCO_S4_supported) continue;
2036         // skip wrong codec
2037         if ( hfp_link_settings[setting].codec != negotiated_codec) continue;
2038         // skip disabled packet types
2039         uint16_t required_packet_types = hfp_link_settings[setting].packet_types;
2040         uint16_t allowed_packet_types  = hfp_allowed_sco_packet_types;
2041         if ((required_packet_types & allowed_packet_types) == 0) continue;
2042 
2043         // found matching setting
2044         return (hfp_link_settings_t) setting;
2045     }
2046     return HFP_LINK_SETTINGS_NONE;
2047 }
2048 
2049 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){
2050     bool local_eSCO_supported  = hci_extended_sco_link_supported();
2051     bool remote_eSCO_supported = hci_remote_esco_supported(hfp_connection->acl_handle);
2052     uint8_t negotiated_codec   = hfp_connection->negotiated_codec;
2053     return  hfp_next_link_setting(current_setting, local_eSCO_supported, remote_eSCO_supported, eSCO_S4_supported, negotiated_codec);
2054 }
2055 
2056 void hfp_init_link_settings(hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported){
2057     // get highest possible link setting
2058     hfp_connection->link_setting = hfp_next_link_setting_for_connection(HFP_LINK_SETTINGS_NONE, hfp_connection, eSCO_S4_supported);
2059     log_info("hfp_init_link_settings: %u", hfp_connection->link_setting);
2060 }
2061 
2062 #define HFP_HF_RX_DEBUG_PRINT_LINE 80
2063 
2064 void hfp_log_rfcomm_message(const char * tag, uint8_t * packet, uint16_t size){
2065 #ifdef ENABLE_LOG_INFO
2066     // encode \n\r
2067     char printable[HFP_HF_RX_DEBUG_PRINT_LINE+2];
2068     int i = 0;
2069     int pos;
2070     for (pos=0 ; (pos < size) && (i < (HFP_HF_RX_DEBUG_PRINT_LINE - 3)) ; pos++){
2071         switch (packet[pos]){
2072             case '\n':
2073                 printable[i++] = '\\';
2074                 printable[i++] = 'n';
2075                 break;
2076             case '\r':
2077                 printable[i++] = '\\';
2078                 printable[i++] = 'r';
2079                 break;
2080             default:
2081                 printable[i++] = packet[pos];
2082                 break;
2083         }
2084     }
2085     printable[i] = 0;
2086     log_info("%s: '%s'", tag, printable);
2087 #endif
2088 }
2089 
2090 void hfp_register_custom_ag_command(hfp_custom_at_command_t * custom_at_command){
2091     btstack_linked_list_add(&hfp_custom_commands_ag, (btstack_linked_item_t *) custom_at_command);
2092 }
2093