xref: /btstack/src/classic/hfp.c (revision b51b065ce0616a484629b52ad685953594ba1555)
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 #ifdef ENABLE_CC256X_ASSISTED_HFP
874                     hfp_cc256x_prepare_for_sco(hfp_connection);
875 #endif
876 #ifdef ENABLE_BCM_PCM_WBS
877                     hfp_bcm_prepare_for_sco(hfp_connection);
878 #endif
879 #ifdef ENABLE_RTK_PCM_WBS
880                     hfp_connection->rtk_send_sco_config = true;
881 #endif
882                     log_info("accept sco %u\n", hfp_connection->accept_sco);
883                     break;
884                 default:
885                     break;
886             }
887             break;
888 
889         case HCI_EVENT_COMMAND_STATUS:
890             if (hci_event_command_status_get_command_opcode(packet) == hci_setup_synchronous_connection.opcode) {
891                 if (hfp_sco_establishment_active == NULL) break;
892                 status = hci_event_command_status_get_status(packet);
893                 if (status == ERROR_CODE_SUCCESS) break;
894 
895                 hfp_connection = hfp_sco_establishment_active;
896                 if (hfp_handle_failed_sco_connection(status)) break;
897 
898                 hfp_connection->accept_sco = 0;
899                 hfp_connection->establish_audio_connection = 0;
900                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
901                 hfp_sco_establishment_active = NULL;
902                 hfp_emit_sco_connection_established(hfp_connection, status,
903                                                     hfp_connection->negotiated_codec, 0, 0);
904             }
905             break;
906 
907         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
908             if (hfp_sco_establishment_active == NULL) break;
909 
910             hfp_connection = hfp_sco_establishment_active;
911 
912             status = hci_event_synchronous_connection_complete_get_status(packet);
913             if (status != ERROR_CODE_SUCCESS){
914                 if (hfp_handle_failed_sco_connection(status)) break;
915 
916                 hfp_connection->accept_sco = 0;
917                 hfp_connection->establish_audio_connection = 0;
918                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
919                 hfp_sco_establishment_active = NULL;
920                 hfp_emit_sco_connection_established(hfp_connection, status,
921                                                     hfp_connection->negotiated_codec, 0, 0);
922                 break;
923             }
924 
925             uint16_t sco_handle = hci_event_synchronous_connection_complete_get_handle(packet);
926             uint8_t  link_type = hci_event_synchronous_connection_complete_get_link_type(packet);
927             uint8_t  transmission_interval = hci_event_synchronous_connection_complete_get_transmission_interval(packet);  // measured in slots
928             uint8_t  retransmission_interval = hci_event_synchronous_connection_complete_get_retransmission_interval(packet);// measured in slots
929             uint16_t rx_packet_length = hci_event_synchronous_connection_complete_get_rx_packet_length(packet); // measured in bytes
930             uint16_t tx_packet_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet); // measured in bytes
931 
932             switch (link_type){
933                 case 0x00:
934                     log_info("SCO Connection established.");
935                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
936                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
937                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
938                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
939                     break;
940                 case 0x02:
941                     log_info("eSCO Connection established. \n");
942                     break;
943                 default:
944                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
945                     break;
946             }
947 
948             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
949                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)\n", sco_handle,
950                  bd_addr_to_str(event_addr), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length,
951                  hci_event_synchronous_connection_complete_get_air_mode(packet));
952 
953             if (hfp_connection->state == HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){
954                 log_info("SCO about to disconnect: HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN");
955                 hfp_connection->state = HFP_W2_DISCONNECT_SCO;
956                 break;
957             }
958             hfp_connection->sco_handle = sco_handle;
959             hfp_connection->accept_sco = 0;
960             hfp_connection->establish_audio_connection = 0;
961 
962             hfp_connection->state = HFP_AUDIO_CONNECTION_ESTABLISHED;
963 
964             switch (hfp_connection->vra_state){
965                 case HFP_VRA_VOICE_RECOGNITION_ACTIVATED:
966                     hfp_connection->ag_audio_connection_opened_before_vra = false;
967                     break;
968                 default:
969                     hfp_connection->ag_audio_connection_opened_before_vra = true;
970                     break;
971             }
972 
973             hfp_sco_establishment_active = NULL;
974 
975             hfp_emit_sco_connection_established(hfp_connection, status,
976                                                 hfp_connection->negotiated_codec, rx_packet_length, tx_packet_length);
977             break;
978         }
979 
980         case HCI_EVENT_DISCONNECTION_COMPLETE:
981             handle = little_endian_read_16(packet,3);
982             hfp_connection = get_hfp_connection_context_for_sco_handle(handle, local_role);
983 
984             if (!hfp_connection) break;
985 
986 #ifdef ENABLE_CC256X_ASSISTED_HFP
987             hfp_connection->cc256x_send_wbs_disassociate = true;
988 #endif
989 #ifdef ENABLE_BCM_PCM_WBS
990             hfp_connection->bcm_send_disable_wbs = true;
991 #endif
992             if (hfp_connection->sco_handle == handle){
993                 hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID;
994                 hfp_connection->release_audio_connection = 0;
995                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
996                 hfp_emit_audio_connection_released(hfp_connection, handle);
997 
998                 hfp_connection->ag_audio_connection_opened_before_vra = false;
999 
1000                 if (hfp_connection->acl_handle == HCI_CON_HANDLE_INVALID){
1001                     hfp_reset_voice_recognition(hfp_connection);
1002                     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
1003                     hfp_finalize_connection_context(hfp_connection);
1004                     break;
1005                 } else if (hfp_connection->release_slc_connection == 1){
1006                     hfp_connection->release_slc_connection = 0;
1007                     hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1008                     rfcomm_disconnect(hfp_connection->acl_handle);
1009                 }
1010             }
1011 
1012             if (hfp_connection->state == HFP_W4_SCO_DISCONNECTED_TO_SHUTDOWN){
1013                 // RFCOMM already closed -> remote power off
1014 #if defined(ENABLE_CC256X_ASSISTED_HFP) || defined (ENABLE_BCM_PCM_WBS)
1015                 hfp_connection->state = HFP_W4_WBS_SHUTDOWN;
1016 #else
1017                 hfp_finalize_connection_context(hfp_connection);
1018 #endif
1019                 break;
1020             }
1021             break;
1022 
1023         default:
1024             break;
1025     }
1026 }
1027 
1028 
1029 void hfp_handle_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
1030     UNUSED(packet_type);
1031     UNUSED(channel);    // ok: no channel
1032     UNUSED(size);
1033 
1034     bd_addr_t event_addr;
1035     uint16_t rfcomm_cid;
1036     hfp_connection_t * hfp_connection = NULL;
1037     uint8_t status;
1038 
1039     log_debug("HFP packet_handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
1040 
1041     switch (hci_event_packet_get_type(packet)) {
1042 
1043         case RFCOMM_EVENT_INCOMING_CONNECTION:
1044             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
1045             rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
1046             hfp_connection = hfp_create_connection(event_addr, local_role);
1047             if (!hfp_connection){
1048                 log_info("hfp: no memory to accept incoming connection - decline");
1049                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
1050                 return;
1051             }
1052             if (hfp_connection->state != HFP_IDLE) {
1053                 log_error("hfp: incoming connection but not idle, reject");
1054                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
1055                 return;
1056             }
1057 
1058             hfp_connection->rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
1059             hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
1060             rfcomm_accept_connection(hfp_connection->rfcomm_cid);
1061             break;
1062 
1063         case RFCOMM_EVENT_CHANNEL_OPENED:
1064             rfcomm_event_channel_opened_get_bd_addr(packet, event_addr);
1065 
1066             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
1067             btstack_assert(hfp_connection != NULL);
1068 
1069             if (hfp_connection->state != HFP_W4_RFCOMM_CONNECTED){
1070                 break;
1071             }
1072 
1073             status = rfcomm_event_channel_opened_get_status(packet);
1074             if (status != ERROR_CODE_SUCCESS) {
1075                 hfp_handle_slc_setup_error(hfp_connection, status);
1076                 break;
1077             }
1078 
1079             hfp_connection->acl_handle = rfcomm_event_channel_opened_get_con_handle(packet);
1080             hfp_connection->rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
1081             hfp_connection->rfcomm_mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
1082             bd_addr_copy(hfp_connection->remote_addr, event_addr);
1083             hfp_connection->state = HFP_EXCHANGE_SUPPORTED_FEATURES;
1084 
1085             rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1086             break;
1087 
1088         case RFCOMM_EVENT_CHANNEL_CLOSED:
1089             rfcomm_cid = little_endian_read_16(packet,2);
1090             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
1091             if (!hfp_connection) break;
1092             switch (hfp_connection->state){
1093                 case HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART:
1094                     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
1095                     hfp_connection->state = HFP_IDLE;
1096                     hfp_establish_service_level_connection(hfp_connection->remote_addr, hfp_connection->service_uuid, local_role);
1097                     break;
1098 
1099                 case HFP_AUDIO_CONNECTION_ESTABLISHED:
1100                     // service connection was released, this implicitly releases audio connection as well
1101                     hfp_connection->release_audio_connection = 0;
1102                     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
1103                     hfp_connection->state = HFP_W4_SCO_DISCONNECTED_TO_SHUTDOWN;
1104                     gap_disconnect(hfp_connection->sco_handle);
1105                     break;
1106 
1107                 default:
1108                     // regular case
1109                     hfp_reset_voice_recognition(hfp_connection);
1110                     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
1111                     hfp_finalize_connection_context(hfp_connection);
1112                     break;
1113             }
1114             break;
1115 
1116         default:
1117             break;
1118     }
1119 }
1120 // translates command string into hfp_command_t CMD
1121 
1122 typedef struct {
1123     const char * command;
1124     hfp_command_t command_id;
1125 } hfp_command_entry_t;
1126 
1127 static hfp_command_entry_t hfp_ag_command_table[] = {
1128     { "AT+BAC=",   HFP_CMD_AVAILABLE_CODECS },
1129     { "AT+BCC",    HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP },
1130     { "AT+BCS=",   HFP_CMD_HF_CONFIRMED_CODEC },
1131     { "AT+BIA=",   HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE, }, // +BIA:<enabled>,,<enabled>,,,<enabled>
1132     { "AT+BIEV=",  HFP_CMD_HF_INDICATOR_STATUS },
1133     { "AT+BIND=",  HFP_CMD_LIST_GENERIC_STATUS_INDICATORS },
1134     { "AT+BIND=?", HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS },
1135     { "AT+BIND?",  HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE },
1136     { "AT+BINP=",  HFP_CMD_HF_REQUEST_PHONE_NUMBER },
1137     { "AT+BLDN",   HFP_CMD_REDIAL_LAST_NUMBER },
1138     { "AT+BRSF=",  HFP_CMD_SUPPORTED_FEATURES },
1139     { "AT+BTRH=",  HFP_CMD_RESPONSE_AND_HOLD_COMMAND },
1140     { "AT+BTRH?",  HFP_CMD_RESPONSE_AND_HOLD_QUERY },
1141     { "AT+BVRA=",  HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION },
1142     { "AT+CCWA=",  HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION},
1143     { "AT+CHLD=",  HFP_CMD_CALL_HOLD },
1144     { "AT+CHLD=?", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
1145     { "AT+CHUP",   HFP_CMD_HANG_UP_CALL },
1146     { "AT+CIND=?", HFP_CMD_RETRIEVE_AG_INDICATORS },
1147     { "AT+CIND?",  HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS },
1148     { "AT+CLCC",   HFP_CMD_LIST_CURRENT_CALLS },
1149     { "AT+CLIP=",  HFP_CMD_ENABLE_CLIP},
1150     { "AT+CMEE=",  HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR},
1151     { "AT+CMER=",  HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE },
1152     { "AT+CNUM",   HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION },
1153     { "AT+COPS=",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT },
1154     { "AT+COPS?",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
1155     { "AT+NREC=",  HFP_CMD_TURN_OFF_EC_AND_NR, },
1156     { "AT+VGM=",   HFP_CMD_SET_MICROPHONE_GAIN },
1157     { "AT+VGS=",   HFP_CMD_SET_SPEAKER_GAIN },
1158     { "AT+VTS=",   HFP_CMD_TRANSMIT_DTMF_CODES },
1159     { "ATA",       HFP_CMD_CALL_ANSWERED },
1160 };
1161 
1162 static hfp_command_entry_t hfp_hf_command_table[] = {
1163     { "+BCS:",  HFP_CMD_AG_SUGGESTED_CODEC },
1164     { "+BIND:", HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS },
1165     { "+BINP:", HFP_CMD_AG_SENT_PHONE_NUMBER },
1166     { "+BRSF:", HFP_CMD_SUPPORTED_FEATURES },
1167     { "+BSIR:", HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING },
1168     { "+BTRH:", HFP_CMD_RESPONSE_AND_HOLD_STATUS },
1169     { "+BVRA:", HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION },
1170     { "+CCWA:", HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE, },
1171     { "+CHLD:", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
1172     { "+CIEV:", HFP_CMD_TRANSFER_AG_INDICATOR_STATUS},
1173     { "+CIND:", HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC },
1174     { "+CLCC:", HFP_CMD_LIST_CURRENT_CALLS },
1175     { "+CLIP:", HFP_CMD_AG_SENT_CLIP_INFORMATION },
1176     { "+CME ERROR:", HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR },
1177     { "+CNUM:", HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION},
1178     { "+COPS:", HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
1179     { "+VGM:",  HFP_CMD_SET_MICROPHONE_GAIN },
1180     { "+VGM=",  HFP_CMD_SET_MICROPHONE_GAIN },
1181     { "+VGS:",  HFP_CMD_SET_SPEAKER_GAIN},
1182     { "+VGS=",  HFP_CMD_SET_SPEAKER_GAIN},
1183     { "ERROR",  HFP_CMD_ERROR},
1184     { "NOP",    HFP_CMD_NONE}, // dummy command used by unit tests
1185     { "OK",     HFP_CMD_OK },
1186     { "RING",   HFP_CMD_RING },
1187 };
1188 
1189 static const hfp_custom_at_command_t *
1190 hfp_custom_command_lookup(bool isHandsFree, const char *text) {
1191     btstack_linked_list_t * custom_commands = isHandsFree ? &hfp_custom_commands_hf : &hfp_custom_commands_ag;
1192     btstack_linked_list_iterator_t it;
1193     btstack_linked_list_iterator_init(&it, custom_commands);
1194     while (btstack_linked_list_iterator_has_next(&it)) {
1195         hfp_custom_at_command_t *at_command = (hfp_custom_at_command_t *) btstack_linked_list_iterator_next(&it);
1196         int match = strcmp(text, at_command->command);
1197         if (match == 0) {
1198             return at_command;
1199         }
1200     }
1201     return NULL;
1202 }
1203 
1204 static hfp_command_t parse_command(const char * line_buffer, int isHandsFree){
1205 
1206     // check for custom commands, AG only
1207     const hfp_custom_at_command_t * custom_at_command = hfp_custom_command_lookup(isHandsFree, line_buffer);
1208     if (custom_at_command != NULL){
1209         return HFP_CMD_CUSTOM_MESSAGE;
1210     }
1211 
1212     // table lookup based on role
1213     uint16_t num_entries;
1214     hfp_command_entry_t * table;
1215     if (isHandsFree == 0){
1216         table = hfp_ag_command_table;
1217         num_entries = sizeof(hfp_ag_command_table) / sizeof(hfp_command_entry_t);
1218     } else {
1219         table = hfp_hf_command_table;
1220         num_entries = sizeof(hfp_hf_command_table) / sizeof(hfp_command_entry_t);
1221     }
1222     // binary search
1223     uint16_t left = 0;
1224     uint16_t right = num_entries - 1;
1225     while (left <= right){
1226         uint16_t middle = left + (right - left) / 2;
1227         hfp_command_entry_t *entry = &table[middle];
1228         int match = strcmp(line_buffer, entry->command);
1229         if (match < 0){
1230             // search term is lower than middle element
1231             if (right == 0) break;
1232             right = middle - 1;
1233         } else if (match == 0){
1234             return entry->command_id;
1235         } else {
1236             // search term is higher than middle element
1237             left = middle + 1;
1238         }
1239     }
1240 
1241     // note: if parser in CMD_HEADER state would treats digits and maybe '+' as separator, match on "ATD" would work.
1242     // note: phone number is currently expected in line_buffer[3..]
1243     // prefix match on 'ATD', AG only
1244     if ((isHandsFree == 0) && (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0)){
1245         return HFP_CMD_CALL_PHONE_NUMBER;
1246     }
1247 
1248     // Valid looking, but unknown commands/responses
1249     if ((isHandsFree == 0) && (strncmp(line_buffer, "AT+", 3) == 0)){
1250         return HFP_CMD_UNKNOWN;
1251     }
1252 
1253     if ((isHandsFree != 0) && (strncmp(line_buffer, "+", 1) == 0)){
1254         return HFP_CMD_UNKNOWN;
1255     }
1256 
1257     return HFP_CMD_NONE;
1258 }
1259 
1260 static void hfp_parser_store_byte(hfp_connection_t * hfp_connection, uint8_t byte){
1261     if ((hfp_connection->line_size + 1) >= HFP_MAX_VR_TEXT_SIZE) return;
1262     hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
1263     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1264 }
1265 static int hfp_parser_is_buffer_empty(hfp_connection_t * hfp_connection){
1266     return hfp_connection->line_size == 0;
1267 }
1268 
1269 static int hfp_parser_is_end_of_line(uint8_t byte){
1270     return (byte == '\n') || (byte == '\r');
1271 }
1272 
1273 void hfp_parser_reset_line_buffer(hfp_connection_t *hfp_connection) {
1274     hfp_connection->line_size = 0;
1275     // we don't set the first byte to '\0' to allow access to last argument e.g. in hfp_hf_handle_rfcommand
1276 }
1277 
1278 static void hfp_parser_store_if_token(hfp_connection_t * hfp_connection, uint8_t byte){
1279     switch (byte){
1280         case ',':
1281 		case '-':
1282         case ';':
1283         case '(':
1284         case ')':
1285         case '\n':
1286         case '\r':
1287             break;
1288         default:
1289             hfp_parser_store_byte(hfp_connection, byte);
1290             break;
1291     }
1292 }
1293 
1294 static bool hfp_parser_is_separator( uint8_t byte){
1295     switch (byte){
1296         case ',':
1297 		case '-':
1298         case ';':
1299         case '\n':
1300         case '\r':
1301             return true;
1302         default:
1303             return false;
1304     }
1305 }
1306 
1307 // returns true if received bytes was processed. Otherwise, functions will be called with same byte again
1308 // this is used to for a one byte lookahead, where an unexpected byte is pushed back by returning false
1309 static bool hfp_parse_byte(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1310 
1311 #ifdef HFP_DEBUG
1312     if (byte >= ' '){
1313         printf("Parse  '%c' - state %u, buffer %s\n", byte, hfp_connection->parser_state, hfp_connection->line_buffer);
1314     } else {
1315         printf("Parse 0x%02x - state %u, buffer %s\n", byte, hfp_connection->parser_state, hfp_connection->line_buffer);
1316     }
1317 #endif
1318 
1319     // handle doubles quotes
1320     if (byte == '"'){
1321         hfp_connection->parser_quoted = !hfp_connection->parser_quoted;
1322         return true;
1323     }
1324     if (hfp_connection->parser_quoted) {
1325         hfp_parser_store_byte(hfp_connection, byte);
1326         return true;
1327     }
1328 
1329     // ignore spaces outside command or double quotes (required e.g. for '+CME ERROR:..") command
1330     if ((byte == ' ') && (hfp_connection->parser_state != HFP_PARSER_CMD_HEADER)) return true;
1331 
1332     bool processed = true;
1333 
1334     switch (hfp_connection->parser_state) {
1335         case HFP_PARSER_CMD_HEADER:
1336             switch (byte) {
1337                 case '\n':
1338                 case '\r':
1339                 case ';':
1340                     // ignore separator
1341                     break;
1342                 case ':':
1343                 case '?':
1344                     // store separator
1345                     hfp_parser_store_byte(hfp_connection, byte);
1346                     break;
1347                 case '=':
1348                     // equal sign: remember and wait for next char to decided between '=?' and '=\?'
1349                     hfp_connection->found_equal_sign = true;
1350                     hfp_parser_store_byte(hfp_connection, byte);
1351                     return true;
1352                 default:
1353                     // store if not lookahead
1354                     if (!hfp_connection->found_equal_sign) {
1355                         hfp_parser_store_byte(hfp_connection, byte);
1356                         return true;
1357                     }
1358                     // mark as lookahead
1359                     processed = false;
1360                     break;
1361             }
1362 
1363             // ignore empty tokens
1364             if (hfp_parser_is_buffer_empty(hfp_connection)) return true;
1365 
1366             // parse
1367             hfp_connection->command = parse_command((char *)hfp_connection->line_buffer, isHandsFree);
1368 
1369             // pick +CIND version based on connection state: descriptions during SLC vs. states later
1370             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC){
1371                 switch(hfp_connection->state){
1372                     case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1373                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
1374                         break;
1375                     case HFP_W4_RETRIEVE_INDICATORS:
1376                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS;
1377                         break;
1378                     default:
1379                         hfp_connection->command = HFP_CMD_UNKNOWN;
1380                         break;
1381                 }
1382             }
1383 
1384             log_info("command string '%s', handsfree %u -> cmd id %u", (char *)hfp_connection->line_buffer, isHandsFree, hfp_connection->command);
1385 
1386             // store command id for custom command and just store rest of line
1387             if (hfp_connection->command == HFP_CMD_CUSTOM_MESSAGE){
1388                 const hfp_custom_at_command_t * at_command = hfp_custom_command_lookup(isHandsFree, (const char *) hfp_connection->line_buffer);
1389                 hfp_connection->custom_at_command_id = at_command->command_id;
1390                 hfp_connection->parser_state = HFP_PARSER_CUSTOM_COMMAND;
1391                 return processed;
1392             }
1393 
1394             // next state
1395             hfp_parser_reset_line_buffer(hfp_connection);
1396             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1397 
1398             return processed;
1399 
1400         case HFP_PARSER_CMD_SEQUENCE:
1401             // handle empty fields
1402             if ((byte == ',' ) && (hfp_connection->line_size == 0)){
1403                 hfp_connection->line_buffer[0] = 0;
1404                 hfp_connection->ignore_value = 1;
1405                 parse_sequence(hfp_connection);
1406                 return true;
1407             }
1408 
1409             hfp_parser_store_if_token(hfp_connection, byte);
1410             if (!hfp_parser_is_separator(byte)) return true;
1411 
1412             // ignore empty tokens
1413             switch (hfp_connection->command){
1414                 case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1415                     // don't ignore empty string
1416                     break;
1417                 default:
1418                     if (hfp_parser_is_buffer_empty(hfp_connection) && (hfp_connection->ignore_value == 0)) {
1419                         return true;
1420                     }
1421                     break;
1422             }
1423 
1424             parse_sequence(hfp_connection);
1425 
1426             hfp_parser_reset_line_buffer(hfp_connection);
1427 
1428             switch (hfp_connection->command){
1429                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1430                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1431                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1432                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1433                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1434                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1435                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1436                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1437                 case HFP_CMD_HF_INDICATOR_STATUS:
1438                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
1439                     break;
1440                 default:
1441                     break;
1442             }
1443             return true;
1444 
1445         case HFP_PARSER_SECOND_ITEM:
1446 
1447             hfp_parser_store_if_token(hfp_connection, byte);
1448             if (!hfp_parser_is_separator(byte)) return true;
1449 
1450             switch (hfp_connection->command){
1451                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1452                     log_info("format %s, ", hfp_connection->line_buffer);
1453                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1454                     break;
1455                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1456                     log_info("format %s \n", hfp_connection->line_buffer);
1457                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1458                     break;
1459                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1460                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1461                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1462                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1463                     break;
1464                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1465                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1466                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1467                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1468                     break;
1469                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1470                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer);
1471                     log_info("%s, ", hfp_connection->line_buffer);
1472                     break;
1473                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1474                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1475                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1476                     hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1477                     break;
1478                 case HFP_CMD_HF_INDICATOR_STATUS:
1479                     hfp_connection->parser_indicator_value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1480                     break;
1481                 default:
1482                     break;
1483             }
1484 
1485             hfp_parser_reset_line_buffer(hfp_connection);
1486 
1487             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
1488 
1489             return true;
1490 
1491         case HFP_PARSER_THIRD_ITEM:
1492 
1493             hfp_parser_store_if_token(hfp_connection, byte);
1494             if (!hfp_parser_is_separator(byte)) return true;
1495 
1496             switch (hfp_connection->command){
1497                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1498                     btstack_strcpy(hfp_connection->network_operator.name, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE,  (char *)hfp_connection->line_buffer);
1499                     break;
1500                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1501                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer);
1502                     hfp_next_indicators_index(hfp_connection);
1503                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1504                     break;
1505                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1506                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1507                     // track if last argument exists
1508                     hfp_connection->clip_have_alpha = hfp_connection->line_size != 0;
1509                     break;
1510                 default:
1511                     break;
1512             }
1513 
1514             hfp_parser_reset_line_buffer(hfp_connection);
1515 
1516             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){
1517                 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1518             }
1519             return true;
1520 
1521         case HFP_PARSER_CUSTOM_COMMAND:
1522             if (hfp_parser_is_end_of_line(byte) == false){
1523                 hfp_parser_store_byte(hfp_connection, byte);
1524             }
1525             return true;
1526 
1527         default:
1528             btstack_assert(false);
1529             return true;
1530     }
1531 }
1532 
1533 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1534     bool processed = false;
1535     while (!processed){
1536         processed = hfp_parse_byte(hfp_connection, byte, isHandsFree);
1537     }
1538     // reset parser state on end-of-line
1539     if (hfp_parser_is_end_of_line(byte)){
1540         hfp_connection->found_equal_sign = false;
1541         hfp_connection->parser_item_index = 0;
1542         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1543     }
1544 }
1545 
1546 static void parse_sequence(hfp_connection_t * hfp_connection){
1547     int value;
1548     switch (hfp_connection->command){
1549         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1550             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1551             int i;
1552             switch (hfp_connection->parser_item_index){
1553                 case 0:
1554                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1555                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1556                             hfp_connection->parser_indicator_index = i;
1557                             break;
1558                         }
1559                     }
1560                     break;
1561                 case 1:
1562                     if (hfp_connection->parser_indicator_index <0) break;
1563                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1564                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1565                      hfp_connection->parser_item_index, value);
1566                     break;
1567                 default:
1568                     break;
1569             }
1570             hfp_next_indicators_index(hfp_connection);
1571             break;
1572 
1573         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1574             switch(hfp_connection->parser_item_index){
1575                 case 0:
1576                     // <alpha>: This optional field is not supported, and shall be left blank.
1577                     break;
1578                 case 1:
1579                     // <number>: Quoted string containing the phone number in the format specified by <type>.
1580                     btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1581                     break;
1582                 case 2:
1583                     /*
1584                       <type> field specifies the format of the phone number provided, and can be one of the following values:
1585                       - 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.
1586                      - 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.
1587                      - values 160-175: National number. No prefix nor escape digits included.
1588                      */
1589                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1590                     hfp_connection->bnip_type = value;
1591                     break;
1592                 case 3:
1593                     // <speed>: This optional field is not supported, and shall be left blank.
1594                     break;
1595                 case 4:
1596                     // <service>: Indicates which service this phone number relates to. Shall be either 4 (voice) or 5 (fax).
1597                 default:
1598                     break;
1599             }
1600             // index > 2 are ignored in switch above
1601             hfp_connection->parser_item_index++;
1602             break;
1603         case HFP_CMD_LIST_CURRENT_CALLS:
1604             switch(hfp_connection->parser_item_index){
1605                 case 0:
1606                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1607                     hfp_connection->clcc_idx = value;
1608                     break;
1609                 case 1:
1610                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1611                     hfp_connection->clcc_dir = value;
1612                     break;
1613                 case 2:
1614                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1615                     hfp_connection->clcc_status = value;
1616                     break;
1617                 case 3:
1618                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1619                     hfp_connection->clcc_mode = value;
1620                     break;
1621                 case 4:
1622                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1623                     hfp_connection->clcc_mpty = value;
1624                     break;
1625                 case 5:
1626                     btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1627                     break;
1628                 case 6:
1629                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1630                     hfp_connection->bnip_type = value;
1631                     break;
1632                 default:
1633                     break;
1634             }
1635             // index > 6 are ignored in switch above
1636             hfp_connection->parser_item_index++;
1637             break;
1638         case HFP_CMD_SET_MICROPHONE_GAIN:
1639             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1640             hfp_connection->microphone_gain = value;
1641             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1642             break;
1643         case HFP_CMD_SET_SPEAKER_GAIN:
1644             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1645             hfp_connection->speaker_gain = value;
1646             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1647             break;
1648         case HFP_CMD_TURN_OFF_EC_AND_NR:
1649             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1650             hfp_connection->ag_echo_and_noise_reduction = value;
1651             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1652             break;
1653         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1654             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1655             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1656             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1657             break;
1658         case HFP_CMD_HF_CONFIRMED_CODEC:
1659             hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer);
1660             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1661             break;
1662         case HFP_CMD_AG_SUGGESTED_CODEC:
1663             hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer);
1664             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1665             break;
1666         case HFP_CMD_SUPPORTED_FEATURES:
1667             hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer);
1668             log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features);
1669             break;
1670         case HFP_CMD_AVAILABLE_CODECS:
1671             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1672             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1673             hfp_next_codec_index(hfp_connection);
1674             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1675             break;
1676         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1677             btstack_strcpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, HFP_MAX_INDICATOR_DESC_SIZE, (char *)hfp_connection->line_buffer);
1678             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1679             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1680             break;
1681         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1682             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1683             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer);
1684             hfp_next_indicators_index(hfp_connection);
1685             break;
1686         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1687             hfp_next_indicators_index(hfp_connection);
1688             if (hfp_connection->parser_item_index != 4) break;
1689             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1690             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1691             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1692             break;
1693         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1694             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1695             if (hfp_connection->line_size > 2 ) break;
1696             memcpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE-1);
1697             hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name[HFP_CALL_SERVICE_SIZE - 1] = 0;
1698             hfp_next_remote_call_services_index(hfp_connection);
1699             break;
1700         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1701         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1702             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1703             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1704             hfp_next_indicators_index(hfp_connection);
1705             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1706             break;
1707         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1708             // HF parses inital AG gen. ind. state
1709             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1710             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1711             break;
1712         case HFP_CMD_HF_INDICATOR_STATUS:
1713             hfp_connection->parser_indicator_index = hfp_parse_indicator_index(hfp_connection);
1714             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1715             break;
1716         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1717             // AG parses new gen. ind. state
1718             if (hfp_connection->ignore_value){
1719                 hfp_connection->ignore_value = 0;
1720                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1721                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1722             }
1723             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1724                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1725                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1726             } else {
1727                 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1728                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1729                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1730                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1731             }
1732             hfp_next_indicators_index(hfp_connection);
1733             break;
1734         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1735             // indicators are indexed starting with 1
1736             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1737             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1738             break;
1739         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1740             hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1741             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1742             break;
1743         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1744             if (hfp_connection->line_buffer[0] == '3'){
1745                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1746                 break;
1747             }
1748             // TODO emit ERROR, wrong format
1749             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1750             break;
1751         case HFP_CMD_ERROR:
1752             break;
1753         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1754             hfp_connection->extended_audio_gateway_error = 1;
1755             hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1756             break;
1757         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1758             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1759             hfp_connection->ok_pending = 1;
1760             hfp_connection->extended_audio_gateway_error = 0;
1761             break;
1762         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1763         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1764         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1765             btstack_strcpy((char *)hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1766             break;
1767         case HFP_CMD_CALL_HOLD:
1768             hfp_connection->ag_call_hold_action = hfp_connection->line_buffer[0] - '0';
1769             if (hfp_connection->line_buffer[1] != '\0'){
1770                 hfp_connection->call_index = btstack_atoi((char *)&hfp_connection->line_buffer[1]);
1771             }
1772             break;
1773         case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1774             hfp_connection->ag_response_and_hold_action = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1775             break;
1776         case HFP_CMD_TRANSMIT_DTMF_CODES:
1777             hfp_connection->ag_dtmf_code = hfp_connection->line_buffer[0];
1778             break;
1779         case HFP_CMD_ENABLE_CLIP:
1780             hfp_connection->clip_enabled = hfp_connection->line_buffer[0] != '0';
1781             break;
1782         case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1783             hfp_connection->call_waiting_notification_enabled = hfp_connection->line_buffer[0] != '0';
1784             break;
1785         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1786             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1787             hfp_connection->ag_activate_voice_recognition_value = value;
1788             break;
1789         case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1790             switch(hfp_connection->parser_item_index){
1791                 case 0:
1792                     hfp_connection->ag_vra_status = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1793                     break;
1794                 case 1:
1795                     hfp_connection->ag_vra_state = (hfp_voice_recognition_state_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1796                     break;
1797                 case 2:
1798                     hfp_connection->ag_msg.text_id = 0;
1799                     for (i = 0 ; i < 4; i++){
1800                         hfp_connection->ag_msg.text_id = (hfp_connection->ag_msg.text_id << 4) | nibble_for_char(hfp_connection->line_buffer[i]);
1801                     }
1802                     break;
1803                 case 3:
1804                     hfp_connection->ag_msg.text_type = (hfp_text_type_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1805                     break;
1806                 case 4:
1807                     hfp_connection->ag_msg.text_operation = (hfp_text_operation_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1808                     break;
1809                 case 5:
1810                     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1811                     hfp_connection->ag_vra_msg_length = hfp_connection->line_size + 1;
1812                     break;
1813                 default:
1814                     break;
1815             }
1816             hfp_connection->parser_item_index++;
1817             break;
1818         default:
1819             break;
1820     }
1821 }
1822 
1823 static void hfp_handle_start_sdp_client_query(void * context){
1824     UNUSED(context);
1825 
1826     btstack_linked_list_iterator_t it;
1827     btstack_linked_list_iterator_init(&it, &hfp_connections);
1828     while (btstack_linked_list_iterator_has_next(&it)){
1829         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1830 
1831         if (connection->state != HFP_W2_SEND_SDP_QUERY) continue;
1832 
1833         connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1834         hfp_sdp_query_context.local_role = connection->local_role;
1835         (void)memcpy(hfp_sdp_query_context.remote_address, connection->remote_addr, 6);
1836         sdp_client_query_rfcomm_channel_and_name_for_service_class_uuid(&handle_query_rfcomm_event, connection->remote_addr, connection->service_uuid);
1837         return;
1838     }
1839 }
1840 
1841 uint8_t hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){
1842     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr, local_role);
1843     if (connection){
1844         return ERROR_CODE_COMMAND_DISALLOWED;
1845     }
1846 
1847     connection = hfp_create_connection(bd_addr, local_role);
1848     if (!connection){
1849         return BTSTACK_MEMORY_ALLOC_FAILED;
1850     }
1851 
1852     connection->state = HFP_W2_SEND_SDP_QUERY;
1853 
1854     bd_addr_copy(connection->remote_addr, bd_addr);
1855     connection->service_uuid = service_uuid;
1856 
1857     hfp_sdp_query_request.callback = &hfp_handle_start_sdp_client_query;
1858     // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1859     (void) sdp_client_register_query_callback(&hfp_sdp_query_request);
1860     return ERROR_CODE_SUCCESS;
1861 }
1862 
1863 void hfp_trigger_release_service_level_connection(hfp_connection_t * hfp_connection){
1864     // called internally, NULL check already performed
1865     btstack_assert(hfp_connection != NULL);
1866 
1867     hfp_trigger_release_audio_connection(hfp_connection);
1868     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1869         hfp_connection->state = HFP_IDLE;
1870         return;
1871     }
1872 
1873     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1874         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1875         return;
1876     }
1877     hfp_connection->release_slc_connection = 1;
1878     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1879         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1880         return;
1881     }
1882 
1883     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1884         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1885         hfp_connection->release_audio_connection = 1;
1886         return;
1887     }
1888 }
1889 
1890 uint8_t hfp_trigger_release_audio_connection(hfp_connection_t * hfp_connection){
1891     // called internally, NULL check already performed
1892     btstack_assert(hfp_connection != NULL);
1893     if (hfp_connection->state <= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
1894         return ERROR_CODE_COMMAND_DISALLOWED;
1895     }
1896     switch (hfp_connection->state) {
1897         case HFP_W2_CONNECT_SCO:
1898             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1899             break;
1900         case HFP_W4_SCO_CONNECTED:
1901         case HFP_AUDIO_CONNECTION_ESTABLISHED:
1902             hfp_connection->release_audio_connection = 1;
1903             break;
1904         default:
1905             return ERROR_CODE_COMMAND_DISALLOWED;
1906     }
1907     return ERROR_CODE_SUCCESS;
1908 }
1909 
1910 bool hfp_sco_setup_active(void){
1911     return hfp_sco_establishment_active != NULL;
1912 }
1913 
1914 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){
1915 
1916     hfp_sco_establishment_active = hfp_connection;
1917 
1918     // all packet types, fixed bandwidth
1919     int setting = hfp_connection->link_setting;
1920     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1921     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1922     if (hfp_connection->negotiated_codec != HFP_CODEC_CVSD){
1923 #ifdef ENABLE_BCM_PCM_WBS
1924         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
1925 #else
1926         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
1927 #endif
1928     }
1929     uint16_t packet_types = hfp_link_settings[setting].packet_types;
1930     hfp_connection->packet_types = packet_types;
1931 
1932     // get packet types - bits 6-9 are 'don't allow'
1933     uint16_t packet_types_flipped = packet_types ^ 0x03c0;
1934     hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency,
1935         sco_voice_setting, hfp_link_settings[setting].retransmission_effort, packet_types_flipped);
1936 }
1937 
1938 void hfp_accept_synchronous_connection(hfp_connection_t * hfp_connection, bool use_eSCO){
1939 
1940     hfp_sco_establishment_active = hfp_connection;
1941 
1942     // use "don't care" where possible
1943     uint16_t max_latency           = 0xffff;
1944     uint16_t retransmission_effort = 0xff;
1945 
1946     // transparent data for non-CVSD connections or if codec provided by Controller
1947     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1948     if (hfp_connection->negotiated_codec != HFP_CODEC_CVSD){
1949 #ifdef ENABLE_BCM_PCM_WBS
1950         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
1951 #else
1952         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
1953 #endif
1954     }
1955 
1956     // filter packet types
1957     uint16_t packet_types = hfp_get_sco_packet_types();
1958     hfp_connection->packet_types = packet_types;
1959 
1960     // bits 6-9 are 'don't allow'
1961     uint16_t packet_types_flipped = packet_types ^ 0x3c0;
1962 
1963     log_info("HFP: sending hci_accept_connection_request, packet types 0x%04x, sco_voice_setting 0x%02x", packet_types, sco_voice_setting);
1964     hci_send_cmd(&hci_accept_synchronous_connection, hfp_connection->remote_addr, 8000, 8000, max_latency,
1965                  sco_voice_setting, retransmission_effort, packet_types_flipped);
1966 }
1967 
1968 #ifdef ENABLE_CC256X_ASSISTED_HFP
1969 void hfp_cc256x_prepare_for_sco(hfp_connection_t * hfp_connection){
1970     hfp_connection->cc256x_send_write_codec_config = true;
1971     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1972         hfp_connection->cc256x_send_wbs_associate = true;
1973     }
1974 }
1975 
1976 void hfp_cc256x_write_codec_config(hfp_connection_t * hfp_connection){
1977     uint32_t sample_rate_hz;
1978     uint16_t clock_rate_khz;
1979     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1980         clock_rate_khz = 512;
1981         sample_rate_hz = 16000;
1982     } else {
1983         clock_rate_khz = 256;
1984         sample_rate_hz = 8000;
1985     }
1986     uint8_t clock_direction = 0;        // master
1987     uint16_t frame_sync_duty_cycle = 0; // i2s with 50%
1988     uint8_t  frame_sync_edge = 1;       // rising edge
1989     uint8_t  frame_sync_polarity = 0;   // active high
1990     uint8_t  reserved = 0;
1991     uint16_t size = 16;
1992     uint16_t chan_1_offset = 1;
1993     uint16_t chan_2_offset = chan_1_offset + size;
1994     uint8_t  out_edge = 1;              // rising
1995     uint8_t  in_edge = 0;               // falling
1996     hci_send_cmd(&hci_ti_write_codec_config, clock_rate_khz, clock_direction, sample_rate_hz, frame_sync_duty_cycle,
1997                  frame_sync_edge, frame_sync_polarity, reserved,
1998                  size, chan_1_offset, out_edge, size, chan_1_offset, in_edge, reserved,
1999                  size, chan_2_offset, out_edge, size, chan_2_offset, in_edge, reserved);
2000 }
2001 #endif
2002 
2003 #ifdef ENABLE_BCM_PCM_WBS
2004 void hfp_bcm_prepare_for_sco(hfp_connection_t * hfp_connection){
2005     hfp_connection->bcm_send_write_i2spcm_interface_param = true;
2006     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
2007         hfp_connection->bcm_send_enable_wbs = true;
2008     }
2009 }
2010 void hfp_bcm_write_i2spcm_interface_param(hfp_connection_t * hfp_connection){
2011     uint8_t sample_rate = (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? 1 : 0;
2012     // i2s enable, master, 8/16 kHz, 512 kHz
2013     hci_send_cmd(&hci_bcm_write_i2spcm_interface_paramhci_bcm_write_i2spcm_interface_param, 1, 1, sample_rate, 2);
2014 }
2015 #endif
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