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