xref: /btstack/src/classic/hfp.c (revision 7bbeb3ad8cec0c1816689843bf9383cf4c644ef8)
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 MATTHIAS
24  * RINGWALD 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 <string.h>
45 #include <inttypes.h>
46 
47 #include "bluetooth_sdp.h"
48 #include "btstack_debug.h"
49 #include "btstack_event.h"
50 #include "btstack_memory.h"
51 #include "btstack_run_loop.h"
52 #include "classic/core.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 #include "l2cap.h"
61 
62 #define HFP_HF_FEATURES_SIZE 10
63 #define HFP_AG_FEATURES_SIZE 12
64 
65 
66 static const char * hfp_hf_features[] = {
67     "EC and/or NR function",
68     "Three-way calling",
69     "CLI presentation capability",
70     "Voice recognition activation",
71     "Remote volume control",
72 
73     "Enhanced call status",
74     "Enhanced call control",
75 
76     "Codec negotiation",
77 
78     "HF Indicators",
79     "eSCO S4 (and T2) Settings Supported",
80     "Reserved for future definition"
81 };
82 
83 static const char * hfp_ag_features[] = {
84     "Three-way calling",
85     "EC and/or NR function",
86     "Voice recognition function",
87     "In-band ring tone capability",
88     "Attach a number to a voice tag",
89     "Ability to reject a call",
90     "Enhanced call status",
91     "Enhanced call control",
92     "Extended Error Result Codes",
93     "Codec negotiation",
94     "HF Indicators",
95     "eSCO S4 (and T2) Settings Supported",
96     "Reserved for future definition"
97 };
98 
99 static const char * hfp_enhanced_call_dir[] = {
100     "outgoing",
101     "incoming"
102 };
103 
104 static const char * hfp_enhanced_call_status[] = {
105     "active",
106     "held",
107     "outgoing dialing",
108     "outgoing alerting",
109     "incoming",
110     "incoming waiting",
111     "call held by response and hold"
112 };
113 
114 static const char * hfp_enhanced_call_mode[] = {
115     "voice",
116     "data",
117     "fax"
118 };
119 
120 static const char * hfp_enhanced_call_mpty[] = {
121     "not a conference call",
122     "conference call"
123 };
124 
125 const char * hfp_enhanced_call_dir2str(uint16_t index){
126     if (index <= HFP_ENHANCED_CALL_DIR_INCOMING) return hfp_enhanced_call_dir[index];
127     return "not defined";
128 }
129 
130 const char * hfp_enhanced_call_status2str(uint16_t index){
131     if (index <= HFP_ENHANCED_CALL_STATUS_CALL_HELD_BY_RESPONSE_AND_HOLD) return hfp_enhanced_call_status[index];
132     return "not defined";
133 }
134 
135 const char * hfp_enhanced_call_mode2str(uint16_t index){
136     if (index <= HFP_ENHANCED_CALL_MODE_FAX) return hfp_enhanced_call_mode[index];
137     return "not defined";
138 }
139 
140 const char * hfp_enhanced_call_mpty2str(uint16_t index){
141     if (index <= HFP_ENHANCED_CALL_MPTY_CONFERENCE_CALL) return hfp_enhanced_call_mpty[index];
142     return "not defined";
143 }
144 
145 typedef struct {
146     hfp_role_t local_role;
147     bd_addr_t  remote_address;
148 } hfp_sdp_query_context_t;
149 
150 static hfp_sdp_query_context_t sdp_query_context;
151 static btstack_context_callback_registration_t hfp_handle_sdp_client_query_request;
152 
153 static void parse_sequence(hfp_connection_t * context);
154 
155 static btstack_linked_list_t hfp_connections = NULL;
156 
157 static btstack_packet_handler_t hfp_hf_callback;
158 static btstack_packet_handler_t hfp_ag_callback;
159 
160 static btstack_packet_handler_t hfp_hf_rfcomm_packet_handler;
161 static btstack_packet_handler_t hfp_ag_rfcomm_packet_handler;
162 
163 static void (*hfp_hf_run_for_context)(hfp_connection_t * hfp_connection);
164 
165 static hfp_connection_t * sco_establishment_active;
166 
167 // HFP_SCO_PACKET_TYPES_NONE == no choice/override
168 static uint16_t hfp_allowed_sco_packet_types;
169 
170 // prototypes
171 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);
172 
173 static uint16_t hfp_parse_indicator_index(hfp_connection_t * hfp_connection){
174     uint16_t index = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
175 
176     if (index > HFP_MAX_NUM_INDICATORS){
177         log_info("ignoring invalid indicator index bigger then HFP_MAX_NUM_INDICATORS");
178         return HFP_MAX_NUM_INDICATORS - 1;
179     }
180 
181     // indicator index enumeration starts with 1, we substract 1 to store in array with starting index 0
182     if (index > 0){
183         index -= 1;
184     } else {
185         log_info("ignoring invalid indicator index 0");
186         return 0;
187     }
188     return index;
189 }
190 
191 static void hfp_next_indicators_index(hfp_connection_t * hfp_connection){
192     if (hfp_connection->parser_item_index < HFP_MAX_NUM_INDICATORS - 1){
193         hfp_connection->parser_item_index++;
194     } else {
195         log_info("Ignoring additional indicator");
196     }
197 }
198 
199 static void hfp_next_codec_index(hfp_connection_t * hfp_connection){
200     if (hfp_connection->parser_item_index < HFP_MAX_NUM_CODECS - 1){
201         hfp_connection->parser_item_index++;
202     } else {
203         log_info("Ignoring additional codec index");
204     }
205 }
206 
207 static void hfp_next_remote_call_services_index(hfp_connection_t * hfp_connection){
208     if (hfp_connection->remote_call_services_index < HFP_MAX_NUM_CALL_SERVICES - 1){
209         hfp_connection->remote_call_services_index++;
210     } else {
211         log_info("Ignoring additional remote_call_services");
212     }
213 }
214 
215 const char * hfp_hf_feature(int index){
216     if (index > HFP_HF_FEATURES_SIZE){
217         return hfp_hf_features[HFP_HF_FEATURES_SIZE];
218     }
219     return hfp_hf_features[index];
220 }
221 
222 const char * hfp_ag_feature(int index){
223     if (index > HFP_AG_FEATURES_SIZE){
224         return hfp_ag_features[HFP_AG_FEATURES_SIZE];
225     }
226     return hfp_ag_features[index];
227 }
228 
229 int send_str_over_rfcomm(uint16_t cid, char * command){
230     if (!rfcomm_can_send_packet_now(cid)) return 1;
231     log_info("HFP_TX %s", command);
232     int err = rfcomm_send(cid, (uint8_t*) command, strlen(command));
233     if (err){
234         log_error("rfcomm_send -> error 0x%02x \n", err);
235     }
236     return 1;
237 }
238 
239 int hfp_supports_codec(uint8_t codec, int codecs_nr, uint8_t * codecs){
240 
241     // mSBC requires support for eSCO connections
242     if ((codec == HFP_CODEC_MSBC) && !hci_extended_sco_link_supported()) return 0;
243 
244     int i;
245     for (i = 0; i < codecs_nr; i++){
246         if (codecs[i] != codec) continue;
247         return 1;
248     }
249     return 0;
250 }
251 
252 void hfp_hf_drop_mSBC_if_eSCO_not_supported(uint8_t * codecs, uint8_t * codecs_nr){
253     if (hci_extended_sco_link_supported()) return;
254     uint8_t tmp_codecs[HFP_MAX_NUM_CODECS];
255     int i;
256     int tmp_codec_nr = 0;
257     for (i=0; i < *codecs_nr; i++){
258         if (codecs[i] == HFP_CODEC_MSBC) continue;
259         tmp_codecs[tmp_codec_nr++] = codecs[i];
260     }
261     *codecs_nr = tmp_codec_nr;
262     (void)memcpy(codecs, tmp_codecs, tmp_codec_nr);
263 }
264 
265 // UTILS
266 int get_bit(uint16_t bitmap, int position){
267     return (bitmap >> position) & 1;
268 }
269 
270 int store_bit(uint32_t bitmap, int position, uint8_t value){
271     if (value){
272         bitmap |= 1 << position;
273     } else {
274         bitmap &= ~ (1 << position);
275     }
276     return bitmap;
277 }
278 
279 int join(char * buffer, int buffer_size, uint8_t * values, int values_nr){
280     if (buffer_size < (values_nr * 3)) return 0;
281     int i;
282     int offset = 0;
283     for (i = 0; i < (values_nr-1); i++) {
284       offset += snprintf(buffer+offset, buffer_size-offset, "%d,", values[i]); // puts string into buffer
285     }
286     if (i<values_nr){
287         offset += snprintf(buffer+offset, buffer_size-offset, "%d", values[i]);
288     }
289     return offset;
290 }
291 
292 int join_bitmap(char * buffer, int buffer_size, uint32_t values, int values_nr){
293     if (buffer_size < (values_nr * 3)) return 0;
294 
295     int i;
296     int offset = 0;
297     for (i = 0; i < (values_nr-1); i++) {
298       offset += snprintf(buffer+offset, buffer_size-offset, "%d,", get_bit(values,i)); // puts string into buffer
299     }
300 
301     if (i<values_nr){
302         offset += snprintf(buffer+offset, buffer_size-offset, "%d", get_bit(values,i));
303     }
304     return offset;
305 }
306 
307 static void hfp_emit_event_for_context(hfp_connection_t * hfp_connection, uint8_t * packet, uint16_t size){
308     if (!hfp_connection) return;
309     btstack_packet_handler_t callback = NULL;
310     switch (hfp_connection->local_role){
311         case HFP_ROLE_HF:
312             callback = hfp_hf_callback;
313             break;
314         case HFP_ROLE_AG:
315             callback = hfp_ag_callback;
316             break;
317         default:
318             return;
319     }
320     (*callback)(HCI_EVENT_PACKET, 0, packet, size);
321 }
322 
323 void hfp_emit_simple_event(hfp_connection_t * hfp_connection, uint8_t event_subtype){
324     uint8_t event[3];
325     event[0] = HCI_EVENT_HFP_META;
326     event[1] = sizeof(event) - 2;
327     event[2] = event_subtype;
328     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
329 }
330 
331 void hfp_emit_event(hfp_connection_t * hfp_connection, uint8_t event_subtype, uint8_t value){
332     uint8_t event[4];
333     event[0] = HCI_EVENT_HFP_META;
334     event[1] = sizeof(event) - 2;
335     event[2] = event_subtype;
336     event[3] = value; // status 0 == OK
337     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
338 }
339 
340 void hfp_emit_slc_connection_event(hfp_connection_t * hfp_connection, uint8_t status, hci_con_handle_t con_handle, bd_addr_t addr){
341     uint8_t event[12];
342     int pos = 0;
343     event[pos++] = HCI_EVENT_HFP_META;
344     event[pos++] = sizeof(event) - 2;
345     event[pos++] = HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
346     event[pos++] = status; // status 0 == OK
347     little_endian_store_16(event, pos, con_handle);
348     pos += 2;
349     reverse_bd_addr(addr,&event[pos]);
350     pos += 6;
351     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
352 }
353 
354 void hfp_emit_sco_event(hfp_connection_t * hfp_connection, uint8_t status, hci_con_handle_t con_handle, bd_addr_t addr, uint8_t  negotiated_codec){
355     uint8_t event[13];
356     int pos = 0;
357     event[pos++] = HCI_EVENT_HFP_META;
358     event[pos++] = sizeof(event) - 2;
359     event[pos++] = HFP_SUBEVENT_AUDIO_CONNECTION_ESTABLISHED;
360     event[pos++] = status; // status 0 == OK
361     little_endian_store_16(event, pos, con_handle);
362     pos += 2;
363     reverse_bd_addr(addr,&event[pos]);
364     pos += 6;
365     event[pos++] = negotiated_codec;
366     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
367 }
368 
369 void hfp_emit_string_event(hfp_connection_t * hfp_connection, uint8_t event_subtype, const char * value){
370     uint8_t event[40];
371     event[0] = HCI_EVENT_HFP_META;
372     event[1] = sizeof(event) - 2;
373     event[2] = event_subtype;
374     uint16_t size = btstack_min(strlen(value), sizeof(event) - 4);
375     strncpy((char*)&event[3], value, size);
376     event[3 + size] = 0;
377     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
378 }
379 
380 btstack_linked_list_t * hfp_get_connections(void){
381     return (btstack_linked_list_t *) &hfp_connections;
382 }
383 
384 hfp_connection_t * get_hfp_connection_context_for_rfcomm_cid(uint16_t cid){
385     btstack_linked_list_iterator_t it;
386     btstack_linked_list_iterator_init(&it, hfp_get_connections());
387     while (btstack_linked_list_iterator_has_next(&it)){
388         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
389         if (hfp_connection->rfcomm_cid == cid){
390             return hfp_connection;
391         }
392     }
393     return NULL;
394 }
395 
396 hfp_connection_t * get_hfp_connection_context_for_bd_addr(bd_addr_t bd_addr, hfp_role_t hfp_role){
397     btstack_linked_list_iterator_t it;
398     btstack_linked_list_iterator_init(&it, hfp_get_connections());
399     while (btstack_linked_list_iterator_has_next(&it)){
400         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
401         if ((memcmp(hfp_connection->remote_addr, bd_addr, 6) == 0) && (hfp_connection->local_role == hfp_role)) {
402             return hfp_connection;
403         }
404     }
405     return NULL;
406 }
407 
408 hfp_connection_t * get_hfp_connection_context_for_sco_handle(uint16_t handle, hfp_role_t hfp_role){
409     btstack_linked_list_iterator_t it;
410     btstack_linked_list_iterator_init(&it, hfp_get_connections());
411     while (btstack_linked_list_iterator_has_next(&it)){
412         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
413         if ((hfp_connection->sco_handle == handle) && (hfp_connection->local_role == hfp_role)){
414             return hfp_connection;
415         }
416     }
417     return NULL;
418 }
419 
420 hfp_connection_t * get_hfp_connection_context_for_acl_handle(uint16_t handle, hfp_role_t hfp_role){
421     btstack_linked_list_iterator_t it;
422     btstack_linked_list_iterator_init(&it, hfp_get_connections());
423     while (btstack_linked_list_iterator_has_next(&it)){
424         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
425         if ((hfp_connection->acl_handle == handle) && (hfp_connection->local_role == hfp_role)){
426             return hfp_connection;
427         }
428     }
429     return NULL;
430 }
431 
432 void hfp_reset_context_flags(hfp_connection_t * hfp_connection){
433     if (!hfp_connection) return;
434     hfp_connection->ok_pending = 0;
435     hfp_connection->send_error = 0;
436 
437     hfp_connection->found_equal_sign = false;
438 
439     hfp_connection->change_status_update_for_individual_ag_indicators = 0;
440     hfp_connection->operator_name_changed = 0;
441 
442     hfp_connection->enable_extended_audio_gateway_error_report = 0;
443     hfp_connection->extended_audio_gateway_error = 0;
444 
445     // establish codecs hfp_connection
446     hfp_connection->suggested_codec = 0;
447     hfp_connection->negotiated_codec = 0;
448     hfp_connection->codec_confirmed = 0;
449 
450     hfp_connection->establish_audio_connection = 0;
451     hfp_connection->call_waiting_notification_enabled = 0;
452     hfp_connection->command = HFP_CMD_NONE;
453     hfp_connection->enable_status_update_for_ag_indicators = 0xFF;
454 }
455 
456 static hfp_connection_t * create_hfp_connection_context(void){
457     hfp_connection_t * hfp_connection = btstack_memory_hfp_connection_get();
458     if (!hfp_connection) return NULL;
459 
460     hfp_connection->state = HFP_IDLE;
461     hfp_connection->call_state = HFP_CALL_IDLE;
462     hfp_connection->codecs_state = HFP_CODECS_IDLE;
463 
464     hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
465     hfp_connection->command = HFP_CMD_NONE;
466 
467     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
468     hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID;
469 
470     hfp_reset_context_flags(hfp_connection);
471 
472     btstack_linked_list_add(&hfp_connections, (btstack_linked_item_t*)hfp_connection);
473     return hfp_connection;
474 }
475 
476 static void remove_hfp_connection_context(hfp_connection_t * hfp_connection){
477     btstack_linked_list_remove(&hfp_connections, (btstack_linked_item_t*) hfp_connection);
478     btstack_memory_hfp_connection_free(hfp_connection);
479 }
480 
481 static hfp_connection_t * provide_hfp_connection_context_for_bd_addr(bd_addr_t bd_addr, hfp_role_t local_role){
482     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(bd_addr, local_role);
483     if (hfp_connection) return  hfp_connection;
484     hfp_connection = create_hfp_connection_context();
485     (void)memcpy(hfp_connection->remote_addr, bd_addr, 6);
486     hfp_connection->local_role = local_role;
487     log_info("Create HFP context %p: role %u, addr %s", hfp_connection, local_role, bd_addr_to_str(bd_addr));
488 
489     return hfp_connection;
490 }
491 
492 /* @param network.
493  * 0 == no ability to reject a call.
494  * 1 == ability to reject a call.
495  */
496 
497 /* @param suported_features
498  * HF bit 0: EC and/or NR function (yes/no, 1 = yes, 0 = no)
499  * HF bit 1: Call waiting or three-way calling(yes/no, 1 = yes, 0 = no)
500  * HF bit 2: CLI presentation capability (yes/no, 1 = yes, 0 = no)
501  * HF bit 3: Voice recognition activation (yes/no, 1= yes, 0 = no)
502  * HF bit 4: Remote volume control (yes/no, 1 = yes, 0 = no)
503  * HF bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
504  */
505  /* Bit position:
506  * AG bit 0: Three-way calling (yes/no, 1 = yes, 0 = no)
507  * AG bit 1: EC and/or NR function (yes/no, 1 = yes, 0 = no)
508  * AG bit 2: Voice recognition function (yes/no, 1 = yes, 0 = no)
509  * AG bit 3: In-band ring tone capability (yes/no, 1 = yes, 0 = no)
510  * AG bit 4: Attach a phone number to a voice tag (yes/no, 1 = yes, 0 = no)
511  * AG bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
512  */
513 
514 void hfp_create_sdp_record(uint8_t * service, uint32_t service_record_handle, uint16_t service_uuid, int rfcomm_channel_nr, const char * name){
515     uint8_t* attribute;
516     de_create_sequence(service);
517 
518     // 0x0000 "Service Record Handle"
519     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
520     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
521 
522     // 0x0001 "Service Class ID List"
523     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
524     attribute = de_push_sequence(service);
525     {
526         //  "UUID for Service"
527         de_add_number(attribute, DE_UUID, DE_SIZE_16, service_uuid);
528         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_GENERIC_AUDIO);
529     }
530     de_pop_sequence(service, attribute);
531 
532     // 0x0004 "Protocol Descriptor List"
533     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
534     attribute = de_push_sequence(service);
535     {
536         uint8_t* l2cpProtocol = de_push_sequence(attribute);
537         {
538             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
539         }
540         de_pop_sequence(attribute, l2cpProtocol);
541 
542         uint8_t* rfcomm = de_push_sequence(attribute);
543         {
544             de_add_number(rfcomm,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_RFCOMM);  // rfcomm_service
545             de_add_number(rfcomm,  DE_UINT, DE_SIZE_8,  rfcomm_channel_nr);  // rfcomm channel
546         }
547         de_pop_sequence(attribute, rfcomm);
548     }
549     de_pop_sequence(service, attribute);
550 
551 
552     // 0x0005 "Public Browse Group"
553     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
554     attribute = de_push_sequence(service);
555     {
556         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
557     }
558     de_pop_sequence(service, attribute);
559 
560     // 0x0009 "Bluetooth Profile Descriptor List"
561     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
562     attribute = de_push_sequence(service);
563     {
564         uint8_t *sppProfile = de_push_sequence(attribute);
565         {
566             de_add_number(sppProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HANDSFREE);
567             de_add_number(sppProfile,  DE_UINT, DE_SIZE_16, 0x0107); // Verision 1.7
568         }
569         de_pop_sequence(attribute, sppProfile);
570     }
571     de_pop_sequence(service, attribute);
572 
573     // 0x0100 "Service Name"
574     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
575     de_add_data(service,  DE_STRING, strlen(name), (uint8_t *) name);
576 }
577 
578 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
579     UNUSED(packet_type);    // ok: handling own sdp events
580     UNUSED(channel);        // ok: no channel
581     UNUSED(size);           // ok: handling own sdp events
582 
583     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(sdp_query_context.remote_address, sdp_query_context.local_role);
584     if (hfp_connection == NULL) {
585         log_info("connection with %s and local role %d not found", sdp_query_context.remote_address, sdp_query_context.local_role);
586         return;
587     }
588 
589     switch (hci_event_packet_get_type(packet)){
590         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
591             hfp_connection->rfcomm_channel_nr = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
592             break;
593         case SDP_EVENT_QUERY_COMPLETE:
594             if (hfp_connection->rfcomm_channel_nr > 0){
595                 hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
596                 btstack_packet_handler_t packet_handler;
597                 switch (hfp_connection->local_role){
598                     case HFP_ROLE_AG:
599                         packet_handler = hfp_ag_rfcomm_packet_handler;
600                         break;
601                     case HFP_ROLE_HF:
602                         packet_handler = hfp_hf_rfcomm_packet_handler;
603                         break;
604                     default:
605                         btstack_assert(false);
606                         return;
607                 }
608 
609                 rfcomm_create_channel(packet_handler, hfp_connection->remote_addr, hfp_connection->rfcomm_channel_nr, NULL);
610 
611             } else {
612                 hfp_connection->state = HFP_IDLE;
613                 hfp_emit_slc_connection_event(hfp_connection, sdp_event_query_complete_get_status(packet), HCI_CON_HANDLE_INVALID, hfp_connection->remote_addr);
614                 log_info("rfcomm service not found, status 0x%02x", sdp_event_query_complete_get_status(packet));
615             }
616 
617             // register the SDP Query request to check if there is another connection waiting for the query
618             // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
619             (void) sdp_client_register_query_callback(&hfp_handle_sdp_client_query_request);
620             break;
621         default:
622             break;
623     }
624 }
625 
626 // returns 0 if unexpected error or no other link options remained, otherwise 1
627 static int hfp_handle_failed_sco_connection(uint8_t status){
628 
629     if (!sco_establishment_active){
630         log_info("(e)SCO Connection failed but not started by us");
631         return 0;
632     }
633 
634     log_info("(e)SCO Connection failed 0x%02x", status);
635     switch (status){
636         case ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE:
637         case ERROR_CODE_UNSPECIFIED_ERROR:
638         case ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES:
639             break;
640         default:
641             return 0;
642     }
643 
644     // note: eSCO_S4 supported flag not available, but it's only relevant for highest CVSD link setting (and the current failed)
645     hfp_link_settings_t next_setting = hfp_next_link_setting_for_connection(sco_establishment_active->link_setting, sco_establishment_active, false);
646 
647     // handle no valid setting found
648     if (next_setting == HFP_LINK_SETTINGS_NONE) {
649         if (sco_establishment_active->negotiated_codec == HFP_CODEC_MSBC){
650             log_info("T2/T1 failed, fallback to CVSD - D1");
651             sco_establishment_active->negotiated_codec = HFP_CODEC_CVSD;
652             sco_establishment_active->sco_for_msbc_failed = 1;
653             sco_establishment_active->command = HFP_CMD_AG_SEND_COMMON_CODEC;
654             sco_establishment_active->link_setting = HFP_LINK_SETTINGS_D1;
655         } else {
656             // no other options
657             return 0;
658         }
659     }
660 
661     log_info("e)SCO Connection: try new link_setting %d", next_setting);
662     sco_establishment_active->establish_audio_connection = 1;
663     sco_establishment_active->link_setting = next_setting;
664     sco_establishment_active = NULL;
665     return 1;
666 }
667 
668 
669 void hfp_handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
670     UNUSED(packet_type);
671     UNUSED(channel);    // ok: no channel
672     UNUSED(size);
673 
674     bd_addr_t event_addr;
675     hci_con_handle_t handle;
676     hfp_connection_t * hfp_connection = NULL;
677     uint8_t status;
678 
679     log_debug("HFP HCI event handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
680 
681     switch (hci_event_packet_get_type(packet)) {
682 
683         case HCI_EVENT_CONNECTION_REQUEST:
684             switch(hci_event_connection_request_get_link_type(packet)){
685                 case 0: //  SCO
686                 case 2: // eSCO
687                     hci_event_connection_request_get_bd_addr(packet, event_addr);
688                     hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
689                     if (!hfp_connection) break;
690                     if (hci_event_connection_request_get_link_type(packet) == 2){
691                         hfp_connection->hf_accept_sco = 2;
692                     } else {
693                         hfp_connection->hf_accept_sco = 1;
694                     }
695                     log_info("hf accept sco %u\n", hfp_connection->hf_accept_sco);
696                     sco_establishment_active = hfp_connection;
697                     if (!hfp_hf_run_for_context) break;
698                     (*hfp_hf_run_for_context)(hfp_connection);
699                     break;
700                 default:
701                     break;
702             }
703             break;
704 
705         case HCI_EVENT_COMMAND_STATUS:
706             if (hci_event_command_status_get_command_opcode(packet) == hci_setup_synchronous_connection.opcode) {
707                 if (sco_establishment_active == NULL) break;
708                 status = hci_event_command_status_get_status(packet);
709                 if (status == ERROR_CODE_SUCCESS) break;
710 
711                 hfp_connection = sco_establishment_active;
712                 if (hfp_handle_failed_sco_connection(status)) break;
713                 hfp_connection->establish_audio_connection = 0;
714                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
715                 hfp_emit_sco_event(hfp_connection, status, 0, hfp_connection->remote_addr, hfp_connection->negotiated_codec);
716             }
717             break;
718 
719         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
720             if (sco_establishment_active == NULL) break;
721             hci_event_synchronous_connection_complete_get_bd_addr(packet, event_addr);
722             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
723             if (!hfp_connection) {
724                 log_error("HFP: connection does not exist for remote with addr %s.", bd_addr_to_str(event_addr));
725                 return;
726             }
727 
728             status = hci_event_synchronous_connection_complete_get_status(packet);
729             if (status != ERROR_CODE_SUCCESS){
730                 hfp_connection->hf_accept_sco = 0;
731                 if (hfp_handle_failed_sco_connection(status)) break;
732 
733                 hfp_connection->establish_audio_connection = 0;
734                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
735                 hfp_emit_sco_event(hfp_connection, status, 0, event_addr, hfp_connection->negotiated_codec);
736                 break;
737             }
738 
739             uint16_t sco_handle = hci_event_synchronous_connection_complete_get_handle(packet);
740             uint8_t  link_type = hci_event_synchronous_connection_complete_get_link_type(packet);
741             uint8_t  transmission_interval = hci_event_synchronous_connection_complete_get_transmission_interval(packet);  // measured in slots
742             uint8_t  retransmission_interval = hci_event_synchronous_connection_complete_get_retransmission_interval(packet);// measured in slots
743             uint16_t rx_packet_length = hci_event_synchronous_connection_complete_get_rx_packet_length(packet); // measured in bytes
744             uint16_t tx_packet_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet); // measured in bytes
745             uint8_t  air_mode = hci_event_synchronous_connection_complete_get_air_mode(packet);
746 
747             switch (link_type){
748                 case 0x00:
749                     log_info("SCO Connection established.");
750                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
751                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
752                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
753                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
754                     break;
755                 case 0x02:
756                     log_info("eSCO Connection established. \n");
757                     break;
758                 default:
759                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
760                     break;
761             }
762             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
763                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)\n", sco_handle,
764                  bd_addr_to_str(event_addr), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length, air_mode);
765 
766             // hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
767 
768             // if (!hfp_connection) {
769             //     log_error("SCO link created, hfp_connection for address %s not found.", bd_addr_to_str(event_addr));
770             //     break;
771             // }
772 
773             if (hfp_connection->state == HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){
774                 log_info("SCO about to disconnect: HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN");
775                 hfp_connection->state = HFP_W2_DISCONNECT_SCO;
776                 break;
777             }
778             hfp_connection->sco_handle = sco_handle;
779             hfp_connection->establish_audio_connection = 0;
780             hfp_connection->state = HFP_AUDIO_CONNECTION_ESTABLISHED;
781             hfp_emit_sco_event(hfp_connection, status, sco_handle, event_addr, hfp_connection->negotiated_codec);
782             break;
783         }
784 
785         case HCI_EVENT_DISCONNECTION_COMPLETE:
786             handle = little_endian_read_16(packet,3);
787             hfp_connection = get_hfp_connection_context_for_sco_handle(handle, local_role);
788 
789             if (!hfp_connection) break;
790 
791             hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID;
792             hfp_connection->release_audio_connection = 0;
793             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
794             hfp_emit_event(hfp_connection, HFP_SUBEVENT_AUDIO_CONNECTION_RELEASED, 0);
795 
796             if (hfp_connection->release_slc_connection){
797                 hfp_connection->release_slc_connection = 0;
798                 log_info("SCO disconnected, w2 disconnect RFCOMM\n");
799                 hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
800             }
801             break;
802 
803         default:
804             break;
805     }
806 }
807 
808 void hfp_handle_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
809     UNUSED(packet_type);
810     UNUSED(channel);    // ok: no channel
811     UNUSED(size);
812 
813     bd_addr_t event_addr;
814     uint16_t rfcomm_cid;
815     hfp_connection_t * hfp_connection = NULL;
816     uint8_t status;
817 
818     log_debug("HFP packet_handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
819 
820     switch (hci_event_packet_get_type(packet)) {
821 
822         case RFCOMM_EVENT_INCOMING_CONNECTION:
823             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
824             rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
825             hfp_connection = provide_hfp_connection_context_for_bd_addr(event_addr, local_role);
826             if (!hfp_connection){
827                 log_info("hfp: no memory to accept incoming connection - decline");
828                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
829                 return;
830             }
831             if (hfp_connection->state != HFP_IDLE) {
832                 log_error("hfp: incoming connection but not idle, reject");
833                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
834                 return;
835             }
836 
837             hfp_connection->rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
838             hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
839             rfcomm_accept_connection(hfp_connection->rfcomm_cid);
840             break;
841 
842         case RFCOMM_EVENT_CHANNEL_OPENED:
843             // data: event(8), len(8), status (8), address (48), handle(16), server channel(8), rfcomm_cid(16), max frame size(16)
844 
845             rfcomm_event_channel_opened_get_bd_addr(packet, event_addr);
846             status = rfcomm_event_channel_opened_get_status(packet);
847 
848             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
849             if (!hfp_connection || (hfp_connection->state != HFP_W4_RFCOMM_CONNECTED)) return;
850 
851             if (status) {
852                 hfp_emit_slc_connection_event(hfp_connection, status, rfcomm_event_channel_opened_get_con_handle(packet), event_addr);
853                 remove_hfp_connection_context(hfp_connection);
854             } else {
855                 hfp_connection->acl_handle = rfcomm_event_channel_opened_get_con_handle(packet);
856                 hfp_connection->rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
857                 bd_addr_copy(hfp_connection->remote_addr, event_addr);
858 
859                 switch (hfp_connection->state){
860                     case HFP_W4_RFCOMM_CONNECTED:
861                         hfp_connection->state = HFP_EXCHANGE_SUPPORTED_FEATURES;
862                         break;
863                     case HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN:
864                         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
865                         break;
866                     default:
867                         break;
868                 }
869                 rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
870             }
871             break;
872 
873         case RFCOMM_EVENT_CHANNEL_CLOSED:
874             rfcomm_cid = little_endian_read_16(packet,2);
875             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
876             if (!hfp_connection) break;
877             if (hfp_connection->state == HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART){
878                 hfp_connection->state = HFP_IDLE;
879                 hfp_establish_service_level_connection(hfp_connection->remote_addr, hfp_connection->service_uuid, local_role);
880                 break;
881             }
882 
883             hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
884             remove_hfp_connection_context(hfp_connection);
885             break;
886 
887         default:
888             break;
889     }
890 }
891 // translates command string into hfp_command_t CMD
892 
893 typedef struct {
894     const char * command;
895     hfp_command_t command_id;
896 } hfp_command_entry_t;
897 
898 static hfp_command_entry_t hfp_ag_commmand_table[] = {
899     { "AT+BAC=",   HFP_CMD_AVAILABLE_CODECS },
900     { "AT+BCC",    HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP },
901     { "AT+BCS=",   HFP_CMD_HF_CONFIRMED_CODEC },
902     { "AT+BIA=",   HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE, }, // +BIA:<enabled>,,<enabled>,,,<enabled>
903     { "AT+BIEV=",  HFP_CMD_HF_INDICATOR_STATUS },
904     { "AT+BIND=",  HFP_CMD_LIST_GENERIC_STATUS_INDICATORS },
905     { "AT+BIND=?", HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS },
906     { "AT+BIND?",  HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE },
907     { "AT+BINP",   HFP_CMD_HF_REQUEST_PHONE_NUMBER },
908     { "AT+BLDN",   HFP_CMD_REDIAL_LAST_NUMBER },
909     { "AT+BRSF=",  HFP_CMD_SUPPORTED_FEATURES },
910     { "AT+BTRH=",  HFP_CMD_RESPONSE_AND_HOLD_COMMAND },
911     { "AT+BTRH?",  HFP_CMD_RESPONSE_AND_HOLD_QUERY },
912     { "AT+BVRA=",  HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION },
913     { "AT+CCWA=",  HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION},
914     { "AT+CHLD=",  HFP_CMD_CALL_HOLD },
915     { "AT+CHLD=?", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
916     { "AT+CHUP",   HFP_CMD_HANG_UP_CALL },
917     { "AT+CIND=?", HFP_CMD_RETRIEVE_AG_INDICATORS },
918     { "AT+CIND?",  HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS },
919     { "AT+CLCC",   HFP_CMD_LIST_CURRENT_CALLS },
920     { "AT+CLIP=",  HFP_CMD_ENABLE_CLIP},
921     { "AT+CMEE=",  HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR},
922     { "AT+CMER=",  HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE },
923     { "AT+CNUM",   HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION },
924     { "AT+COPS=",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT },
925     { "AT+COPS?",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
926     { "AT+NREC=",  HFP_CMD_TURN_OFF_EC_AND_NR, },
927     { "AT+VGM=",   HFP_CMD_SET_MICROPHONE_GAIN },
928     { "AT+VGS=",   HFP_CMD_SET_SPEAKER_GAIN },
929     { "AT+VTS:",   HFP_CMD_TRANSMIT_DTMF_CODES },
930     { "ATA",       HFP_CMD_CALL_ANSWERED },
931 };
932 
933 static hfp_command_entry_t hfp_hf_commmand_table[] = {
934     { "+BCS:",  HFP_CMD_AG_SUGGESTED_CODEC },
935     { "+BIND:", HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS },
936     { "+BINP",  HFP_CMD_AG_SENT_PHONE_NUMBER },
937     { "+BRSF:", HFP_CMD_SUPPORTED_FEATURES },
938     { "+BSIR:", HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING },
939     { "+BTRH:", HFP_CMD_RESPONSE_AND_HOLD_STATUS },
940     { "+BVRA:", HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION },
941     { "+CCWA:", HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE, },
942     { "+CHLD:", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
943     { "+CIEV:", HFP_CMD_TRANSFER_AG_INDICATOR_STATUS},
944     { "+CIND:", HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC },
945     { "+CLCC:", HFP_CMD_LIST_CURRENT_CALLS },
946     { "+CLIP:", HFP_CMD_AG_SENT_CLIP_INFORMATION },
947     { "+CME ERROR:", HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR },
948     { "+CNUM:", HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION},
949     { "+COPS:", HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
950     { "+VGM:",  HFP_CMD_SET_MICROPHONE_GAIN },
951     { "+VGS:",  HFP_CMD_SET_SPEAKER_GAIN},
952     { "ERROR",  HFP_CMD_ERROR},
953     { "NOP",    HFP_CMD_NONE}, // dummy command used by unit tests
954     { "OK",     HFP_CMD_OK },
955     { "RING",   HFP_CMD_RING },
956 };
957 
958 static hfp_command_t parse_command(const char * line_buffer, int isHandsFree){
959 
960     // table lookup based on role
961     uint16_t num_entries;
962     hfp_command_entry_t * table;
963     if (isHandsFree == 0){
964         table = hfp_ag_commmand_table;
965         num_entries = sizeof(hfp_ag_commmand_table) / sizeof(hfp_command_entry_t);
966     } else {
967         table = hfp_hf_commmand_table;
968         num_entries = sizeof(hfp_hf_commmand_table) / sizeof(hfp_command_entry_t);
969     }
970     // binary search
971     uint16_t left = 0;
972     uint16_t right = num_entries - 1;
973     while (left <= right){
974         uint16_t middle = left + (right - left) / 2;
975         hfp_command_entry_t *entry = &table[middle];
976         int match = strcmp(line_buffer, entry->command);
977         if (match < 0){
978             // search term is lower than middle element
979             if (right == 0) break;
980             right = middle - 1;
981         } else if (match == 0){
982             return entry->command_id;
983         } else {
984             // search term is higher than middle element
985             left = middle + 1;
986         }
987     }
988 
989     // note: if parser in CMD_HEADER state would treats digits and maybe '+' as separator, match on "ATD" would work.
990     // note: phone number is currently expected in line_buffer[3..]
991     // prefix match on 'ATD', AG only
992     if ((isHandsFree == 0) && (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0)){
993         return HFP_CMD_CALL_PHONE_NUMBER;
994     }
995 
996     // Valid looking, but unknown commands/responses
997     if ((isHandsFree == 0) && (strncmp(line_buffer, "AT+", 3) == 0)){
998         return HFP_CMD_UNKNOWN;
999     }
1000 
1001     if ((isHandsFree != 0) && (strncmp(line_buffer, "+", 1) == 0)){
1002         return HFP_CMD_UNKNOWN;
1003     }
1004 
1005     return HFP_CMD_NONE;
1006 }
1007 
1008 static void hfp_parser_store_byte(hfp_connection_t * hfp_connection, uint8_t byte){
1009     if ((hfp_connection->line_size + 1 ) >= HFP_MAX_INDICATOR_DESC_SIZE) return;
1010     hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
1011     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1012 }
1013 static int hfp_parser_is_buffer_empty(hfp_connection_t * hfp_connection){
1014     return hfp_connection->line_size == 0;
1015 }
1016 
1017 static int hfp_parser_is_end_of_line(uint8_t byte){
1018     return (byte == '\n') || (byte == '\r');
1019 }
1020 
1021 static void hfp_parser_reset_line_buffer(hfp_connection_t *hfp_connection) {
1022     hfp_connection->line_size = 0;
1023 }
1024 
1025 static void hfp_parser_store_if_token(hfp_connection_t * hfp_connection, uint8_t byte){
1026     switch (byte){
1027         case ',':
1028 		case '-':
1029         case ';':
1030         case '(':
1031         case ')':
1032         case '\n':
1033         case '\r':
1034             break;
1035         default:
1036             hfp_parser_store_byte(hfp_connection, byte);
1037             break;
1038     }
1039 }
1040 
1041 static bool hfp_parser_is_separator( uint8_t byte){
1042     switch (byte){
1043         case ',':
1044 		case '-':
1045         case ';':
1046         case '\n':
1047         case '\r':
1048             return true;
1049         default:
1050             return false;
1051     }
1052 }
1053 
1054 static bool hfp_parse_byte(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1055 
1056     // handle doubles quotes
1057     if (byte == '"'){
1058         hfp_connection->parser_quoted = !hfp_connection->parser_quoted;
1059         return true;
1060     }
1061     if (hfp_connection->parser_quoted) {
1062         hfp_parser_store_byte(hfp_connection, byte);
1063         return true;
1064     }
1065 
1066     // ignore spaces outside command or double quotes (required e.g. for '+CME ERROR:..") command
1067     if ((byte == ' ') && (hfp_connection->parser_state != HFP_PARSER_CMD_HEADER)) return true;
1068 
1069     bool processed = true;
1070 
1071     switch (hfp_connection->parser_state) {
1072         case HFP_PARSER_CMD_HEADER:
1073             switch (byte) {
1074                 case '\n':
1075                 case '\r':
1076                 case ';':
1077                     // ignore separator
1078                     break;
1079                 case ':':
1080                 case '?':
1081                     // store separator
1082                     hfp_parser_store_byte(hfp_connection, byte);
1083                     break;
1084                 case '=':
1085                     // equal sign: remember and wait for next char to decided between '=?' and '=\?'
1086                     hfp_connection->found_equal_sign = true;
1087                     hfp_parser_store_byte(hfp_connection, byte);
1088                     return true;
1089                 default:
1090                     // store if not lookahead
1091                     if (!hfp_connection->found_equal_sign) {
1092                         hfp_parser_store_byte(hfp_connection, byte);
1093                         return true;
1094                     }
1095                     // mark as lookahead
1096                     processed = false;
1097                     break;
1098             }
1099 
1100             // ignore empty tokens
1101             if (hfp_parser_is_buffer_empty(hfp_connection)) return true;
1102 
1103             // parse
1104             hfp_connection->command = parse_command((char *)hfp_connection->line_buffer, isHandsFree);
1105 
1106             // pick +CIND version based on connection state: descriptions during SLC vs. states later
1107             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC){
1108                 switch(hfp_connection->state){
1109                     case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1110                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
1111                         break;
1112                     case HFP_W4_RETRIEVE_INDICATORS:
1113                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS;
1114                         break;
1115                     default:
1116                         hfp_connection->command = HFP_CMD_UNKNOWN;
1117                         break;
1118                 }
1119             }
1120 
1121             log_info("command string '%s', handsfree %u -> cmd id %u", (char *)hfp_connection->line_buffer, isHandsFree, hfp_connection->command);
1122 
1123             // next state
1124             hfp_connection->found_equal_sign = false;
1125             hfp_parser_reset_line_buffer(hfp_connection);
1126             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1127 
1128             return processed;
1129 
1130         case HFP_PARSER_CMD_SEQUENCE:
1131             // handle empty fields
1132             if ((byte == ',' ) && (hfp_connection->line_size == 0)){
1133                 hfp_connection->line_buffer[0] = 0;
1134                 hfp_connection->ignore_value = 1;
1135                 parse_sequence(hfp_connection);
1136                 return true;
1137             }
1138 
1139             hfp_parser_store_if_token(hfp_connection, byte);
1140             if (!hfp_parser_is_separator(byte)) return true;
1141 
1142             // ignore empty tokens
1143             if (hfp_parser_is_buffer_empty(hfp_connection) && (hfp_connection->ignore_value == 0)) return true;
1144 
1145             parse_sequence(hfp_connection);
1146 
1147             hfp_parser_reset_line_buffer(hfp_connection);
1148 
1149             switch (hfp_connection->command){
1150                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1151                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1152                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1153                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1154                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1155                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1156                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1157                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1158                 case HFP_CMD_HF_INDICATOR_STATUS:
1159                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
1160                     break;
1161                 default:
1162                     break;
1163             }
1164             return true;
1165 
1166         case HFP_PARSER_SECOND_ITEM:
1167 
1168             hfp_parser_store_if_token(hfp_connection, byte);
1169             if (!hfp_parser_is_separator(byte)) return true;
1170 
1171             switch (hfp_connection->command){
1172                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1173                     log_info("format %s, ", hfp_connection->line_buffer);
1174                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1175                     break;
1176                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1177                     log_info("format %s \n", hfp_connection->line_buffer);
1178                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1179                     break;
1180                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1181                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1182                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1183                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1184                     break;
1185                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1186                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1187                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1188                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1189                     break;
1190                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1191                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer);
1192                     log_info("%s, ", hfp_connection->line_buffer);
1193                     break;
1194                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1195                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1196                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1197                     hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1198                     break;
1199                 case HFP_CMD_HF_INDICATOR_STATUS:
1200                     hfp_connection->parser_indicator_value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1201                     break;
1202                 default:
1203                     break;
1204             }
1205 
1206             hfp_parser_reset_line_buffer(hfp_connection);
1207 
1208             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
1209 
1210             return true;
1211 
1212         case HFP_PARSER_THIRD_ITEM:
1213 
1214             hfp_parser_store_if_token(hfp_connection, byte);
1215             if (!hfp_parser_is_separator(byte)) return true;
1216 
1217             switch (hfp_connection->command){
1218                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1219                     strncpy(hfp_connection->network_operator.name, (char *)hfp_connection->line_buffer, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE);
1220                     hfp_connection->network_operator.name[HFP_MAX_NETWORK_OPERATOR_NAME_SIZE - 1] = 0;
1221                     log_info("name %s\n", hfp_connection->line_buffer);
1222                     break;
1223                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1224                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer);
1225                     hfp_next_indicators_index(hfp_connection);
1226                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1227                     log_info("%s)\n", hfp_connection->line_buffer);
1228                     break;
1229                 default:
1230                     break;
1231             }
1232 
1233             hfp_parser_reset_line_buffer(hfp_connection);
1234 
1235             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){
1236                 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1237             } else {
1238                 hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1239             }
1240             return true;
1241 
1242         default:
1243             btstack_assert(false);
1244             return true;
1245     }
1246 }
1247 
1248 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1249     bool processed = false;
1250     while (!processed){
1251         processed = hfp_parse_byte(hfp_connection, byte, isHandsFree);
1252     }
1253     // reset parser state on end-of-line
1254     if (hfp_parser_is_end_of_line(byte)){
1255         hfp_connection->parser_item_index = 0;
1256         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1257     }
1258 }
1259 
1260 static void parse_sequence(hfp_connection_t * hfp_connection){
1261     int value;
1262     switch (hfp_connection->command){
1263         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1264             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1265             int i;
1266             switch (hfp_connection->parser_item_index){
1267                 case 0:
1268                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1269                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1270                             hfp_connection->parser_indicator_index = i;
1271                             break;
1272                         }
1273                     }
1274                     break;
1275                 case 1:
1276                     if (hfp_connection->parser_indicator_index <0) break;
1277                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1278                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1279                      hfp_connection->parser_item_index, value);
1280                     break;
1281                 default:
1282                     break;
1283             }
1284             hfp_next_indicators_index(hfp_connection);
1285             break;
1286 
1287         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1288             switch(hfp_connection->parser_item_index){
1289                 case 0:
1290                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1291                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1292                     break;
1293                 case 1:
1294                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1295                     hfp_connection->bnip_type = value;
1296                     break;
1297                 default:
1298                     break;
1299             }
1300             // index > 2 are ignored in switch above
1301             hfp_connection->parser_item_index++;
1302             break;
1303         case HFP_CMD_LIST_CURRENT_CALLS:
1304             switch(hfp_connection->parser_item_index){
1305                 case 0:
1306                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1307                     hfp_connection->clcc_idx = value;
1308                     break;
1309                 case 1:
1310                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1311                     hfp_connection->clcc_dir = value;
1312                     break;
1313                 case 2:
1314                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1315                     hfp_connection->clcc_status = value;
1316                     break;
1317                 case 3:
1318                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1319                     hfp_connection->clcc_mode = value;
1320                     break;
1321                 case 4:
1322                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1323                     hfp_connection->clcc_mpty = value;
1324                     break;
1325                 case 5:
1326                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1327                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1328                     break;
1329                 case 6:
1330                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1331                     hfp_connection->bnip_type = value;
1332                     break;
1333                 default:
1334                     break;
1335             }
1336             // index > 6 are ignored in switch above
1337             hfp_connection->parser_item_index++;
1338             break;
1339         case HFP_CMD_SET_MICROPHONE_GAIN:
1340             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1341             hfp_connection->microphone_gain = value;
1342             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1343             break;
1344         case HFP_CMD_SET_SPEAKER_GAIN:
1345             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1346             hfp_connection->speaker_gain = value;
1347             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1348             break;
1349         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1350             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1351             hfp_connection->ag_activate_voice_recognition = value;
1352             log_info("hfp parse HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION %d\n", value);
1353             break;
1354         case HFP_CMD_TURN_OFF_EC_AND_NR:
1355             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1356             hfp_connection->ag_echo_and_noise_reduction = value;
1357             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1358             break;
1359         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1360             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1361             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1362             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1363             break;
1364         case HFP_CMD_HF_CONFIRMED_CODEC:
1365             hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer);
1366             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1367             break;
1368         case HFP_CMD_AG_SUGGESTED_CODEC:
1369             hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer);
1370             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1371             break;
1372         case HFP_CMD_SUPPORTED_FEATURES:
1373             hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer);
1374             log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features);
1375             break;
1376         case HFP_CMD_AVAILABLE_CODECS:
1377             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1378             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1379             hfp_next_codec_index(hfp_connection);
1380             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1381             break;
1382         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1383             strncpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name,  (char *)hfp_connection->line_buffer, HFP_MAX_INDICATOR_DESC_SIZE);
1384             hfp_connection->ag_indicators[hfp_connection->parser_item_index].name[HFP_MAX_INDICATOR_DESC_SIZE-1] = 0;
1385             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1386             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1387             break;
1388         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1389             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1390             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer);
1391             hfp_next_indicators_index(hfp_connection);
1392             break;
1393         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1394             hfp_next_indicators_index(hfp_connection);
1395             if (hfp_connection->parser_item_index != 4) break;
1396             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1397             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1398             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1399             break;
1400         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1401             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1402             if (hfp_connection->line_size > 2 ) break;
1403             strncpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE);
1404             hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name[HFP_CALL_SERVICE_SIZE - 1] = 0;
1405             hfp_next_remote_call_services_index(hfp_connection);
1406             break;
1407         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1408         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1409             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1410             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1411             hfp_next_indicators_index(hfp_connection);
1412             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1413             break;
1414         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1415             // HF parses inital AG gen. ind. state
1416             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1417             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1418             break;
1419         case HFP_CMD_HF_INDICATOR_STATUS:
1420             hfp_connection->parser_indicator_index = hfp_parse_indicator_index(hfp_connection);
1421             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1422             break;
1423         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1424             // AG parses new gen. ind. state
1425             if (hfp_connection->ignore_value){
1426                 hfp_connection->ignore_value = 0;
1427                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1428                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1429             }
1430             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1431                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1432                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1433             } else {
1434                 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1435                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1436                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1437                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1438             }
1439             hfp_next_indicators_index(hfp_connection);
1440             break;
1441         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1442             // indicators are indexed starting with 1
1443             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1444             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1445             break;
1446         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1447             hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1448             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1449             break;
1450         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1451             if (hfp_connection->line_buffer[0] == '3'){
1452                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1453                 break;
1454             }
1455             // TODO emit ERROR, wrong format
1456             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1457             break;
1458         case HFP_CMD_ERROR:
1459             break;
1460         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1461             hfp_connection->extended_audio_gateway_error = 1;
1462             hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1463             break;
1464         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1465             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1466             hfp_connection->ok_pending = 1;
1467             hfp_connection->extended_audio_gateway_error = 0;
1468             break;
1469         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1470         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1471         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1472             strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1473             hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1474             break;
1475         case HFP_CMD_CALL_HOLD:
1476             hfp_connection->ag_call_hold_action = hfp_connection->line_buffer[0] - '0';
1477             if (hfp_connection->line_buffer[1] != '\0'){
1478                 hfp_connection->call_index = btstack_atoi((char *)&hfp_connection->line_buffer[1]);
1479             }
1480             break;
1481         case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1482             hfp_connection->ag_response_and_hold_action = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1483             break;
1484         case HFP_CMD_TRANSMIT_DTMF_CODES:
1485             hfp_connection->ag_dtmf_code = hfp_connection->line_buffer[0];
1486             break;
1487         case HFP_CMD_ENABLE_CLIP:
1488             hfp_connection->clip_enabled = hfp_connection->line_buffer[0] != '0';
1489             break;
1490         case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1491             hfp_connection->call_waiting_notification_enabled = hfp_connection->line_buffer[0] != '0';
1492             break;
1493         default:
1494             break;
1495     }
1496 }
1497 
1498 static void hfp_handle_start_sdp_client_query(void * context){
1499     UNUSED(context);
1500 
1501     btstack_linked_list_iterator_t it;
1502     btstack_linked_list_iterator_init(&it, &hfp_connections);
1503     while (btstack_linked_list_iterator_has_next(&it)){
1504         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1505 
1506         if (connection->state != HFP_W2_SEND_SDP_QUERY) continue;
1507 
1508         connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1509         sdp_query_context.local_role = connection->local_role;
1510         (void)memcpy(sdp_query_context.remote_address, connection->remote_addr, 6);
1511         sdp_client_query_rfcomm_channel_and_name_for_uuid(&handle_query_rfcomm_event, connection->remote_addr, connection->service_uuid);
1512         return;
1513     }
1514 }
1515 
1516 void hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){
1517     hfp_connection_t * hfp_connection = provide_hfp_connection_context_for_bd_addr(bd_addr, local_role);
1518     log_info("hfp_connect %s, hfp_connection %p", bd_addr_to_str(bd_addr), hfp_connection);
1519 
1520     if (!hfp_connection) {
1521         log_error("hfp_establish_service_level_connection for addr %s failed", bd_addr_to_str(bd_addr));
1522         return;
1523     }
1524     switch (hfp_connection->state){
1525         case HFP_W2_DISCONNECT_RFCOMM:
1526             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1527             return;
1528         case HFP_W4_RFCOMM_DISCONNECTED:
1529             hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART;
1530             return;
1531         case HFP_IDLE:
1532             (void)memcpy(hfp_connection->remote_addr, bd_addr, 6);
1533             hfp_connection->state = HFP_W2_SEND_SDP_QUERY;
1534             hfp_connection->service_uuid = service_uuid;
1535 
1536             hfp_handle_sdp_client_query_request.callback = &hfp_handle_start_sdp_client_query;
1537             // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1538             (void) sdp_client_register_query_callback(&hfp_handle_sdp_client_query_request);
1539             break;
1540         default:
1541             break;
1542     }
1543 }
1544 
1545 void hfp_release_service_level_connection(hfp_connection_t * hfp_connection){
1546     if (!hfp_connection) return;
1547     hfp_release_audio_connection(hfp_connection);
1548 
1549     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1550         hfp_connection->state = HFP_IDLE;
1551         return;
1552     }
1553 
1554     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1555         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1556         return;
1557     }
1558 
1559     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1560         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1561         return;
1562     }
1563 
1564     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1565         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1566         return;
1567     }
1568 
1569     // HFP_W4_SCO_DISCONNECTED or later
1570     hfp_connection->release_slc_connection = 1;
1571 }
1572 
1573 void hfp_release_audio_connection(hfp_connection_t * hfp_connection){
1574     if (!hfp_connection) return;
1575     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
1576     hfp_connection->release_audio_connection = 1;
1577 }
1578 
1579 static const struct link_settings {
1580     const uint16_t max_latency;
1581     const uint8_t  retransmission_effort;
1582     const uint16_t packet_types;
1583     const bool     eSCO;
1584     const uint8_t  codec;
1585 } hfp_link_settings [] = {
1586     { 0xffff, 0xff, SCO_PACKET_TYPES_HV1,  false, HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_D0
1587     { 0xffff, 0xff, SCO_PACKET_TYPES_HV3,  false, HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_D1
1588     { 0x0007, 0x01, SCO_PACKET_TYPES_EV3,  true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S1
1589     { 0x0007, 0x01, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S2
1590     { 0x000a, 0x01, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S3
1591     { 0x000c, 0x02, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S4
1592     { 0x0008, 0x02, SCO_PACKET_TYPES_EV3,  true,  HFP_CODEC_MSBC }, // HFP_LINK_SETTINGS_T1
1593     { 0x000d, 0x02, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_MSBC }  // HFP_LINK_SETTINGS_T2
1594 };
1595 
1596 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){
1597     // all packet types, fixed bandwidth
1598     int setting = hfp_connection->link_setting;
1599     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1600     sco_establishment_active = hfp_connection;
1601     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1602     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1603         sco_voice_setting = 0x0043; // Transparent data
1604     }
1605     // get packet types - bits 6-9 are 'don't allow'
1606     uint16_t packet_types = hfp_link_settings[setting].packet_types ^ 0x03c0;
1607     hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency,
1608         sco_voice_setting, hfp_link_settings[setting].retransmission_effort, packet_types);
1609 }
1610 
1611 void hfp_set_hf_callback(btstack_packet_handler_t callback){
1612     hfp_hf_callback = callback;
1613 }
1614 
1615 void hfp_set_ag_callback(btstack_packet_handler_t callback){
1616     hfp_ag_callback = callback;
1617 }
1618 
1619 void hfp_set_ag_rfcomm_packet_handler(btstack_packet_handler_t handler){
1620     hfp_ag_rfcomm_packet_handler = handler;
1621 }
1622 
1623 void hfp_set_hf_rfcomm_packet_handler(btstack_packet_handler_t handler){
1624     hfp_hf_rfcomm_packet_handler = handler;
1625 }
1626 
1627 void hfp_set_hf_run_for_context(void (*callback)(hfp_connection_t * hfp_connection)){
1628     hfp_hf_run_for_context = callback;
1629 }
1630 
1631 void hfp_init(void){
1632     hfp_allowed_sco_packet_types = SCO_PACKET_TYPES_ALL;
1633 }
1634 
1635 void hfp_set_sco_packet_types(uint16_t packet_types){
1636     hfp_allowed_sco_packet_types = packet_types;
1637 }
1638 
1639 uint16_t hfp_get_sco_packet_types(void){
1640     return hfp_allowed_sco_packet_types;
1641 }
1642 
1643 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){
1644     int8_t setting = (int8_t) current_setting;
1645     bool can_use_eSCO = local_eSCO_supported && remote_eSCO_supported;
1646     while (setting > 0){
1647         setting--;
1648         // skip if eSCO required but not available
1649         if (hfp_link_settings[setting].eSCO && !can_use_eSCO) continue;
1650         // skip if S4 but not supported
1651         if ((setting == (int8_t) HFP_LINK_SETTINGS_S4) && !eSCO_S4_supported) continue;
1652         // skip wrong codec
1653         if ( hfp_link_settings[setting].codec != negotiated_codec) continue;
1654         // skip disabled packet types
1655         uint16_t required_packet_types = hfp_link_settings[setting].packet_types;
1656         uint16_t allowed_packet_types  = hfp_allowed_sco_packet_types;
1657         if ((required_packet_types & allowed_packet_types) == 0) continue;
1658 
1659         // found matching setting
1660         return (hfp_link_settings_t) setting;
1661     }
1662     return HFP_LINK_SETTINGS_NONE;
1663 }
1664 
1665 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){
1666     bool local_eSCO_supported  = hci_extended_sco_link_supported();
1667     bool remote_eSCO_supported = hci_remote_esco_supported(hfp_connection->acl_handle);
1668     uint8_t negotiated_codec   = hfp_connection->negotiated_codec;
1669     return  hfp_next_link_setting(current_setting, local_eSCO_supported, remote_eSCO_supported, eSCO_S4_supported, negotiated_codec);
1670 }
1671 
1672 void hfp_init_link_settings(hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported){
1673     // get highest possible link setting
1674     hfp_connection->link_setting = hfp_next_link_setting_for_connection(HFP_LINK_SETTINGS_NONE, hfp_connection, eSCO_S4_supported);
1675     log_info("hfp_init_link_settings: %u", hfp_connection->link_setting);
1676 }
1677 
1678 #define HFP_HF_RX_DEBUG_PRINT_LINE 80
1679 
1680 void hfp_log_rfcomm_message(const char * tag, uint8_t * packet, uint16_t size){
1681 #ifdef ENABLE_LOG_INFO
1682     // encode \n\r
1683     char printable[HFP_HF_RX_DEBUG_PRINT_LINE+2];
1684     int i = 0;
1685     int pos;
1686     for (pos=0 ; (pos < size) && (i < (HFP_HF_RX_DEBUG_PRINT_LINE - 3)) ; pos++){
1687         switch (packet[pos]){
1688             case '\n':
1689                 printable[i++] = '\\';
1690                 printable[i++] = 'n';
1691                 break;
1692             case '\r':
1693                 printable[i++] = '\\';
1694                 printable[i++] = 'r';
1695                 break;
1696             default:
1697                 printable[i++] = packet[pos];
1698                 break;
1699         }
1700     }
1701     printable[i] = 0;
1702     log_info("%s: '%s'", tag, printable);
1703 #endif
1704 }
1705