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