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