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