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