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