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