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