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