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