xref: /btstack/src/classic/hfp.c (revision a8d51f092f1b660d0f6921369ad2bc3f9368296c)
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 
746             switch (link_type){
747                 case 0x00:
748                     log_info("SCO Connection established.");
749                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
750                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
751                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
752                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
753                     break;
754                 case 0x02:
755                     log_info("eSCO Connection established. \n");
756                     break;
757                 default:
758                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
759                     break;
760             }
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,
765                  hci_event_synchronous_connection_complete_get_air_mode(packet));
766 
767             if (hfp_connection->state == HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){
768                 log_info("SCO about to disconnect: HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN");
769                 hfp_connection->state = HFP_W2_DISCONNECT_SCO;
770                 break;
771             }
772             hfp_connection->sco_handle = sco_handle;
773             hfp_connection->establish_audio_connection = 0;
774             hfp_connection->state = HFP_AUDIO_CONNECTION_ESTABLISHED;
775             hfp_emit_sco_event(hfp_connection, status, sco_handle, event_addr, hfp_connection->negotiated_codec);
776             break;
777         }
778 
779         case HCI_EVENT_DISCONNECTION_COMPLETE:
780             handle = little_endian_read_16(packet,3);
781             hfp_connection = get_hfp_connection_context_for_sco_handle(handle, local_role);
782 
783             if (!hfp_connection) break;
784 
785             hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID;
786             hfp_connection->release_audio_connection = 0;
787             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
788             hfp_emit_event(hfp_connection, HFP_SUBEVENT_AUDIO_CONNECTION_RELEASED, 0);
789 
790             if (hfp_connection->release_slc_connection){
791                 hfp_connection->release_slc_connection = 0;
792                 log_info("SCO disconnected, w2 disconnect RFCOMM\n");
793                 hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
794             }
795             break;
796 
797         default:
798             break;
799     }
800 }
801 
802 void hfp_handle_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
803     UNUSED(packet_type);
804     UNUSED(channel);    // ok: no channel
805     UNUSED(size);
806 
807     bd_addr_t event_addr;
808     uint16_t rfcomm_cid;
809     hfp_connection_t * hfp_connection = NULL;
810     uint8_t status;
811 
812     log_debug("HFP packet_handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
813 
814     switch (hci_event_packet_get_type(packet)) {
815 
816         case RFCOMM_EVENT_INCOMING_CONNECTION:
817             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
818             rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
819             hfp_connection = provide_hfp_connection_context_for_bd_addr(event_addr, local_role);
820             if (!hfp_connection){
821                 log_info("hfp: no memory to accept incoming connection - decline");
822                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
823                 return;
824             }
825             if (hfp_connection->state != HFP_IDLE) {
826                 log_error("hfp: incoming connection but not idle, reject");
827                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
828                 return;
829             }
830 
831             hfp_connection->rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
832             hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
833             rfcomm_accept_connection(hfp_connection->rfcomm_cid);
834             break;
835 
836         case RFCOMM_EVENT_CHANNEL_OPENED:
837             // data: event(8), len(8), status (8), address (48), handle(16), server channel(8), rfcomm_cid(16), max frame size(16)
838 
839             rfcomm_event_channel_opened_get_bd_addr(packet, event_addr);
840             status = rfcomm_event_channel_opened_get_status(packet);
841 
842             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
843             if (!hfp_connection || (hfp_connection->state != HFP_W4_RFCOMM_CONNECTED)) return;
844 
845             if (status) {
846                 hfp_emit_slc_connection_event(hfp_connection, status, rfcomm_event_channel_opened_get_con_handle(packet), event_addr);
847                 remove_hfp_connection_context(hfp_connection);
848             } else {
849                 hfp_connection->acl_handle = rfcomm_event_channel_opened_get_con_handle(packet);
850                 hfp_connection->rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
851                 bd_addr_copy(hfp_connection->remote_addr, event_addr);
852 
853                 switch (hfp_connection->state){
854                     case HFP_W4_RFCOMM_CONNECTED:
855                         hfp_connection->state = HFP_EXCHANGE_SUPPORTED_FEATURES;
856                         break;
857                     case HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN:
858                         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
859                         break;
860                     default:
861                         break;
862                 }
863                 rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
864             }
865             break;
866 
867         case RFCOMM_EVENT_CHANNEL_CLOSED:
868             rfcomm_cid = little_endian_read_16(packet,2);
869             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
870             if (!hfp_connection) break;
871             if (hfp_connection->state == HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART){
872                 hfp_connection->state = HFP_IDLE;
873                 hfp_establish_service_level_connection(hfp_connection->remote_addr, hfp_connection->service_uuid, local_role);
874                 break;
875             }
876 
877             hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
878             remove_hfp_connection_context(hfp_connection);
879             break;
880 
881         default:
882             break;
883     }
884 }
885 // translates command string into hfp_command_t CMD
886 
887 typedef struct {
888     const char * command;
889     hfp_command_t command_id;
890 } hfp_command_entry_t;
891 
892 static hfp_command_entry_t hfp_ag_commmand_table[] = {
893     { "AT+BAC=",   HFP_CMD_AVAILABLE_CODECS },
894     { "AT+BCC",    HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP },
895     { "AT+BCS=",   HFP_CMD_HF_CONFIRMED_CODEC },
896     { "AT+BIA=",   HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE, }, // +BIA:<enabled>,,<enabled>,,,<enabled>
897     { "AT+BIEV=",  HFP_CMD_HF_INDICATOR_STATUS },
898     { "AT+BIND=",  HFP_CMD_LIST_GENERIC_STATUS_INDICATORS },
899     { "AT+BIND=?", HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS },
900     { "AT+BIND?",  HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE },
901     { "AT+BINP",   HFP_CMD_HF_REQUEST_PHONE_NUMBER },
902     { "AT+BLDN",   HFP_CMD_REDIAL_LAST_NUMBER },
903     { "AT+BRSF=",  HFP_CMD_SUPPORTED_FEATURES },
904     { "AT+BTRH=",  HFP_CMD_RESPONSE_AND_HOLD_COMMAND },
905     { "AT+BTRH?",  HFP_CMD_RESPONSE_AND_HOLD_QUERY },
906     { "AT+BVRA=",  HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION },
907     { "AT+CCWA=",  HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION},
908     { "AT+CHLD=",  HFP_CMD_CALL_HOLD },
909     { "AT+CHLD=?", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
910     { "AT+CHUP",   HFP_CMD_HANG_UP_CALL },
911     { "AT+CIND=?", HFP_CMD_RETRIEVE_AG_INDICATORS },
912     { "AT+CIND?",  HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS },
913     { "AT+CLCC",   HFP_CMD_LIST_CURRENT_CALLS },
914     { "AT+CLIP=",  HFP_CMD_ENABLE_CLIP},
915     { "AT+CMEE=",  HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR},
916     { "AT+CMER=",  HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE },
917     { "AT+CNUM",   HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION },
918     { "AT+COPS=",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT },
919     { "AT+COPS?",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
920     { "AT+NREC=",  HFP_CMD_TURN_OFF_EC_AND_NR, },
921     { "AT+VGM=",   HFP_CMD_SET_MICROPHONE_GAIN },
922     { "AT+VGS=",   HFP_CMD_SET_SPEAKER_GAIN },
923     { "AT+VTS:",   HFP_CMD_TRANSMIT_DTMF_CODES },
924     { "ATA",       HFP_CMD_CALL_ANSWERED },
925 };
926 
927 static hfp_command_entry_t hfp_hf_commmand_table[] = {
928     { "+BCS:",  HFP_CMD_AG_SUGGESTED_CODEC },
929     { "+BIND:", HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS },
930     { "+BINP",  HFP_CMD_AG_SENT_PHONE_NUMBER },
931     { "+BRSF:", HFP_CMD_SUPPORTED_FEATURES },
932     { "+BSIR:", HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING },
933     { "+BTRH:", HFP_CMD_RESPONSE_AND_HOLD_STATUS },
934     { "+BVRA:", HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION },
935     { "+CCWA:", HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE, },
936     { "+CHLD:", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
937     { "+CIEV:", HFP_CMD_TRANSFER_AG_INDICATOR_STATUS},
938     { "+CIND:", HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC },
939     { "+CLCC:", HFP_CMD_LIST_CURRENT_CALLS },
940     { "+CLIP:", HFP_CMD_AG_SENT_CLIP_INFORMATION },
941     { "+CME ERROR:", HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR },
942     { "+CNUM:", HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION},
943     { "+COPS:", HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
944     { "+VGM:",  HFP_CMD_SET_MICROPHONE_GAIN },
945     { "+VGS:",  HFP_CMD_SET_SPEAKER_GAIN},
946     { "ERROR",  HFP_CMD_ERROR},
947     { "NOP",    HFP_CMD_NONE}, // dummy command used by unit tests
948     { "OK",     HFP_CMD_OK },
949     { "RING",   HFP_CMD_RING },
950 };
951 
952 static hfp_command_t parse_command(const char * line_buffer, int isHandsFree){
953 
954     // table lookup based on role
955     uint16_t num_entries;
956     hfp_command_entry_t * table;
957     if (isHandsFree == 0){
958         table = hfp_ag_commmand_table;
959         num_entries = sizeof(hfp_ag_commmand_table) / sizeof(hfp_command_entry_t);
960     } else {
961         table = hfp_hf_commmand_table;
962         num_entries = sizeof(hfp_hf_commmand_table) / sizeof(hfp_command_entry_t);
963     }
964     // binary search
965     uint16_t left = 0;
966     uint16_t right = num_entries - 1;
967     while (left <= right){
968         uint16_t middle = left + (right - left) / 2;
969         hfp_command_entry_t *entry = &table[middle];
970         int match = strcmp(line_buffer, entry->command);
971         if (match < 0){
972             // search term is lower than middle element
973             if (right == 0) break;
974             right = middle - 1;
975         } else if (match == 0){
976             return entry->command_id;
977         } else {
978             // search term is higher than middle element
979             left = middle + 1;
980         }
981     }
982 
983     // note: if parser in CMD_HEADER state would treats digits and maybe '+' as separator, match on "ATD" would work.
984     // note: phone number is currently expected in line_buffer[3..]
985     // prefix match on 'ATD', AG only
986     if ((isHandsFree == 0) && (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0)){
987         return HFP_CMD_CALL_PHONE_NUMBER;
988     }
989 
990     // Valid looking, but unknown commands/responses
991     if ((isHandsFree == 0) && (strncmp(line_buffer, "AT+", 3) == 0)){
992         return HFP_CMD_UNKNOWN;
993     }
994 
995     if ((isHandsFree != 0) && (strncmp(line_buffer, "+", 1) == 0)){
996         return HFP_CMD_UNKNOWN;
997     }
998 
999     return HFP_CMD_NONE;
1000 }
1001 
1002 static void hfp_parser_store_byte(hfp_connection_t * hfp_connection, uint8_t byte){
1003     if ((hfp_connection->line_size + 1 ) >= HFP_MAX_INDICATOR_DESC_SIZE) return;
1004     hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
1005     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1006 }
1007 static int hfp_parser_is_buffer_empty(hfp_connection_t * hfp_connection){
1008     return hfp_connection->line_size == 0;
1009 }
1010 
1011 static int hfp_parser_is_end_of_line(uint8_t byte){
1012     return (byte == '\n') || (byte == '\r');
1013 }
1014 
1015 static void hfp_parser_reset_line_buffer(hfp_connection_t *hfp_connection) {
1016     hfp_connection->line_size = 0;
1017 }
1018 
1019 static void hfp_parser_store_if_token(hfp_connection_t * hfp_connection, uint8_t byte){
1020     switch (byte){
1021         case ',':
1022 		case '-':
1023         case ';':
1024         case '(':
1025         case ')':
1026         case '\n':
1027         case '\r':
1028             break;
1029         default:
1030             hfp_parser_store_byte(hfp_connection, byte);
1031             break;
1032     }
1033 }
1034 
1035 static bool hfp_parser_is_separator( uint8_t byte){
1036     switch (byte){
1037         case ',':
1038 		case '-':
1039         case ';':
1040         case '\n':
1041         case '\r':
1042             return true;
1043         default:
1044             return false;
1045     }
1046 }
1047 
1048 static bool hfp_parse_byte(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1049 
1050     // handle doubles quotes
1051     if (byte == '"'){
1052         hfp_connection->parser_quoted = !hfp_connection->parser_quoted;
1053         return true;
1054     }
1055     if (hfp_connection->parser_quoted) {
1056         hfp_parser_store_byte(hfp_connection, byte);
1057         return true;
1058     }
1059 
1060     // ignore spaces outside command or double quotes (required e.g. for '+CME ERROR:..") command
1061     if ((byte == ' ') && (hfp_connection->parser_state != HFP_PARSER_CMD_HEADER)) return true;
1062 
1063     bool processed = true;
1064 
1065     switch (hfp_connection->parser_state) {
1066         case HFP_PARSER_CMD_HEADER:
1067             switch (byte) {
1068                 case '\n':
1069                 case '\r':
1070                 case ';':
1071                     // ignore separator
1072                     break;
1073                 case ':':
1074                 case '?':
1075                     // store separator
1076                     hfp_parser_store_byte(hfp_connection, byte);
1077                     break;
1078                 case '=':
1079                     // equal sign: remember and wait for next char to decided between '=?' and '=\?'
1080                     hfp_connection->found_equal_sign = true;
1081                     hfp_parser_store_byte(hfp_connection, byte);
1082                     return true;
1083                 default:
1084                     // store if not lookahead
1085                     if (!hfp_connection->found_equal_sign) {
1086                         hfp_parser_store_byte(hfp_connection, byte);
1087                         return true;
1088                     }
1089                     // mark as lookahead
1090                     processed = false;
1091                     break;
1092             }
1093 
1094             // ignore empty tokens
1095             if (hfp_parser_is_buffer_empty(hfp_connection)) return true;
1096 
1097             // parse
1098             hfp_connection->command = parse_command((char *)hfp_connection->line_buffer, isHandsFree);
1099 
1100             // pick +CIND version based on connection state: descriptions during SLC vs. states later
1101             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC){
1102                 switch(hfp_connection->state){
1103                     case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1104                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
1105                         break;
1106                     case HFP_W4_RETRIEVE_INDICATORS:
1107                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS;
1108                         break;
1109                     default:
1110                         hfp_connection->command = HFP_CMD_UNKNOWN;
1111                         break;
1112                 }
1113             }
1114 
1115             log_info("command string '%s', handsfree %u -> cmd id %u", (char *)hfp_connection->line_buffer, isHandsFree, hfp_connection->command);
1116 
1117             // next state
1118             hfp_connection->found_equal_sign = false;
1119             hfp_parser_reset_line_buffer(hfp_connection);
1120             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1121 
1122             return processed;
1123 
1124         case HFP_PARSER_CMD_SEQUENCE:
1125             // handle empty fields
1126             if ((byte == ',' ) && (hfp_connection->line_size == 0)){
1127                 hfp_connection->line_buffer[0] = 0;
1128                 hfp_connection->ignore_value = 1;
1129                 parse_sequence(hfp_connection);
1130                 return true;
1131             }
1132 
1133             hfp_parser_store_if_token(hfp_connection, byte);
1134             if (!hfp_parser_is_separator(byte)) return true;
1135 
1136             // ignore empty tokens
1137             if (hfp_parser_is_buffer_empty(hfp_connection) && (hfp_connection->ignore_value == 0)) return true;
1138 
1139             parse_sequence(hfp_connection);
1140 
1141             hfp_parser_reset_line_buffer(hfp_connection);
1142 
1143             switch (hfp_connection->command){
1144                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1145                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1146                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1147                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1148                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1149                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1150                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1151                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1152                 case HFP_CMD_HF_INDICATOR_STATUS:
1153                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
1154                     break;
1155                 default:
1156                     break;
1157             }
1158             return true;
1159 
1160         case HFP_PARSER_SECOND_ITEM:
1161 
1162             hfp_parser_store_if_token(hfp_connection, byte);
1163             if (!hfp_parser_is_separator(byte)) return true;
1164 
1165             switch (hfp_connection->command){
1166                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1167                     log_info("format %s, ", hfp_connection->line_buffer);
1168                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1169                     break;
1170                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1171                     log_info("format %s \n", hfp_connection->line_buffer);
1172                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1173                     break;
1174                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1175                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1176                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1177                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1178                     break;
1179                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1180                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1181                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1182                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1183                     break;
1184                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1185                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer);
1186                     log_info("%s, ", hfp_connection->line_buffer);
1187                     break;
1188                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1189                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1190                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1191                     hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1192                     break;
1193                 case HFP_CMD_HF_INDICATOR_STATUS:
1194                     hfp_connection->parser_indicator_value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1195                     break;
1196                 default:
1197                     break;
1198             }
1199 
1200             hfp_parser_reset_line_buffer(hfp_connection);
1201 
1202             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
1203 
1204             return true;
1205 
1206         case HFP_PARSER_THIRD_ITEM:
1207 
1208             hfp_parser_store_if_token(hfp_connection, byte);
1209             if (!hfp_parser_is_separator(byte)) return true;
1210 
1211             switch (hfp_connection->command){
1212                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1213                     strncpy(hfp_connection->network_operator.name, (char *)hfp_connection->line_buffer, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE);
1214                     hfp_connection->network_operator.name[HFP_MAX_NETWORK_OPERATOR_NAME_SIZE - 1] = 0;
1215                     log_info("name %s\n", hfp_connection->line_buffer);
1216                     break;
1217                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1218                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer);
1219                     hfp_next_indicators_index(hfp_connection);
1220                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1221                     log_info("%s)\n", hfp_connection->line_buffer);
1222                     break;
1223                 default:
1224                     break;
1225             }
1226 
1227             hfp_parser_reset_line_buffer(hfp_connection);
1228 
1229             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){
1230                 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1231             } else {
1232                 hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1233             }
1234             return true;
1235 
1236         default:
1237             btstack_assert(false);
1238             return true;
1239     }
1240 }
1241 
1242 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1243     bool processed = false;
1244     while (!processed){
1245         processed = hfp_parse_byte(hfp_connection, byte, isHandsFree);
1246     }
1247     // reset parser state on end-of-line
1248     if (hfp_parser_is_end_of_line(byte)){
1249         hfp_connection->parser_item_index = 0;
1250         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1251     }
1252 }
1253 
1254 static void parse_sequence(hfp_connection_t * hfp_connection){
1255     int value;
1256     switch (hfp_connection->command){
1257         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1258             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1259             int i;
1260             switch (hfp_connection->parser_item_index){
1261                 case 0:
1262                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1263                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1264                             hfp_connection->parser_indicator_index = i;
1265                             break;
1266                         }
1267                     }
1268                     break;
1269                 case 1:
1270                     if (hfp_connection->parser_indicator_index <0) break;
1271                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1272                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1273                      hfp_connection->parser_item_index, value);
1274                     break;
1275                 default:
1276                     break;
1277             }
1278             hfp_next_indicators_index(hfp_connection);
1279             break;
1280 
1281         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1282             switch(hfp_connection->parser_item_index){
1283                 case 0:
1284                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1285                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1286                     break;
1287                 case 1:
1288                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1289                     hfp_connection->bnip_type = value;
1290                     break;
1291                 default:
1292                     break;
1293             }
1294             // index > 2 are ignored in switch above
1295             hfp_connection->parser_item_index++;
1296             break;
1297         case HFP_CMD_LIST_CURRENT_CALLS:
1298             switch(hfp_connection->parser_item_index){
1299                 case 0:
1300                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1301                     hfp_connection->clcc_idx = value;
1302                     break;
1303                 case 1:
1304                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1305                     hfp_connection->clcc_dir = value;
1306                     break;
1307                 case 2:
1308                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1309                     hfp_connection->clcc_status = value;
1310                     break;
1311                 case 3:
1312                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1313                     hfp_connection->clcc_mode = value;
1314                     break;
1315                 case 4:
1316                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1317                     hfp_connection->clcc_mpty = value;
1318                     break;
1319                 case 5:
1320                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1321                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1322                     break;
1323                 case 6:
1324                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1325                     hfp_connection->bnip_type = value;
1326                     break;
1327                 default:
1328                     break;
1329             }
1330             // index > 6 are ignored in switch above
1331             hfp_connection->parser_item_index++;
1332             break;
1333         case HFP_CMD_SET_MICROPHONE_GAIN:
1334             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1335             hfp_connection->microphone_gain = value;
1336             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1337             break;
1338         case HFP_CMD_SET_SPEAKER_GAIN:
1339             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1340             hfp_connection->speaker_gain = value;
1341             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1342             break;
1343         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1344             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1345             hfp_connection->ag_activate_voice_recognition = value;
1346             log_info("hfp parse HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION %d\n", value);
1347             break;
1348         case HFP_CMD_TURN_OFF_EC_AND_NR:
1349             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1350             hfp_connection->ag_echo_and_noise_reduction = value;
1351             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1352             break;
1353         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1354             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1355             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1356             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1357             break;
1358         case HFP_CMD_HF_CONFIRMED_CODEC:
1359             hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer);
1360             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1361             break;
1362         case HFP_CMD_AG_SUGGESTED_CODEC:
1363             hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer);
1364             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1365             break;
1366         case HFP_CMD_SUPPORTED_FEATURES:
1367             hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer);
1368             log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features);
1369             break;
1370         case HFP_CMD_AVAILABLE_CODECS:
1371             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1372             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1373             hfp_next_codec_index(hfp_connection);
1374             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1375             break;
1376         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1377             strncpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name,  (char *)hfp_connection->line_buffer, HFP_MAX_INDICATOR_DESC_SIZE);
1378             hfp_connection->ag_indicators[hfp_connection->parser_item_index].name[HFP_MAX_INDICATOR_DESC_SIZE-1] = 0;
1379             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1380             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1381             break;
1382         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1383             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1384             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer);
1385             hfp_next_indicators_index(hfp_connection);
1386             break;
1387         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1388             hfp_next_indicators_index(hfp_connection);
1389             if (hfp_connection->parser_item_index != 4) break;
1390             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1391             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1392             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1393             break;
1394         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1395             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1396             if (hfp_connection->line_size > 2 ) break;
1397             strncpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE);
1398             hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name[HFP_CALL_SERVICE_SIZE - 1] = 0;
1399             hfp_next_remote_call_services_index(hfp_connection);
1400             break;
1401         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1402         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1403             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1404             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1405             hfp_next_indicators_index(hfp_connection);
1406             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1407             break;
1408         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1409             // HF parses inital AG gen. ind. state
1410             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1411             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1412             break;
1413         case HFP_CMD_HF_INDICATOR_STATUS:
1414             hfp_connection->parser_indicator_index = hfp_parse_indicator_index(hfp_connection);
1415             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1416             break;
1417         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1418             // AG parses new gen. ind. state
1419             if (hfp_connection->ignore_value){
1420                 hfp_connection->ignore_value = 0;
1421                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1422                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1423             }
1424             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1425                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1426                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1427             } else {
1428                 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1429                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1430                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1431                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1432             }
1433             hfp_next_indicators_index(hfp_connection);
1434             break;
1435         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1436             // indicators are indexed starting with 1
1437             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1438             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1439             break;
1440         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1441             hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1442             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1443             break;
1444         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1445             if (hfp_connection->line_buffer[0] == '3'){
1446                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1447                 break;
1448             }
1449             // TODO emit ERROR, wrong format
1450             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1451             break;
1452         case HFP_CMD_ERROR:
1453             break;
1454         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1455             hfp_connection->extended_audio_gateway_error = 1;
1456             hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1457             break;
1458         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1459             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1460             hfp_connection->ok_pending = 1;
1461             hfp_connection->extended_audio_gateway_error = 0;
1462             break;
1463         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1464         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1465         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1466             strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1467             hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1468             break;
1469         case HFP_CMD_CALL_HOLD:
1470             hfp_connection->ag_call_hold_action = hfp_connection->line_buffer[0] - '0';
1471             if (hfp_connection->line_buffer[1] != '\0'){
1472                 hfp_connection->call_index = btstack_atoi((char *)&hfp_connection->line_buffer[1]);
1473             }
1474             break;
1475         case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1476             hfp_connection->ag_response_and_hold_action = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1477             break;
1478         case HFP_CMD_TRANSMIT_DTMF_CODES:
1479             hfp_connection->ag_dtmf_code = hfp_connection->line_buffer[0];
1480             break;
1481         case HFP_CMD_ENABLE_CLIP:
1482             hfp_connection->clip_enabled = hfp_connection->line_buffer[0] != '0';
1483             break;
1484         case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1485             hfp_connection->call_waiting_notification_enabled = hfp_connection->line_buffer[0] != '0';
1486             break;
1487         default:
1488             break;
1489     }
1490 }
1491 
1492 static void hfp_handle_start_sdp_client_query(void * context){
1493     UNUSED(context);
1494 
1495     btstack_linked_list_iterator_t it;
1496     btstack_linked_list_iterator_init(&it, &hfp_connections);
1497     while (btstack_linked_list_iterator_has_next(&it)){
1498         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1499 
1500         if (connection->state != HFP_W2_SEND_SDP_QUERY) continue;
1501 
1502         connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1503         sdp_query_context.local_role = connection->local_role;
1504         (void)memcpy(sdp_query_context.remote_address, connection->remote_addr, 6);
1505         sdp_client_query_rfcomm_channel_and_name_for_uuid(&handle_query_rfcomm_event, connection->remote_addr, connection->service_uuid);
1506         return;
1507     }
1508 }
1509 
1510 void hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){
1511     hfp_connection_t * hfp_connection = provide_hfp_connection_context_for_bd_addr(bd_addr, local_role);
1512     log_info("hfp_connect %s, hfp_connection %p", bd_addr_to_str(bd_addr), hfp_connection);
1513 
1514     if (!hfp_connection) {
1515         log_error("hfp_establish_service_level_connection for addr %s failed", bd_addr_to_str(bd_addr));
1516         return;
1517     }
1518     switch (hfp_connection->state){
1519         case HFP_W2_DISCONNECT_RFCOMM:
1520             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1521             return;
1522         case HFP_W4_RFCOMM_DISCONNECTED:
1523             hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART;
1524             return;
1525         case HFP_IDLE:
1526             (void)memcpy(hfp_connection->remote_addr, bd_addr, 6);
1527             hfp_connection->state = HFP_W2_SEND_SDP_QUERY;
1528             hfp_connection->service_uuid = service_uuid;
1529 
1530             hfp_handle_sdp_client_query_request.callback = &hfp_handle_start_sdp_client_query;
1531             // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1532             (void) sdp_client_register_query_callback(&hfp_handle_sdp_client_query_request);
1533             break;
1534         default:
1535             break;
1536     }
1537 }
1538 
1539 void hfp_release_service_level_connection(hfp_connection_t * hfp_connection){
1540     if (!hfp_connection) return;
1541     hfp_release_audio_connection(hfp_connection);
1542 
1543     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1544         hfp_connection->state = HFP_IDLE;
1545         return;
1546     }
1547 
1548     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1549         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1550         return;
1551     }
1552 
1553     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1554         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1555         return;
1556     }
1557 
1558     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1559         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1560         return;
1561     }
1562 
1563     // HFP_W4_SCO_DISCONNECTED or later
1564     hfp_connection->release_slc_connection = 1;
1565 }
1566 
1567 void hfp_release_audio_connection(hfp_connection_t * hfp_connection){
1568     if (!hfp_connection) return;
1569     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
1570     hfp_connection->release_audio_connection = 1;
1571 }
1572 
1573 static const struct link_settings {
1574     const uint16_t max_latency;
1575     const uint8_t  retransmission_effort;
1576     const uint16_t packet_types;
1577     const bool     eSCO;
1578     const uint8_t  codec;
1579 } hfp_link_settings [] = {
1580     { 0xffff, 0xff, SCO_PACKET_TYPES_HV1,  false, HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_D0
1581     { 0xffff, 0xff, SCO_PACKET_TYPES_HV3,  false, HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_D1
1582     { 0x0007, 0x01, SCO_PACKET_TYPES_EV3,  true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S1
1583     { 0x0007, 0x01, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S2
1584     { 0x000a, 0x01, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S3
1585     { 0x000c, 0x02, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S4
1586     { 0x0008, 0x02, SCO_PACKET_TYPES_EV3,  true,  HFP_CODEC_MSBC }, // HFP_LINK_SETTINGS_T1
1587     { 0x000d, 0x02, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_MSBC }  // HFP_LINK_SETTINGS_T2
1588 };
1589 
1590 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){
1591     // all packet types, fixed bandwidth
1592     int setting = hfp_connection->link_setting;
1593     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1594     sco_establishment_active = hfp_connection;
1595     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1596     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1597         sco_voice_setting = 0x0043; // Transparent data
1598     }
1599     // get packet types - bits 6-9 are 'don't allow'
1600     uint16_t packet_types = hfp_link_settings[setting].packet_types ^ 0x03c0;
1601     hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency,
1602         sco_voice_setting, hfp_link_settings[setting].retransmission_effort, packet_types);
1603 }
1604 
1605 void hfp_set_hf_callback(btstack_packet_handler_t callback){
1606     hfp_hf_callback = callback;
1607 }
1608 
1609 void hfp_set_ag_callback(btstack_packet_handler_t callback){
1610     hfp_ag_callback = callback;
1611 }
1612 
1613 void hfp_set_ag_rfcomm_packet_handler(btstack_packet_handler_t handler){
1614     hfp_ag_rfcomm_packet_handler = handler;
1615 }
1616 
1617 void hfp_set_hf_rfcomm_packet_handler(btstack_packet_handler_t handler){
1618     hfp_hf_rfcomm_packet_handler = handler;
1619 }
1620 
1621 void hfp_set_hf_run_for_context(void (*callback)(hfp_connection_t * hfp_connection)){
1622     hfp_hf_run_for_context = callback;
1623 }
1624 
1625 void hfp_init(void){
1626     hfp_allowed_sco_packet_types = SCO_PACKET_TYPES_ALL;
1627 }
1628 
1629 void hfp_set_sco_packet_types(uint16_t packet_types){
1630     hfp_allowed_sco_packet_types = packet_types;
1631 }
1632 
1633 uint16_t hfp_get_sco_packet_types(void){
1634     return hfp_allowed_sco_packet_types;
1635 }
1636 
1637 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){
1638     int8_t setting = (int8_t) current_setting;
1639     bool can_use_eSCO = local_eSCO_supported && remote_eSCO_supported;
1640     while (setting > 0){
1641         setting--;
1642         // skip if eSCO required but not available
1643         if (hfp_link_settings[setting].eSCO && !can_use_eSCO) continue;
1644         // skip if S4 but not supported
1645         if ((setting == (int8_t) HFP_LINK_SETTINGS_S4) && !eSCO_S4_supported) continue;
1646         // skip wrong codec
1647         if ( hfp_link_settings[setting].codec != negotiated_codec) continue;
1648         // skip disabled packet types
1649         uint16_t required_packet_types = hfp_link_settings[setting].packet_types;
1650         uint16_t allowed_packet_types  = hfp_allowed_sco_packet_types;
1651         if ((required_packet_types & allowed_packet_types) == 0) continue;
1652 
1653         // found matching setting
1654         return (hfp_link_settings_t) setting;
1655     }
1656     return HFP_LINK_SETTINGS_NONE;
1657 }
1658 
1659 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){
1660     bool local_eSCO_supported  = hci_extended_sco_link_supported();
1661     bool remote_eSCO_supported = hci_remote_esco_supported(hfp_connection->acl_handle);
1662     uint8_t negotiated_codec   = hfp_connection->negotiated_codec;
1663     return  hfp_next_link_setting(current_setting, local_eSCO_supported, remote_eSCO_supported, eSCO_S4_supported, negotiated_codec);
1664 }
1665 
1666 void hfp_init_link_settings(hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported){
1667     // get highest possible link setting
1668     hfp_connection->link_setting = hfp_next_link_setting_for_connection(HFP_LINK_SETTINGS_NONE, hfp_connection, eSCO_S4_supported);
1669     log_info("hfp_init_link_settings: %u", hfp_connection->link_setting);
1670 }
1671 
1672 #define HFP_HF_RX_DEBUG_PRINT_LINE 80
1673 
1674 void hfp_log_rfcomm_message(const char * tag, uint8_t * packet, uint16_t size){
1675 #ifdef ENABLE_LOG_INFO
1676     // encode \n\r
1677     char printable[HFP_HF_RX_DEBUG_PRINT_LINE+2];
1678     int i = 0;
1679     int pos;
1680     for (pos=0 ; (pos < size) && (i < (HFP_HF_RX_DEBUG_PRINT_LINE - 3)) ; pos++){
1681         switch (packet[pos]){
1682             case '\n':
1683                 printable[i++] = '\\';
1684                 printable[i++] = 'n';
1685                 break;
1686             case '\r':
1687                 printable[i++] = '\\';
1688                 printable[i++] = 'r';
1689                 break;
1690             default:
1691                 printable[i++] = packet[pos];
1692                 break;
1693         }
1694     }
1695     printable[i] = 0;
1696     log_info("%s: '%s'", tag, printable);
1697 #endif
1698 }
1699