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