xref: /btstack/src/classic/hfp.c (revision ce6f85e79d1d141c1b45dfa16b2671762457cbb4)
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     if (!hfp_connection) {
635         return NULL;
636     }
637     (void)memcpy(hfp_connection->remote_addr, bd_addr, 6);
638     hfp_connection->local_role = local_role;
639     log_info("Create HFP context %p: role %u, addr %s", hfp_connection, local_role, bd_addr_to_str(bd_addr));
640 
641     return hfp_connection;
642 }
643 
644 /* @param network.
645  * 0 == no ability to reject a call.
646  * 1 == ability to reject a call.
647  */
648 
649 /* @param suported_features
650  * HF bit 0: EC and/or NR function (yes/no, 1 = yes, 0 = no)
651  * HF bit 1: Call waiting or three-way calling(yes/no, 1 = yes, 0 = no)
652  * HF bit 2: CLI presentation capability (yes/no, 1 = yes, 0 = no)
653  * HF bit 3: Voice recognition activation (yes/no, 1= yes, 0 = no)
654  * HF bit 4: Remote volume control (yes/no, 1 = yes, 0 = no)
655  * HF bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
656  */
657  /* Bit position:
658  * AG bit 0: Three-way calling (yes/no, 1 = yes, 0 = no)
659  * AG bit 1: EC and/or NR function (yes/no, 1 = yes, 0 = no)
660  * AG bit 2: Voice recognition function (yes/no, 1 = yes, 0 = no)
661  * AG bit 3: In-band ring tone capability (yes/no, 1 = yes, 0 = no)
662  * AG bit 4: Attach a phone number to a voice tag (yes/no, 1 = yes, 0 = no)
663  * AG bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
664  */
665 
666 void hfp_create_sdp_record(uint8_t * service, uint32_t service_record_handle, uint16_t service_uuid, int rfcomm_channel_nr, const char * name){
667     uint8_t* attribute;
668     de_create_sequence(service);
669 
670     // 0x0000 "Service Record Handle"
671     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
672     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
673 
674     // 0x0001 "Service Class ID List"
675     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
676     attribute = de_push_sequence(service);
677     {
678         //  "UUID for Service"
679         de_add_number(attribute, DE_UUID, DE_SIZE_16, service_uuid);
680         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_GENERIC_AUDIO);
681     }
682     de_pop_sequence(service, attribute);
683 
684     // 0x0004 "Protocol Descriptor List"
685     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
686     attribute = de_push_sequence(service);
687     {
688         uint8_t* l2cpProtocol = de_push_sequence(attribute);
689         {
690             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
691         }
692         de_pop_sequence(attribute, l2cpProtocol);
693 
694         uint8_t* rfcomm = de_push_sequence(attribute);
695         {
696             de_add_number(rfcomm,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_RFCOMM);  // rfcomm_service
697             de_add_number(rfcomm,  DE_UINT, DE_SIZE_8,  rfcomm_channel_nr);  // rfcomm channel
698         }
699         de_pop_sequence(attribute, rfcomm);
700     }
701     de_pop_sequence(service, attribute);
702 
703 
704     // 0x0005 "Public Browse Group"
705     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
706     attribute = de_push_sequence(service);
707     {
708         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
709     }
710     de_pop_sequence(service, attribute);
711 
712     // 0x0009 "Bluetooth Profile Descriptor List"
713     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
714     attribute = de_push_sequence(service);
715     {
716         uint8_t *sppProfile = de_push_sequence(attribute);
717         {
718             de_add_number(sppProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HANDSFREE);
719             de_add_number(sppProfile,  DE_UINT, DE_SIZE_16, 0x0108); // Verision 1.8
720         }
721         de_pop_sequence(attribute, sppProfile);
722     }
723     de_pop_sequence(service, attribute);
724 
725     // 0x0100 "Service Name"
726     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
727     de_add_data(service,  DE_STRING, (uint16_t) strlen(name), (uint8_t *) name);
728 }
729 
730 static void hfp_handle_slc_setup_error(hfp_connection_t * hfp_connection, uint8_t status){
731     // cache fields for event
732     hfp_role_t local_role = hfp_connection->local_role;
733     bd_addr_t remote_addr;
734     (void)memcpy(remote_addr, hfp_connection->remote_addr, 6);
735     // finalize connection struct
736     hfp_finalize_connection_context(hfp_connection);
737     // emit event
738     hfp_emit_slc_connection_event(local_role, status, HCI_CON_HANDLE_INVALID, remote_addr);
739 }
740 
741 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
742     UNUSED(packet_type);    // ok: handling own sdp events
743     UNUSED(channel);        // ok: no channel
744     UNUSED(size);           // ok: handling own sdp events
745 
746     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(hfp_sdp_query_context.remote_address, hfp_sdp_query_context.local_role);
747     if (hfp_connection == NULL) {
748         log_info("connection with %s and local role %d not found", hfp_sdp_query_context.remote_address, hfp_sdp_query_context.local_role);
749         return;
750     }
751 
752     switch (hci_event_packet_get_type(packet)){
753         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
754             hfp_connection->rfcomm_channel_nr = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
755             break;
756         case SDP_EVENT_QUERY_COMPLETE:
757             if (hfp_connection->rfcomm_channel_nr > 0){
758                 hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
759                 btstack_packet_handler_t packet_handler;
760                 switch (hfp_connection->local_role){
761                     case HFP_ROLE_AG:
762                         packet_handler = hfp_ag_rfcomm_packet_handler;
763                         break;
764                     case HFP_ROLE_HF:
765                         packet_handler = hfp_hf_rfcomm_packet_handler;
766                         break;
767                     default:
768                         btstack_assert(false);
769                         return;
770                 }
771 
772                 rfcomm_create_channel(packet_handler, hfp_connection->remote_addr, hfp_connection->rfcomm_channel_nr, NULL);
773 
774             } else {
775                 uint8_t status = sdp_event_query_complete_get_status(packet);
776                 if (status == ERROR_CODE_SUCCESS){
777                     // report service not found
778                     status = SDP_SERVICE_NOT_FOUND;
779                 }
780                 hfp_handle_slc_setup_error(hfp_connection, status);
781                 log_info("rfcomm service not found, status 0x%02x", status);
782             }
783 
784             // register the SDP Query request to check if there is another connection waiting for the query
785             // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
786             (void) sdp_client_register_query_callback(&hfp_sdp_query_request);
787             break;
788         default:
789             break;
790     }
791 }
792 
793 // returns 0 if unexpected error or no other link options remained, otherwise 1
794 static int hfp_handle_failed_sco_connection(uint8_t status){
795 
796     if (!hfp_sco_establishment_active){
797         log_info("(e)SCO Connection failed but not started by us");
798         return 0;
799     }
800 
801     log_info("(e)SCO Connection failed 0x%02x", status);
802     switch (status){
803         case ERROR_CODE_SCO_AIR_MODE_REJECTED:
804         case ERROR_CODE_SCO_INTERVAL_REJECTED:
805         case ERROR_CODE_SCO_OFFSET_REJECTED:
806         case ERROR_CODE_UNSPECIFIED_ERROR:
807         case ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE:
808         case ERROR_CODE_UNSUPPORTED_REMOTE_FEATURE_UNSUPPORTED_LMP_FEATURE:
809             break;
810         default:
811             return 0;
812     }
813 
814     // note: eSCO_S4 supported flag not available, but it's only relevant for highest CVSD link setting (and the current failed)
815     hfp_link_settings_t next_setting = hfp_next_link_setting_for_connection(hfp_sco_establishment_active->link_setting, hfp_sco_establishment_active, false);
816 
817     // handle no valid setting found
818     if (next_setting == HFP_LINK_SETTINGS_NONE) {
819         if (hfp_sco_establishment_active->negotiated_codec == HFP_CODEC_MSBC){
820             log_info("T2/T1 failed, fallback to CVSD - D1");
821             hfp_sco_establishment_active->negotiated_codec = HFP_CODEC_CVSD;
822             hfp_sco_establishment_active->sco_for_msbc_failed = 1;
823             hfp_sco_establishment_active->ag_send_common_codec = true;
824             hfp_sco_establishment_active->link_setting = HFP_LINK_SETTINGS_D1;
825         } else {
826             // no other options
827             return 0;
828         }
829     }
830 
831     log_info("e)SCO Connection: try new link_setting %d", next_setting);
832     hfp_sco_establishment_active->establish_audio_connection = 1;
833     hfp_sco_establishment_active->link_setting = next_setting;
834     hfp_sco_establishment_active = NULL;
835     return 1;
836 }
837 
838 void hfp_handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
839     UNUSED(packet_type);
840     UNUSED(channel);    // ok: no channel
841     UNUSED(size);
842 
843     bd_addr_t event_addr;
844     hci_con_handle_t handle;
845     hfp_connection_t * hfp_connection = NULL;
846     uint8_t status;
847 
848     log_debug("HFP HCI event handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
849 
850     switch (hci_event_packet_get_type(packet)) {
851 
852         case HCI_EVENT_CONNECTION_REQUEST:
853             switch(hci_event_connection_request_get_link_type(packet)){
854                 case 0: //  SCO
855                 case 2: // eSCO
856                     hci_event_connection_request_get_bd_addr(packet, event_addr);
857                     hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
858                     if (!hfp_connection) break;
859                     if (hci_event_connection_request_get_link_type(packet) == 2){
860                         hfp_connection->accept_sco = 2;
861                     } else {
862                         hfp_connection->accept_sco = 1;
863                     }
864 #ifdef ENABLE_CC256X_ASSISTED_HFP
865                     hfp_cc256x_prepare_for_sco(hfp_connection);
866 #endif
867 #ifdef ENABLE_BCM_PCM_WBS
868                     hfp_bcm_prepare_for_sco(hfp_connection);
869 #endif
870 #ifdef ENABLE_RTK_PCM_WBS
871                     hfp_connection->rtk_send_sco_config = true;
872 #endif
873                     log_info("accept sco %u\n", hfp_connection->accept_sco);
874                     hfp_sco_establishment_active = hfp_connection;
875                     break;
876                 default:
877                     break;
878             }
879             break;
880 
881         case HCI_EVENT_COMMAND_STATUS:
882             if (hci_event_command_status_get_command_opcode(packet) == hci_setup_synchronous_connection.opcode) {
883                 if (hfp_sco_establishment_active == NULL) break;
884                 status = hci_event_command_status_get_status(packet);
885                 if (status == ERROR_CODE_SUCCESS) break;
886 
887                 hfp_connection = hfp_sco_establishment_active;
888                 if (hfp_handle_failed_sco_connection(status)) break;
889                 hfp_connection->establish_audio_connection = 0;
890                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
891                 hfp_emit_sco_connection_established(hfp_connection, status,
892                                                     hfp_connection->negotiated_codec, 0, 0);
893             }
894             break;
895 
896         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
897             if (hfp_sco_establishment_active == NULL) break;
898             hci_event_synchronous_connection_complete_get_bd_addr(packet, event_addr);
899             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
900             if (!hfp_connection) {
901                 log_error("HFP: connection does not exist for remote with addr %s.", bd_addr_to_str(event_addr));
902                 return;
903             }
904 
905             status = hci_event_synchronous_connection_complete_get_status(packet);
906             if (status != ERROR_CODE_SUCCESS){
907                 hfp_connection->accept_sco = 0;
908                 if (hfp_handle_failed_sco_connection(status)) break;
909 
910                 hfp_connection->establish_audio_connection = 0;
911                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
912                 hfp_emit_sco_connection_established(hfp_connection, status,
913                                                     hfp_connection->negotiated_codec, 0, 0);
914                 break;
915             }
916 
917             uint16_t sco_handle = hci_event_synchronous_connection_complete_get_handle(packet);
918             uint8_t  link_type = hci_event_synchronous_connection_complete_get_link_type(packet);
919             uint8_t  transmission_interval = hci_event_synchronous_connection_complete_get_transmission_interval(packet);  // measured in slots
920             uint8_t  retransmission_interval = hci_event_synchronous_connection_complete_get_retransmission_interval(packet);// measured in slots
921             uint16_t rx_packet_length = hci_event_synchronous_connection_complete_get_rx_packet_length(packet); // measured in bytes
922             uint16_t tx_packet_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet); // measured in bytes
923 
924             switch (link_type){
925                 case 0x00:
926                     log_info("SCO Connection established.");
927                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
928                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
929                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
930                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
931                     break;
932                 case 0x02:
933                     log_info("eSCO Connection established. \n");
934                     break;
935                 default:
936                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
937                     break;
938             }
939 
940             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
941                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)\n", sco_handle,
942                  bd_addr_to_str(event_addr), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length,
943                  hci_event_synchronous_connection_complete_get_air_mode(packet));
944 
945             if (hfp_connection->state == HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){
946                 log_info("SCO about to disconnect: HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN");
947                 hfp_connection->state = HFP_W2_DISCONNECT_SCO;
948                 break;
949             }
950             hfp_connection->sco_handle = sco_handle;
951             hfp_connection->establish_audio_connection = 0;
952 
953             hfp_connection->state = HFP_AUDIO_CONNECTION_ESTABLISHED;
954 
955             switch (hfp_connection->vra_state){
956                 case HFP_VRA_VOICE_RECOGNITION_ACTIVATED:
957                     hfp_connection->ag_audio_connection_opened_before_vra = false;
958                     break;
959                 default:
960                     hfp_connection->ag_audio_connection_opened_before_vra = true;
961                     break;
962             }
963             hfp_emit_sco_connection_established(hfp_connection, status,
964                                                 hfp_connection->negotiated_codec, rx_packet_length, tx_packet_length);
965             break;
966         }
967 
968         case HCI_EVENT_DISCONNECTION_COMPLETE:
969             handle = little_endian_read_16(packet,3);
970             hfp_connection = get_hfp_connection_context_for_sco_handle(handle, local_role);
971 
972             if (!hfp_connection) break;
973 
974 #ifdef ENABLE_CC256X_ASSISTED_HFP
975             hfp_connection->cc256x_send_wbs_disassociate = true;
976 #endif
977 #ifdef ENABLE_BCM_PCM_WBS
978             hfp_connection->bcm_send_disable_wbs = true;
979 #endif
980             if (hfp_connection->sco_handle == handle){
981                 hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID;
982                 hfp_connection->release_audio_connection = 0;
983                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
984                 hfp_emit_audio_connection_released(hfp_connection, handle);
985 
986                 hfp_connection->ag_audio_connection_opened_before_vra = false;
987 
988                 if (hfp_connection->acl_handle == HCI_CON_HANDLE_INVALID){
989                     hfp_reset_voice_recognition(hfp_connection);
990                     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
991                     hfp_finalize_connection_context(hfp_connection);
992                     break;
993                 } else if (hfp_connection->release_slc_connection == 1){
994                     hfp_connection->release_slc_connection = 0;
995                     hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
996                     rfcomm_disconnect(hfp_connection->acl_handle);
997                 }
998             }
999 
1000             if (hfp_connection->state == HFP_W4_SCO_DISCONNECTED_TO_SHUTDOWN){
1001                 // RFCOMM already closed -> remote power off
1002 #if defined(ENABLE_CC256X_ASSISTED_HFP) || defined (ENABLE_BCM_PCM_WBS)
1003                 hfp_connection->state = HFP_W4_WBS_SHUTDOWN;
1004 #else
1005                 hfp_finalize_connection_context(hfp_connection);
1006 #endif
1007                 break;
1008             }
1009             break;
1010 
1011         default:
1012             break;
1013     }
1014 }
1015 
1016 
1017 void hfp_handle_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
1018     UNUSED(packet_type);
1019     UNUSED(channel);    // ok: no channel
1020     UNUSED(size);
1021 
1022     bd_addr_t event_addr;
1023     uint16_t rfcomm_cid;
1024     hfp_connection_t * hfp_connection = NULL;
1025     uint8_t status;
1026 
1027     log_debug("HFP packet_handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
1028 
1029     switch (hci_event_packet_get_type(packet)) {
1030 
1031         case RFCOMM_EVENT_INCOMING_CONNECTION:
1032             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
1033             rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
1034             hfp_connection = hfp_create_connection(event_addr, local_role);
1035             if (!hfp_connection){
1036                 log_info("hfp: no memory to accept incoming connection - decline");
1037                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
1038                 return;
1039             }
1040             if (hfp_connection->state != HFP_IDLE) {
1041                 log_error("hfp: incoming connection but not idle, reject");
1042                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
1043                 return;
1044             }
1045 
1046             hfp_connection->rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
1047             hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
1048             rfcomm_accept_connection(hfp_connection->rfcomm_cid);
1049             break;
1050 
1051         case RFCOMM_EVENT_CHANNEL_OPENED:
1052             rfcomm_event_channel_opened_get_bd_addr(packet, event_addr);
1053 
1054             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
1055             btstack_assert(hfp_connection != NULL);
1056 
1057             if (hfp_connection->state != HFP_W4_RFCOMM_CONNECTED){
1058                 break;
1059             }
1060 
1061             status = rfcomm_event_channel_opened_get_status(packet);
1062             if (status != ERROR_CODE_SUCCESS) {
1063                 hfp_handle_slc_setup_error(hfp_connection, status);
1064                 break;
1065             }
1066 
1067             hfp_connection->acl_handle = rfcomm_event_channel_opened_get_con_handle(packet);
1068             hfp_connection->rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
1069             hfp_connection->rfcomm_mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
1070             bd_addr_copy(hfp_connection->remote_addr, event_addr);
1071             hfp_connection->state = HFP_EXCHANGE_SUPPORTED_FEATURES;
1072 
1073             rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1074             break;
1075 
1076         case RFCOMM_EVENT_CHANNEL_CLOSED:
1077             rfcomm_cid = little_endian_read_16(packet,2);
1078             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
1079             if (!hfp_connection) break;
1080             switch (hfp_connection->state){
1081                 case HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART:
1082                     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
1083                     hfp_connection->state = HFP_IDLE;
1084                     hfp_establish_service_level_connection(hfp_connection->remote_addr, hfp_connection->service_uuid, local_role);
1085                     break;
1086 
1087                 case HFP_AUDIO_CONNECTION_ESTABLISHED:
1088                     // service connection was released, this implicitly releases audio connection as well
1089                     hfp_connection->release_audio_connection = 0;
1090                     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
1091                     hfp_connection->state = HFP_W4_SCO_DISCONNECTED_TO_SHUTDOWN;
1092                     gap_disconnect(hfp_connection->sco_handle);
1093                     break;
1094 
1095                 default:
1096                     // regular case
1097                     hfp_reset_voice_recognition(hfp_connection);
1098                     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
1099                     hfp_finalize_connection_context(hfp_connection);
1100                     break;
1101             }
1102             break;
1103 
1104         default:
1105             break;
1106     }
1107 }
1108 // translates command string into hfp_command_t CMD
1109 
1110 typedef struct {
1111     const char * command;
1112     hfp_command_t command_id;
1113 } hfp_command_entry_t;
1114 
1115 static hfp_command_entry_t hfp_ag_commmand_table[] = {
1116     { "AT+BAC=",   HFP_CMD_AVAILABLE_CODECS },
1117     { "AT+BCC",    HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP },
1118     { "AT+BCS=",   HFP_CMD_HF_CONFIRMED_CODEC },
1119     { "AT+BIA=",   HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE, }, // +BIA:<enabled>,,<enabled>,,,<enabled>
1120     { "AT+BIEV=",  HFP_CMD_HF_INDICATOR_STATUS },
1121     { "AT+BIND=",  HFP_CMD_LIST_GENERIC_STATUS_INDICATORS },
1122     { "AT+BIND=?", HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS },
1123     { "AT+BIND?",  HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE },
1124     { "AT+BINP=",  HFP_CMD_HF_REQUEST_PHONE_NUMBER },
1125     { "AT+BLDN",   HFP_CMD_REDIAL_LAST_NUMBER },
1126     { "AT+BRSF=",  HFP_CMD_SUPPORTED_FEATURES },
1127     { "AT+BTRH=",  HFP_CMD_RESPONSE_AND_HOLD_COMMAND },
1128     { "AT+BTRH?",  HFP_CMD_RESPONSE_AND_HOLD_QUERY },
1129     { "AT+BVRA=",  HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION },
1130     { "AT+CCWA=",  HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION},
1131     { "AT+CHLD=",  HFP_CMD_CALL_HOLD },
1132     { "AT+CHLD=?", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
1133     { "AT+CHUP",   HFP_CMD_HANG_UP_CALL },
1134     { "AT+CIND=?", HFP_CMD_RETRIEVE_AG_INDICATORS },
1135     { "AT+CIND?",  HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS },
1136     { "AT+CLCC",   HFP_CMD_LIST_CURRENT_CALLS },
1137     { "AT+CLIP=",  HFP_CMD_ENABLE_CLIP},
1138     { "AT+CMEE=",  HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR},
1139     { "AT+CMER=",  HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE },
1140     { "AT+CNUM",   HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION },
1141     { "AT+COPS=",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT },
1142     { "AT+COPS?",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
1143     { "AT+NREC=",  HFP_CMD_TURN_OFF_EC_AND_NR, },
1144     { "AT+VGM=",   HFP_CMD_SET_MICROPHONE_GAIN },
1145     { "AT+VGS=",   HFP_CMD_SET_SPEAKER_GAIN },
1146     { "AT+VTS=",   HFP_CMD_TRANSMIT_DTMF_CODES },
1147     { "ATA",       HFP_CMD_CALL_ANSWERED },
1148 };
1149 
1150 static hfp_command_entry_t hfp_hf_commmand_table[] = {
1151     { "+BCS:",  HFP_CMD_AG_SUGGESTED_CODEC },
1152     { "+BIND:", HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS },
1153     { "+BINP:", HFP_CMD_AG_SENT_PHONE_NUMBER },
1154     { "+BRSF:", HFP_CMD_SUPPORTED_FEATURES },
1155     { "+BSIR:", HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING },
1156     { "+BTRH:", HFP_CMD_RESPONSE_AND_HOLD_STATUS },
1157     { "+BVRA:", HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION },
1158     { "+CCWA:", HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE, },
1159     { "+CHLD:", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
1160     { "+CIEV:", HFP_CMD_TRANSFER_AG_INDICATOR_STATUS},
1161     { "+CIND:", HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC },
1162     { "+CLCC:", HFP_CMD_LIST_CURRENT_CALLS },
1163     { "+CLIP:", HFP_CMD_AG_SENT_CLIP_INFORMATION },
1164     { "+CME ERROR:", HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR },
1165     { "+CNUM:", HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION},
1166     { "+COPS:", HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
1167     { "+VGM:",  HFP_CMD_SET_MICROPHONE_GAIN },
1168     { "+VGM=",  HFP_CMD_SET_MICROPHONE_GAIN },
1169     { "+VGS:",  HFP_CMD_SET_SPEAKER_GAIN},
1170     { "+VGS=",  HFP_CMD_SET_SPEAKER_GAIN},
1171     { "ERROR",  HFP_CMD_ERROR},
1172     { "NOP",    HFP_CMD_NONE}, // dummy command used by unit tests
1173     { "OK",     HFP_CMD_OK },
1174     { "RING",   HFP_CMD_RING },
1175 };
1176 
1177 static const hfp_custom_at_command_t * hfp_custom_command_lookup(const char * text){
1178     btstack_linked_list_iterator_t it;
1179     btstack_linked_list_iterator_init(&it, &hfp_custom_commands_ag);
1180     while (btstack_linked_list_iterator_has_next(&it)) {
1181         hfp_custom_at_command_t *at_command = (hfp_custom_at_command_t *) btstack_linked_list_iterator_next(&it);
1182         int match = strcmp(text, at_command->command);
1183         if (match == 0) {
1184             return at_command;
1185         }
1186     }
1187     return NULL;
1188 }
1189 
1190 static hfp_command_t parse_command(const char * line_buffer, int isHandsFree){
1191 
1192     // check for custom commands, AG only
1193     if (isHandsFree == 0) {
1194         const hfp_custom_at_command_t * custom_at_command = hfp_custom_command_lookup(line_buffer);
1195         if (custom_at_command != NULL){
1196             return HFP_CMD_CUSTOM_MESSAGE;
1197         }
1198     }
1199 
1200     // table lookup based on role
1201     uint16_t num_entries;
1202     hfp_command_entry_t * table;
1203     if (isHandsFree == 0){
1204         table = hfp_ag_commmand_table;
1205         num_entries = sizeof(hfp_ag_commmand_table) / sizeof(hfp_command_entry_t);
1206     } else {
1207         table = hfp_hf_commmand_table;
1208         num_entries = sizeof(hfp_hf_commmand_table) / sizeof(hfp_command_entry_t);
1209     }
1210     // binary search
1211     uint16_t left = 0;
1212     uint16_t right = num_entries - 1;
1213     while (left <= right){
1214         uint16_t middle = left + (right - left) / 2;
1215         hfp_command_entry_t *entry = &table[middle];
1216         int match = strcmp(line_buffer, entry->command);
1217         if (match < 0){
1218             // search term is lower than middle element
1219             if (right == 0) break;
1220             right = middle - 1;
1221         } else if (match == 0){
1222             return entry->command_id;
1223         } else {
1224             // search term is higher than middle element
1225             left = middle + 1;
1226         }
1227     }
1228 
1229     // note: if parser in CMD_HEADER state would treats digits and maybe '+' as separator, match on "ATD" would work.
1230     // note: phone number is currently expected in line_buffer[3..]
1231     // prefix match on 'ATD', AG only
1232     if ((isHandsFree == 0) && (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0)){
1233         return HFP_CMD_CALL_PHONE_NUMBER;
1234     }
1235 
1236     // Valid looking, but unknown commands/responses
1237     if ((isHandsFree == 0) && (strncmp(line_buffer, "AT+", 3) == 0)){
1238         return HFP_CMD_UNKNOWN;
1239     }
1240 
1241     if ((isHandsFree != 0) && (strncmp(line_buffer, "+", 1) == 0)){
1242         return HFP_CMD_UNKNOWN;
1243     }
1244 
1245     return HFP_CMD_NONE;
1246 }
1247 
1248 static void hfp_parser_store_byte(hfp_connection_t * hfp_connection, uint8_t byte){
1249     if ((hfp_connection->line_size + 1) >= HFP_MAX_VR_TEXT_SIZE) return;
1250     hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
1251     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1252 }
1253 static int hfp_parser_is_buffer_empty(hfp_connection_t * hfp_connection){
1254     return hfp_connection->line_size == 0;
1255 }
1256 
1257 static int hfp_parser_is_end_of_line(uint8_t byte){
1258     return (byte == '\n') || (byte == '\r');
1259 }
1260 
1261 void hfp_parser_reset_line_buffer(hfp_connection_t *hfp_connection) {
1262     hfp_connection->line_size = 0;
1263     // we don't set the first byte to '\0' to allow access to last argument e.g. in hfp_hf_handle_rfcommand
1264 }
1265 
1266 static void hfp_parser_store_if_token(hfp_connection_t * hfp_connection, uint8_t byte){
1267     switch (byte){
1268         case ',':
1269 		case '-':
1270         case ';':
1271         case '(':
1272         case ')':
1273         case '\n':
1274         case '\r':
1275             break;
1276         default:
1277             hfp_parser_store_byte(hfp_connection, byte);
1278             break;
1279     }
1280 }
1281 
1282 static bool hfp_parser_is_separator( uint8_t byte){
1283     switch (byte){
1284         case ',':
1285 		case '-':
1286         case ';':
1287         case '\n':
1288         case '\r':
1289             return true;
1290         default:
1291             return false;
1292     }
1293 }
1294 
1295 static bool hfp_parse_byte(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1296 
1297     // handle doubles quotes
1298     if (byte == '"'){
1299         hfp_connection->parser_quoted = !hfp_connection->parser_quoted;
1300         return true;
1301     }
1302     if (hfp_connection->parser_quoted) {
1303         hfp_parser_store_byte(hfp_connection, byte);
1304         return true;
1305     }
1306 
1307     // ignore spaces outside command or double quotes (required e.g. for '+CME ERROR:..") command
1308     if ((byte == ' ') && (hfp_connection->parser_state != HFP_PARSER_CMD_HEADER)) return true;
1309 
1310     bool processed = true;
1311 
1312     switch (hfp_connection->parser_state) {
1313         case HFP_PARSER_CMD_HEADER:
1314             switch (byte) {
1315                 case '\n':
1316                 case '\r':
1317                 case ';':
1318                     // ignore separator
1319                     break;
1320                 case ':':
1321                 case '?':
1322                     // store separator
1323                     hfp_parser_store_byte(hfp_connection, byte);
1324                     break;
1325                 case '=':
1326                     // equal sign: remember and wait for next char to decided between '=?' and '=\?'
1327                     hfp_connection->found_equal_sign = true;
1328                     hfp_parser_store_byte(hfp_connection, byte);
1329                     return true;
1330                 default:
1331                     // store if not lookahead
1332                     if (!hfp_connection->found_equal_sign) {
1333                         hfp_parser_store_byte(hfp_connection, byte);
1334                         return true;
1335                     }
1336                     // mark as lookahead
1337                     processed = false;
1338                     break;
1339             }
1340 
1341             // ignore empty tokens
1342             if (hfp_parser_is_buffer_empty(hfp_connection)) return true;
1343 
1344             // parse
1345             hfp_connection->command = parse_command((char *)hfp_connection->line_buffer, isHandsFree);
1346 
1347             // pick +CIND version based on connection state: descriptions during SLC vs. states later
1348             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC){
1349                 switch(hfp_connection->state){
1350                     case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1351                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
1352                         break;
1353                     case HFP_W4_RETRIEVE_INDICATORS:
1354                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS;
1355                         break;
1356                     default:
1357                         hfp_connection->command = HFP_CMD_UNKNOWN;
1358                         break;
1359                 }
1360             }
1361 
1362             log_info("command string '%s', handsfree %u -> cmd id %u", (char *)hfp_connection->line_buffer, isHandsFree, hfp_connection->command);
1363 
1364             // store command id for custom command and just store rest of line
1365             if (hfp_connection->command == HFP_CMD_CUSTOM_MESSAGE){
1366                 const hfp_custom_at_command_t * at_command = hfp_custom_command_lookup((const char *)hfp_connection->line_buffer);
1367                 hfp_connection->ag_custom_at_command_id = at_command->command_id;
1368                 hfp_connection->parser_state = HFP_PARSER_CUSTOM_COMMAND;
1369                 return true;
1370             }
1371 
1372             // next state
1373             hfp_parser_reset_line_buffer(hfp_connection);
1374             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1375 
1376             return processed;
1377 
1378         case HFP_PARSER_CMD_SEQUENCE:
1379             // handle empty fields
1380             if ((byte == ',' ) && (hfp_connection->line_size == 0)){
1381                 hfp_connection->line_buffer[0] = 0;
1382                 hfp_connection->ignore_value = 1;
1383                 parse_sequence(hfp_connection);
1384                 return true;
1385             }
1386 
1387             hfp_parser_store_if_token(hfp_connection, byte);
1388             if (!hfp_parser_is_separator(byte)) return true;
1389 
1390             // ignore empty tokens
1391             switch (hfp_connection->command){
1392                 case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1393                     // don't ignore empty string
1394                     break;
1395                 default:
1396                     if (hfp_parser_is_buffer_empty(hfp_connection) && (hfp_connection->ignore_value == 0)) {
1397                         return true;
1398                     }
1399                     break;
1400             }
1401 
1402             parse_sequence(hfp_connection);
1403 
1404             hfp_parser_reset_line_buffer(hfp_connection);
1405 
1406             switch (hfp_connection->command){
1407                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1408                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1409                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1410                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1411                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1412                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1413                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1414                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1415                 case HFP_CMD_HF_INDICATOR_STATUS:
1416                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
1417                     break;
1418                 default:
1419                     break;
1420             }
1421             return true;
1422 
1423         case HFP_PARSER_SECOND_ITEM:
1424 
1425             hfp_parser_store_if_token(hfp_connection, byte);
1426             if (!hfp_parser_is_separator(byte)) return true;
1427 
1428             switch (hfp_connection->command){
1429                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1430                     log_info("format %s, ", hfp_connection->line_buffer);
1431                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1432                     break;
1433                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1434                     log_info("format %s \n", hfp_connection->line_buffer);
1435                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1436                     break;
1437                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1438                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1439                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1440                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1441                     break;
1442                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1443                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1444                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1445                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1446                     break;
1447                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1448                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer);
1449                     log_info("%s, ", hfp_connection->line_buffer);
1450                     break;
1451                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1452                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1453                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1454                     hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1455                     break;
1456                 case HFP_CMD_HF_INDICATOR_STATUS:
1457                     hfp_connection->parser_indicator_value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1458                     break;
1459                 default:
1460                     break;
1461             }
1462 
1463             hfp_parser_reset_line_buffer(hfp_connection);
1464 
1465             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
1466 
1467             return true;
1468 
1469         case HFP_PARSER_THIRD_ITEM:
1470 
1471             hfp_parser_store_if_token(hfp_connection, byte);
1472             if (!hfp_parser_is_separator(byte)) return true;
1473 
1474             switch (hfp_connection->command){
1475                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1476                     btstack_strcpy(hfp_connection->network_operator.name, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE,  (char *)hfp_connection->line_buffer);
1477                     break;
1478                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1479                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer);
1480                     hfp_next_indicators_index(hfp_connection);
1481                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1482                     break;
1483                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1484                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1485                     // track if last argument exists
1486                     hfp_connection->clip_have_alpha = hfp_connection->line_size != 0;
1487                     break;
1488                 default:
1489                     break;
1490             }
1491 
1492             hfp_parser_reset_line_buffer(hfp_connection);
1493 
1494             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){
1495                 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1496             }
1497             return true;
1498 
1499         case HFP_PARSER_CUSTOM_COMMAND:
1500             hfp_parser_store_byte(hfp_connection, byte);
1501             return true;
1502 
1503         default:
1504             btstack_assert(false);
1505             return true;
1506     }
1507 }
1508 
1509 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1510     bool processed = false;
1511     while (!processed){
1512         processed = hfp_parse_byte(hfp_connection, byte, isHandsFree);
1513     }
1514     // reset parser state on end-of-line
1515     if (hfp_parser_is_end_of_line(byte)){
1516         hfp_connection->found_equal_sign = false;
1517         hfp_connection->parser_item_index = 0;
1518         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1519     }
1520 }
1521 
1522 static void parse_sequence(hfp_connection_t * hfp_connection){
1523     int value;
1524     switch (hfp_connection->command){
1525         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1526             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1527             int i;
1528             switch (hfp_connection->parser_item_index){
1529                 case 0:
1530                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1531                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1532                             hfp_connection->parser_indicator_index = i;
1533                             break;
1534                         }
1535                     }
1536                     break;
1537                 case 1:
1538                     if (hfp_connection->parser_indicator_index <0) break;
1539                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1540                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1541                      hfp_connection->parser_item_index, value);
1542                     break;
1543                 default:
1544                     break;
1545             }
1546             hfp_next_indicators_index(hfp_connection);
1547             break;
1548 
1549         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1550             switch(hfp_connection->parser_item_index){
1551                 case 0:
1552                     // <alpha>: This optional field is not supported, and shall be left blank.
1553                     break;
1554                 case 1:
1555                     // <number>: Quoted string containing the phone number in the format specified by <type>.
1556                     btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1557                     break;
1558                 case 2:
1559                     /*
1560                       <type> field specifies the format of the phone number provided, and can be one of the following values:
1561                       - 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.
1562                      - 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.
1563                      - values 160-175: National number. No prefix nor escape digits included.
1564                      */
1565                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1566                     hfp_connection->bnip_type = value;
1567                     break;
1568                 case 3:
1569                     // <speed>: This optional field is not supported, and shall be left blank.
1570                     break;
1571                 case 4:
1572                     // <service>: Indicates which service this phone number relates to. Shall be either 4 (voice) or 5 (fax).
1573                 default:
1574                     break;
1575             }
1576             // index > 2 are ignored in switch above
1577             hfp_connection->parser_item_index++;
1578             break;
1579         case HFP_CMD_LIST_CURRENT_CALLS:
1580             switch(hfp_connection->parser_item_index){
1581                 case 0:
1582                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1583                     hfp_connection->clcc_idx = value;
1584                     break;
1585                 case 1:
1586                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1587                     hfp_connection->clcc_dir = value;
1588                     break;
1589                 case 2:
1590                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1591                     hfp_connection->clcc_status = value;
1592                     break;
1593                 case 3:
1594                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1595                     hfp_connection->clcc_mode = value;
1596                     break;
1597                 case 4:
1598                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1599                     hfp_connection->clcc_mpty = value;
1600                     break;
1601                 case 5:
1602                     btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1603                     break;
1604                 case 6:
1605                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1606                     hfp_connection->bnip_type = value;
1607                     break;
1608                 default:
1609                     break;
1610             }
1611             // index > 6 are ignored in switch above
1612             hfp_connection->parser_item_index++;
1613             break;
1614         case HFP_CMD_SET_MICROPHONE_GAIN:
1615             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1616             hfp_connection->microphone_gain = value;
1617             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1618             break;
1619         case HFP_CMD_SET_SPEAKER_GAIN:
1620             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1621             hfp_connection->speaker_gain = value;
1622             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1623             break;
1624         case HFP_CMD_TURN_OFF_EC_AND_NR:
1625             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1626             hfp_connection->ag_echo_and_noise_reduction = value;
1627             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1628             break;
1629         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1630             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1631             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1632             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1633             break;
1634         case HFP_CMD_HF_CONFIRMED_CODEC:
1635             hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer);
1636             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1637             break;
1638         case HFP_CMD_AG_SUGGESTED_CODEC:
1639             hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer);
1640             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1641             break;
1642         case HFP_CMD_SUPPORTED_FEATURES:
1643             hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer);
1644             log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features);
1645             break;
1646         case HFP_CMD_AVAILABLE_CODECS:
1647             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1648             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1649             hfp_next_codec_index(hfp_connection);
1650             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1651             break;
1652         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1653             btstack_strcpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, HFP_MAX_INDICATOR_DESC_SIZE, (char *)hfp_connection->line_buffer);
1654             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1655             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1656             break;
1657         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1658             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1659             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer);
1660             hfp_next_indicators_index(hfp_connection);
1661             break;
1662         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1663             hfp_next_indicators_index(hfp_connection);
1664             if (hfp_connection->parser_item_index != 4) break;
1665             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1666             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1667             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1668             break;
1669         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1670             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1671             if (hfp_connection->line_size > 2 ) break;
1672             memcpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE-1);
1673             hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name[HFP_CALL_SERVICE_SIZE - 1] = 0;
1674             hfp_next_remote_call_services_index(hfp_connection);
1675             break;
1676         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1677         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1678             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1679             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1680             hfp_next_indicators_index(hfp_connection);
1681             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1682             break;
1683         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1684             // HF parses inital AG gen. ind. state
1685             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1686             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1687             break;
1688         case HFP_CMD_HF_INDICATOR_STATUS:
1689             hfp_connection->parser_indicator_index = hfp_parse_indicator_index(hfp_connection);
1690             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1691             break;
1692         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1693             // AG parses new gen. ind. state
1694             if (hfp_connection->ignore_value){
1695                 hfp_connection->ignore_value = 0;
1696                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1697                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1698             }
1699             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1700                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1701                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1702             } else {
1703                 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1704                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1705                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1706                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1707             }
1708             hfp_next_indicators_index(hfp_connection);
1709             break;
1710         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1711             // indicators are indexed starting with 1
1712             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1713             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1714             break;
1715         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1716             hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1717             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1718             break;
1719         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1720             if (hfp_connection->line_buffer[0] == '3'){
1721                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1722                 break;
1723             }
1724             // TODO emit ERROR, wrong format
1725             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1726             break;
1727         case HFP_CMD_ERROR:
1728             break;
1729         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1730             hfp_connection->extended_audio_gateway_error = 1;
1731             hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1732             break;
1733         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1734             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1735             hfp_connection->ok_pending = 1;
1736             hfp_connection->extended_audio_gateway_error = 0;
1737             break;
1738         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1739         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1740         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1741             btstack_strcpy((char *)hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer);
1742             break;
1743         case HFP_CMD_CALL_HOLD:
1744             hfp_connection->ag_call_hold_action = hfp_connection->line_buffer[0] - '0';
1745             if (hfp_connection->line_buffer[1] != '\0'){
1746                 hfp_connection->call_index = btstack_atoi((char *)&hfp_connection->line_buffer[1]);
1747             }
1748             break;
1749         case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1750             hfp_connection->ag_response_and_hold_action = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1751             break;
1752         case HFP_CMD_TRANSMIT_DTMF_CODES:
1753             hfp_connection->ag_dtmf_code = hfp_connection->line_buffer[0];
1754             break;
1755         case HFP_CMD_ENABLE_CLIP:
1756             hfp_connection->clip_enabled = hfp_connection->line_buffer[0] != '0';
1757             break;
1758         case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1759             hfp_connection->call_waiting_notification_enabled = hfp_connection->line_buffer[0] != '0';
1760             break;
1761         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1762             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1763             hfp_connection->ag_activate_voice_recognition_value = value;
1764             break;
1765         case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1766             switch(hfp_connection->parser_item_index){
1767                 case 0:
1768                     hfp_connection->ag_vra_status = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1769                     break;
1770                 case 1:
1771                     hfp_connection->ag_vra_state = (hfp_voice_recognition_state_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1772                     break;
1773                 case 2:
1774                     hfp_connection->ag_msg.text_id = 0;
1775                     for (i = 0 ; i < 4; i++){
1776                         hfp_connection->ag_msg.text_id = (hfp_connection->ag_msg.text_id << 4) | nibble_for_char(hfp_connection->line_buffer[i]);
1777                     }
1778                     break;
1779                 case 3:
1780                     hfp_connection->ag_msg.text_type = (hfp_text_type_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1781                     break;
1782                 case 4:
1783                     hfp_connection->ag_msg.text_operation = (hfp_text_operation_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1784                     break;
1785                 case 5:
1786                     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1787                     hfp_connection->ag_vra_msg_length = hfp_connection->line_size + 1;
1788                     break;
1789                 default:
1790                     break;
1791             }
1792             hfp_connection->parser_item_index++;
1793             break;
1794         default:
1795             break;
1796     }
1797 }
1798 
1799 static void hfp_handle_start_sdp_client_query(void * context){
1800     UNUSED(context);
1801 
1802     btstack_linked_list_iterator_t it;
1803     btstack_linked_list_iterator_init(&it, &hfp_connections);
1804     while (btstack_linked_list_iterator_has_next(&it)){
1805         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1806 
1807         if (connection->state != HFP_W2_SEND_SDP_QUERY) continue;
1808 
1809         connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1810         hfp_sdp_query_context.local_role = connection->local_role;
1811         (void)memcpy(hfp_sdp_query_context.remote_address, connection->remote_addr, 6);
1812         sdp_client_query_rfcomm_channel_and_name_for_service_class_uuid(&handle_query_rfcomm_event, connection->remote_addr, connection->service_uuid);
1813         return;
1814     }
1815 }
1816 
1817 uint8_t hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){
1818     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr, local_role);
1819     if (connection){
1820         return ERROR_CODE_COMMAND_DISALLOWED;
1821     }
1822 
1823     connection = hfp_create_connection(bd_addr, local_role);
1824     if (!connection){
1825         return BTSTACK_MEMORY_ALLOC_FAILED;
1826     }
1827 
1828     connection->state = HFP_W2_SEND_SDP_QUERY;
1829 
1830     bd_addr_copy(connection->remote_addr, bd_addr);
1831     connection->service_uuid = service_uuid;
1832 
1833     hfp_sdp_query_request.callback = &hfp_handle_start_sdp_client_query;
1834     // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1835     (void) sdp_client_register_query_callback(&hfp_sdp_query_request);
1836     return ERROR_CODE_SUCCESS;
1837 }
1838 
1839 void hfp_trigger_release_service_level_connection(hfp_connection_t * hfp_connection){
1840     // called internally, NULL check already performed
1841     btstack_assert(hfp_connection != NULL);
1842 
1843     hfp_trigger_release_audio_connection(hfp_connection);
1844     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1845         hfp_connection->state = HFP_IDLE;
1846         return;
1847     }
1848 
1849     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1850         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1851         return;
1852     }
1853     hfp_connection->release_slc_connection = 1;
1854     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1855         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1856         return;
1857     }
1858 
1859     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1860         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1861         hfp_connection->release_audio_connection = 1;
1862         return;
1863     }
1864 }
1865 
1866 uint8_t hfp_trigger_release_audio_connection(hfp_connection_t * hfp_connection){
1867     // called internally, NULL check already performed
1868     btstack_assert(hfp_connection != NULL);
1869     if (hfp_connection->state <= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
1870         return ERROR_CODE_COMMAND_DISALLOWED;
1871     }
1872     switch (hfp_connection->state) {
1873         case HFP_W2_CONNECT_SCO:
1874             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1875             break;
1876         case HFP_W4_SCO_CONNECTED:
1877         case HFP_AUDIO_CONNECTION_ESTABLISHED:
1878             hfp_connection->release_audio_connection = 1;
1879             break;
1880         default:
1881             return ERROR_CODE_COMMAND_DISALLOWED;
1882     }
1883     return ERROR_CODE_SUCCESS;
1884 }
1885 
1886 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){
1887     // all packet types, fixed bandwidth
1888     int setting = hfp_connection->link_setting;
1889     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1890     hfp_sco_establishment_active = hfp_connection;
1891     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1892     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1893 #ifdef ENABLE_BCM_PCM_WBS
1894         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
1895 #else
1896         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
1897 #endif
1898     }
1899     uint16_t packet_types = hfp_link_settings[setting].packet_types;
1900     hfp_connection->packet_types = packet_types;
1901 
1902     // get packet types - bits 6-9 are 'don't allow'
1903     uint16_t packet_types_flipped = packet_types ^ 0x03c0;
1904     hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency,
1905         sco_voice_setting, hfp_link_settings[setting].retransmission_effort, packet_types_flipped);
1906 }
1907 
1908 void hfp_accept_synchronous_connection(hfp_connection_t * hfp_connection, bool incoming_eSCO){
1909 
1910     // remote supported feature eSCO is set if link type is eSCO
1911     // eSCO: S4 - max latency == transmission interval = 0x000c == 12 ms,
1912     uint16_t max_latency;
1913     uint8_t  retransmission_effort;
1914     uint16_t packet_types;
1915 
1916     if (incoming_eSCO && hci_extended_sco_link_supported() && hci_remote_esco_supported(hfp_connection->acl_handle)){
1917         max_latency = 0x000c;
1918         retransmission_effort = 0x02;
1919         // eSCO: EV3 and 2-EV3
1920         packet_types = 0x0048;
1921     } else {
1922         max_latency = 0xffff;
1923         retransmission_effort = 0xff;
1924         // sco: HV1 and HV3
1925         packet_types = 0x005;
1926     }
1927 
1928     // mSBC only allows for transparent data
1929     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1930     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1931 #ifdef ENABLE_BCM_PCM_WBS
1932         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
1933 #else
1934         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
1935 #endif
1936     }
1937 
1938     // filter packet types
1939     packet_types &= hfp_get_sco_packet_types();
1940 
1941     hfp_connection->packet_types = packet_types;
1942 
1943     // bits 6-9 are 'don't allow'
1944     uint16_t packet_types_flipped = packet_types ^ 0x3c0;
1945 
1946     log_info("HFP: sending hci_accept_connection_request, packet types 0x%04x, sco_voice_setting 0x%02x", packet_types, sco_voice_setting);
1947     hci_send_cmd(&hci_accept_synchronous_connection, hfp_connection->remote_addr, 8000, 8000, max_latency,
1948                  sco_voice_setting, retransmission_effort, packet_types_flipped);
1949 }
1950 
1951 #ifdef ENABLE_CC256X_ASSISTED_HFP
1952 void hfp_cc256x_prepare_for_sco(hfp_connection_t * hfp_connection){
1953     hfp_connection->cc256x_send_write_codec_config = true;
1954     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1955         hfp_connection->cc256x_send_wbs_associate = true;
1956     }
1957 }
1958 
1959 void hfp_cc256x_write_codec_config(hfp_connection_t * hfp_connection){
1960     uint32_t sample_rate_hz;
1961     uint16_t clock_rate_khz;
1962     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1963         clock_rate_khz = 512;
1964         sample_rate_hz = 16000;
1965     } else {
1966         clock_rate_khz = 256;
1967         sample_rate_hz = 8000;
1968     }
1969     uint8_t clock_direction = 0;        // master
1970     uint16_t frame_sync_duty_cycle = 0; // i2s with 50%
1971     uint8_t  frame_sync_edge = 1;       // rising edge
1972     uint8_t  frame_sync_polarity = 0;   // active high
1973     uint8_t  reserved = 0;
1974     uint16_t size = 16;
1975     uint16_t chan_1_offset = 1;
1976     uint16_t chan_2_offset = chan_1_offset + size;
1977     uint8_t  out_edge = 1;              // rising
1978     uint8_t  in_edge = 0;               // falling
1979     hci_send_cmd(&hci_ti_write_codec_config, clock_rate_khz, clock_direction, sample_rate_hz, frame_sync_duty_cycle,
1980                  frame_sync_edge, frame_sync_polarity, reserved,
1981                  size, chan_1_offset, out_edge, size, chan_1_offset, in_edge, reserved,
1982                  size, chan_2_offset, out_edge, size, chan_2_offset, in_edge, reserved);
1983 }
1984 #endif
1985 
1986 #ifdef ENABLE_BCM_PCM_WBS
1987 void hfp_bcm_prepare_for_sco(hfp_connection_t * hfp_connection){
1988     hfp_connection->bcm_send_write_i2spcm_interface_param = true;
1989     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1990         hfp_connection->bcm_send_enable_wbs = true;
1991     }
1992 }
1993 void hfp_bcm_write_i2spcm_interface_param(hfp_connection_t * hfp_connection){
1994     uint8_t sample_rate = (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? 1 : 0;
1995     // i2s enable, master, 8/16 kHz, 512 kHz
1996     hci_send_cmd(&hci_bcm_write_i2spcm_interface_paramhci_bcm_write_i2spcm_interface_param, 1, 1, sample_rate, 2);
1997 }
1998 #endif
1999 
2000 void hfp_set_hf_callback(btstack_packet_handler_t callback){
2001     hfp_hf_callback = callback;
2002 }
2003 
2004 void hfp_set_ag_callback(btstack_packet_handler_t callback){
2005     hfp_ag_callback = callback;
2006 }
2007 
2008 void hfp_set_ag_rfcomm_packet_handler(btstack_packet_handler_t handler){
2009     hfp_ag_rfcomm_packet_handler = handler;
2010 }
2011 
2012 void hfp_set_hf_rfcomm_packet_handler(btstack_packet_handler_t handler){
2013     hfp_hf_rfcomm_packet_handler = handler;
2014 }
2015 
2016 void hfp_init(void){
2017     hfp_allowed_sco_packet_types = SCO_PACKET_TYPES_ALL;
2018 }
2019 
2020 void hfp_deinit(void){
2021     hfp_allowed_sco_packet_types = 0;
2022     hfp_connections = NULL;
2023     hfp_hf_callback = NULL;
2024     hfp_ag_callback = NULL;
2025     hfp_hf_rfcomm_packet_handler = NULL;
2026     hfp_ag_rfcomm_packet_handler = NULL;
2027     hfp_sco_establishment_active = NULL;
2028     hfp_custom_commands_ag = NULL;
2029     (void) memset(&hfp_sdp_query_context, 0, sizeof(hfp_sdp_query_context_t));
2030     (void) memset(&hfp_sdp_query_request, 0, sizeof(btstack_context_callback_registration_t));
2031 }
2032 
2033 void hfp_set_sco_packet_types(uint16_t packet_types){
2034     hfp_allowed_sco_packet_types = packet_types;
2035 }
2036 
2037 uint16_t hfp_get_sco_packet_types(void){
2038     return hfp_allowed_sco_packet_types;
2039 }
2040 
2041 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){
2042     int8_t setting = (int8_t) current_setting;
2043     bool can_use_eSCO = local_eSCO_supported && remote_eSCO_supported;
2044     while (setting > 0){
2045         setting--;
2046         // skip if eSCO required but not available
2047         if (hfp_link_settings[setting].eSCO && !can_use_eSCO) continue;
2048         // skip if S4 but not supported
2049         if ((setting == (int8_t) HFP_LINK_SETTINGS_S4) && !eSCO_S4_supported) continue;
2050         // skip wrong codec
2051         if ( hfp_link_settings[setting].codec != negotiated_codec) continue;
2052         // skip disabled packet types
2053         uint16_t required_packet_types = hfp_link_settings[setting].packet_types;
2054         uint16_t allowed_packet_types  = hfp_allowed_sco_packet_types;
2055         if ((required_packet_types & allowed_packet_types) == 0) continue;
2056 
2057         // found matching setting
2058         return (hfp_link_settings_t) setting;
2059     }
2060     return HFP_LINK_SETTINGS_NONE;
2061 }
2062 
2063 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){
2064     bool local_eSCO_supported  = hci_extended_sco_link_supported();
2065     bool remote_eSCO_supported = hci_remote_esco_supported(hfp_connection->acl_handle);
2066     uint8_t negotiated_codec   = hfp_connection->negotiated_codec;
2067     return  hfp_next_link_setting(current_setting, local_eSCO_supported, remote_eSCO_supported, eSCO_S4_supported, negotiated_codec);
2068 }
2069 
2070 void hfp_init_link_settings(hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported){
2071     // get highest possible link setting
2072     hfp_connection->link_setting = hfp_next_link_setting_for_connection(HFP_LINK_SETTINGS_NONE, hfp_connection, eSCO_S4_supported);
2073     log_info("hfp_init_link_settings: %u", hfp_connection->link_setting);
2074 }
2075 
2076 #define HFP_HF_RX_DEBUG_PRINT_LINE 80
2077 
2078 void hfp_log_rfcomm_message(const char * tag, uint8_t * packet, uint16_t size){
2079 #ifdef ENABLE_LOG_INFO
2080     // encode \n\r
2081     char printable[HFP_HF_RX_DEBUG_PRINT_LINE+2];
2082     int i = 0;
2083     int pos;
2084     for (pos=0 ; (pos < size) && (i < (HFP_HF_RX_DEBUG_PRINT_LINE - 3)) ; pos++){
2085         switch (packet[pos]){
2086             case '\n':
2087                 printable[i++] = '\\';
2088                 printable[i++] = 'n';
2089                 break;
2090             case '\r':
2091                 printable[i++] = '\\';
2092                 printable[i++] = 'r';
2093                 break;
2094             default:
2095                 printable[i++] = packet[pos];
2096                 break;
2097         }
2098     }
2099     printable[i] = 0;
2100     log_info("%s: '%s'", tag, printable);
2101 #endif
2102 }
2103 
2104 void hfp_register_custom_ag_command(hfp_custom_at_command_t * custom_at_command){
2105     btstack_linked_list_add(&hfp_custom_commands_ag, (btstack_linked_item_t *) custom_at_command);
2106 }
2107