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