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