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