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