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