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