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