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