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