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