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