xref: /btstack/src/classic/hfp.c (revision 0c4cc577b21c11709db67ba73e95e3716dea3bcf)
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 
1010 static void hfp_parser_next_state(hfp_connection_t * hfp_connection, uint8_t byte){
1011     hfp_connection->line_size = 0;
1012     if (hfp_parser_is_end_of_line(byte)){
1013         hfp_connection->parser_item_index = 0;
1014         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1015         return;
1016     }
1017     switch (hfp_connection->parser_state){
1018         case HFP_PARSER_CMD_HEADER:
1019             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1020             if (hfp_connection->keep_byte == 1){
1021                 hfp_parser_store_byte(hfp_connection, byte);
1022                 hfp_connection->keep_byte = 0;
1023             }
1024             break;
1025         case HFP_PARSER_CMD_SEQUENCE:
1026             switch (hfp_connection->command){
1027                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1028                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1029                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1030                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1031                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1032                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1033                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1034                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1035                 case HFP_CMD_HF_INDICATOR_STATUS:
1036                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
1037                     break;
1038                 default:
1039                     break;
1040             }
1041             break;
1042         case HFP_PARSER_SECOND_ITEM:
1043             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
1044             break;
1045         case HFP_PARSER_THIRD_ITEM:
1046             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){
1047                 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1048                 break;
1049             }
1050             hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1051             break;
1052     }
1053 }
1054 
1055 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1056     // handle ATD<dial_string>;
1057     if (strncmp((const char*)hfp_connection->line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0){
1058         // check for end-of-line or ';'
1059         if (byte == ';' || hfp_parser_is_end_of_line(byte)){
1060             hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1061             hfp_connection->line_size = 0;
1062             hfp_connection->command = HFP_CMD_CALL_PHONE_NUMBER;
1063         } else {
1064             hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
1065         }
1066         return;
1067     }
1068 
1069     // TODO: handle space inside word
1070     if (byte == ' ' && hfp_connection->parser_state > HFP_PARSER_CMD_HEADER) return;
1071 
1072     if (byte == ',' && hfp_connection->command == HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE){
1073         if (hfp_connection->line_size == 0){
1074             hfp_connection->line_buffer[0] = 0;
1075             hfp_connection->ignore_value = 1;
1076             parse_sequence(hfp_connection);
1077             return;
1078         }
1079     }
1080 
1081     if (!hfp_parser_found_separator(hfp_connection, byte)){
1082         hfp_parser_store_byte(hfp_connection, byte);
1083         return;
1084     }
1085 
1086     if (hfp_parser_is_end_of_line(byte)) {
1087         if (hfp_parser_is_buffer_empty(hfp_connection)){
1088             hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1089         }
1090     }
1091     if (hfp_parser_is_buffer_empty(hfp_connection)) return;
1092 
1093     switch (hfp_connection->parser_state){
1094         case HFP_PARSER_CMD_HEADER: // header
1095             if (byte == '='){
1096                 hfp_connection->keep_byte = 1;
1097                 hfp_parser_store_byte(hfp_connection, byte);
1098                 return;
1099             }
1100 
1101             if (byte == '?'){
1102                 hfp_connection->keep_byte = 0;
1103                 hfp_parser_store_byte(hfp_connection, byte);
1104                 return;
1105             }
1106 
1107             if (byte == ','){
1108                 hfp_connection->resolve_byte = 1;
1109             }
1110 
1111             // printf(" parse header 2 %s, keep separator $ %d\n", hfp_connection->line_buffer, hfp_connection->keep_byte);
1112             if (hfp_parser_is_end_of_header(byte) || hfp_connection->keep_byte == 1){
1113                 // printf(" parse header 3 %s, keep separator $ %d\n", hfp_connection->line_buffer, hfp_connection->keep_byte);
1114                 char * line_buffer = (char *)hfp_connection->line_buffer;
1115                 hfp_connection->command = parse_command(line_buffer, isHandsFree);
1116 
1117                 /* resolve command name according to hfp_connection */
1118                 if (hfp_connection->command == HFP_CMD_UNKNOWN){
1119                     switch(hfp_connection->state){
1120                         case HFP_W4_LIST_GENERIC_STATUS_INDICATORS:
1121                             hfp_connection->command = HFP_CMD_LIST_GENERIC_STATUS_INDICATORS;
1122                             break;
1123                         case HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS:
1124                             hfp_connection->command = HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS;
1125                             break;
1126                         case HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS:
1127                             hfp_connection->command = HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE;
1128                             break;
1129                         case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1130                             hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
1131                             break;
1132                         case HFP_W4_RETRIEVE_INDICATORS:
1133                             hfp_connection->send_ag_indicators_segment = 0;
1134                             hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS;
1135                             break;
1136                         default:
1137                             break;
1138                     }
1139                 }
1140             }
1141             break;
1142 
1143         case HFP_PARSER_CMD_SEQUENCE:
1144             parse_sequence(hfp_connection);
1145             break;
1146         case HFP_PARSER_SECOND_ITEM:
1147             switch (hfp_connection->command){
1148                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1149                     log_info("format %s, ", hfp_connection->line_buffer);
1150                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1151                     break;
1152                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1153                     log_info("format %s \n", hfp_connection->line_buffer);
1154                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1155                     break;
1156                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1157                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1158                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1159                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1160                     break;
1161                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1162                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1163                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1164                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1165                     break;
1166                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1167                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer);
1168                     log_info("%s, ", hfp_connection->line_buffer);
1169                     break;
1170                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1171                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1172                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1173                     hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1174                     break;
1175                 default:
1176                     break;
1177             }
1178             break;
1179 
1180         case HFP_PARSER_THIRD_ITEM:
1181              switch (hfp_connection->command){
1182                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1183                     strncpy(hfp_connection->network_operator.name, (char *)hfp_connection->line_buffer, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE);
1184                     hfp_connection->network_operator.name[HFP_MAX_NETWORK_OPERATOR_NAME_SIZE - 1] = 0;
1185                     log_info("name %s\n", hfp_connection->line_buffer);
1186                     break;
1187                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1188                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer);
1189                     hfp_connection->parser_item_index++;
1190                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1191                     log_info("%s)\n", hfp_connection->line_buffer);
1192                     break;
1193                 default:
1194                     break;
1195             }
1196             break;
1197     }
1198     hfp_parser_next_state(hfp_connection, byte);
1199 
1200     if (hfp_connection->resolve_byte && hfp_connection->command == HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE){
1201         hfp_connection->resolve_byte = 0;
1202         hfp_connection->ignore_value = 1;
1203         parse_sequence(hfp_connection);
1204         hfp_connection->line_buffer[0] = 0;
1205         hfp_connection->line_size = 0;
1206     }
1207 }
1208 
1209 static void parse_sequence(hfp_connection_t * hfp_connection){
1210     int value;
1211     switch (hfp_connection->command){
1212         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1213             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1214             int i;
1215             switch (hfp_connection->parser_item_index){
1216                 case 0:
1217                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1218                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1219                             hfp_connection->parser_indicator_index = i;
1220                             break;
1221                         }
1222                     }
1223                     break;
1224                 case 1:
1225                     if (hfp_connection->parser_indicator_index <0) break;
1226                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1227                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1228                      hfp_connection->parser_item_index, value);
1229                     break;
1230                 default:
1231                     break;
1232             }
1233             hfp_connection->parser_item_index++;
1234             break;
1235 
1236         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1237             switch(hfp_connection->parser_item_index){
1238                 case 0:
1239                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1240                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1241                     break;
1242                 case 1:
1243                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1244                     hfp_connection->bnip_type = value;
1245                     break;
1246                 default:
1247                     break;
1248             }
1249             hfp_connection->parser_item_index++;
1250             break;
1251         case HFP_CMD_LIST_CURRENT_CALLS:
1252             switch(hfp_connection->parser_item_index){
1253                 case 0:
1254                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1255                     hfp_connection->clcc_idx = value;
1256                     break;
1257                 case 1:
1258                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1259                     hfp_connection->clcc_dir = value;
1260                     break;
1261                 case 2:
1262                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1263                     hfp_connection->clcc_status = value;
1264                     break;
1265                 case 3:
1266                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1267                     hfp_connection->clcc_mpty = value;
1268                     break;
1269                 case 4:
1270                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1271                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1272                     break;
1273                 case 5:
1274                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1275                     hfp_connection->bnip_type = value;
1276                     break;
1277                 default:
1278                     break;
1279             }
1280             hfp_connection->parser_item_index++;
1281             break;
1282         case HFP_CMD_SET_MICROPHONE_GAIN:
1283             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1284             hfp_connection->microphone_gain = value;
1285             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1286             break;
1287         case HFP_CMD_SET_SPEAKER_GAIN:
1288             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1289             hfp_connection->speaker_gain = value;
1290             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1291             break;
1292         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1293             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1294             hfp_connection->ag_activate_voice_recognition = value;
1295             log_info("hfp parse HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION %d\n", value);
1296             break;
1297         case HFP_CMD_TURN_OFF_EC_AND_NR:
1298             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1299             hfp_connection->ag_echo_and_noise_reduction = value;
1300             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1301             break;
1302         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1303             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1304             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1305             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1306             break;
1307         case HFP_CMD_HF_CONFIRMED_CODEC:
1308             hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer);
1309             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1310             break;
1311         case HFP_CMD_AG_SUGGESTED_CODEC:
1312             hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer);
1313             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1314             break;
1315         case HFP_CMD_SUPPORTED_FEATURES:
1316             hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer);
1317             log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features);
1318             break;
1319         case HFP_CMD_AVAILABLE_CODECS:
1320             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1321             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1322             hfp_connection->parser_item_index++;
1323             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1324             break;
1325         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1326             strncpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name,  (char *)hfp_connection->line_buffer, HFP_MAX_INDICATOR_DESC_SIZE);
1327             hfp_connection->ag_indicators[hfp_connection->parser_item_index].name[HFP_MAX_INDICATOR_DESC_SIZE-1] = 0;
1328             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1329             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1330             break;
1331         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1332             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1333             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer);
1334             hfp_connection->parser_item_index++;
1335             break;
1336         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1337             hfp_connection->parser_item_index++;
1338             if (hfp_connection->parser_item_index != 4) break;
1339             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1340             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1341             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1342             break;
1343         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1344             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1345             if (hfp_connection->line_size > 2 ) break;
1346             strncpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_nr].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE);
1347             hfp_connection->remote_call_services[hfp_connection->remote_call_services_nr].name[HFP_CALL_SERVICE_SIZE - 1] = 0;
1348             hfp_connection->remote_call_services_nr++;
1349             break;
1350         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1351         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1352             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1353             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1354             hfp_connection->parser_item_index++;
1355             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1356             break;
1357         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1358             // HF parses inital AG gen. ind. state
1359             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1360             hfp_connection->parser_item_index = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1361             break;
1362         case HFP_CMD_HF_INDICATOR_STATUS:
1363             hfp_connection->parser_indicator_index = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1364             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1365             break;
1366         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1367             // AG parses new gen. ind. state
1368             if (hfp_connection->ignore_value){
1369                 hfp_connection->ignore_value = 0;
1370                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1371                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1372             }
1373             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1374                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1375                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1376             } else {
1377                 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1378                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1379                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1380                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1381             }
1382             hfp_connection->parser_item_index++;
1383             break;
1384         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1385             // indicators are indexed starting with 1
1386             hfp_connection->parser_item_index = btstack_atoi((char *)&hfp_connection->line_buffer[0]) - 1;
1387             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1388             break;
1389         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1390             hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1391             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1392             break;
1393         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1394             if (hfp_connection->line_buffer[0] == '3'){
1395                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1396                 break;
1397             }
1398             // TODO emit ERROR, wrong format
1399             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1400             break;
1401         case HFP_CMD_ERROR:
1402             break;
1403         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1404             hfp_connection->extended_audio_gateway_error = 1;
1405             hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1406             break;
1407         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1408             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1409             hfp_connection->ok_pending = 1;
1410             hfp_connection->extended_audio_gateway_error = 0;
1411             break;
1412         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1413         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1414         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1415             strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1416             hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1417             break;
1418         default:
1419             break;
1420     }
1421 }
1422 
1423 void hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){
1424     hfp_connection_t * hfp_connection = provide_hfp_connection_context_for_bd_addr(bd_addr, local_role);
1425     log_info("hfp_connect %s, hfp_connection %p", bd_addr_to_str(bd_addr), hfp_connection);
1426 
1427     if (!hfp_connection) {
1428         log_error("hfp_establish_service_level_connection for addr %s failed", bd_addr_to_str(bd_addr));
1429         return;
1430     }
1431 
1432     switch (hfp_connection->state){
1433         case HFP_W2_DISCONNECT_RFCOMM:
1434             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1435             return;
1436         case HFP_W4_RFCOMM_DISCONNECTED:
1437             hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART;
1438             return;
1439         case HFP_IDLE:
1440             memcpy(hfp_connection->remote_addr, bd_addr, 6);
1441             hfp_connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1442             connection_doing_sdp_query = hfp_connection;
1443             hfp_connection->service_uuid = service_uuid;
1444             sdp_client_query_rfcomm_channel_and_name_for_uuid(&handle_query_rfcomm_event, hfp_connection->remote_addr, service_uuid);
1445             break;
1446         default:
1447             break;
1448     }
1449 }
1450 
1451 void hfp_release_service_level_connection(hfp_connection_t * hfp_connection){
1452     if (!hfp_connection) return;
1453     hfp_release_audio_connection(hfp_connection);
1454 
1455     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1456         hfp_connection->state = HFP_IDLE;
1457         return;
1458     }
1459 
1460     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1461         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1462         return;
1463     }
1464 
1465     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1466         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1467         return;
1468     }
1469 
1470     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1471         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1472         return;
1473     }
1474 
1475     return;
1476 }
1477 
1478 void hfp_release_audio_connection(hfp_connection_t * hfp_connection){
1479     if (!hfp_connection) return;
1480     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
1481     hfp_connection->release_audio_connection = 1;
1482 }
1483 
1484 static const struct link_settings {
1485     const uint16_t max_latency;
1486     const uint8_t  retransmission_effort;
1487     const uint16_t packet_types;
1488 } hfp_link_settings [] = {
1489     { 0xffff, 0xff, 0x03c1 }, // HFP_LINK_SETTINGS_D0,   HV1
1490     { 0xffff, 0xff, 0x03c4 }, // HFP_LINK_SETTINGS_D1,   HV3
1491     { 0x0007, 0x01, 0x03c8 }, // HFP_LINK_SETTINGS_S1,   EV3
1492     { 0x0007, 0x01, 0x0380 }, // HFP_LINK_SETTINGS_S2, 2-EV3
1493     { 0x000a, 0x01, 0x0380 }, // HFP_LINK_SETTINGS_S3, 2-EV3
1494     { 0x000c, 0x02, 0x0380 }, // HFP_LINK_SETTINGS_S4, 2-EV3
1495     { 0x0008, 0x02, 0x03c8 }, // HFP_LINK_SETTINGS_T1,   EV3
1496     { 0x000d, 0x02, 0x0380 }  // HFP_LINK_SETTINGS_T2, 2-EV3
1497 };
1498 
1499 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){
1500     // all packet types, fixed bandwidth
1501     int setting = hfp_connection->link_setting;
1502     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1503     sco_establishment_active = hfp_connection;
1504     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1505     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1506         sco_voice_setting = 0x0043; // Transparent data
1507     }
1508     hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency,
1509         sco_voice_setting, hfp_link_settings[setting].retransmission_effort, hfp_link_settings[setting].packet_types); // all types 0x003f, only 2-ev3 0x380
1510 }
1511 
1512 void hfp_set_hf_callback(btstack_packet_handler_t callback){
1513     hfp_hf_callback = callback;
1514 }
1515 
1516 void hfp_set_ag_callback(btstack_packet_handler_t callback){
1517     hfp_ag_callback = callback;
1518 }
1519 
1520 void hfp_set_ag_rfcomm_packet_handler(btstack_packet_handler_t handler){
1521     hfp_ag_rfcomm_packet_handler = handler;
1522 }
1523 
1524 void hfp_set_hf_rfcomm_packet_handler(btstack_packet_handler_t handler){
1525     hfp_hf_rfcomm_packet_handler = handler;
1526 }
1527 
1528 void hfp_set_hf_run_for_context(void (*callback)(hfp_connection_t * hfp_connection)){
1529     hfp_hf_run_for_context = callback;
1530 }
1531 
1532 void hfp_init(void){
1533 }
1534 
1535 void hfp_init_link_settings(hfp_connection_t * hfp_connection, uint8_t esco_s4_supported){
1536     // determine highest possible link setting
1537     hfp_connection->link_setting = HFP_LINK_SETTINGS_D1;
1538     // anything else requires eSCO support on both sides
1539     if (hci_extended_sco_link_supported() && hci_remote_esco_supported(hfp_connection->acl_handle)){
1540         switch (hfp_connection->negotiated_codec){
1541             case HFP_CODEC_CVSD:
1542                 hfp_connection->link_setting = HFP_LINK_SETTINGS_S3;
1543                 if (esco_s4_supported){
1544                     hfp_connection->link_setting = HFP_LINK_SETTINGS_S4;
1545                 }
1546                 break;
1547             case HFP_CODEC_MSBC:
1548                 hfp_connection->link_setting = HFP_LINK_SETTINGS_T2;
1549                 break;
1550             default:
1551                 break;
1552         }
1553     }
1554     log_info("hfp_init_link_settings: %u", hfp_connection->link_setting);
1555 }
1556 
1557 #define HFP_HF_RX_DEBUG_PRINT_LINE 80
1558 
1559 void hfp_log_rfcomm_message(const char * tag, uint8_t * packet, uint16_t size){
1560 #ifdef ENABLE_LOG_INFO
1561     // encode \n\r
1562     char printable[HFP_HF_RX_DEBUG_PRINT_LINE+2];
1563     int i;
1564     int pos;
1565     for (i=0,pos=0;(pos < size) && (i < (HFP_HF_RX_DEBUG_PRINT_LINE - 3)); pos++){
1566         switch (packet[pos]){
1567             case '\n':
1568                 printable[i++] = '\\';
1569                 printable[i++] = 'n';
1570                 break;
1571             case '\r':
1572                 printable[i++] = '\\';
1573                 printable[i++] = 'r';
1574                 break;
1575             default:
1576                 printable[i++] = packet[pos];
1577                 break;
1578         }
1579     }
1580     printable[i] = 0;
1581     log_info("%s: '%s'", tag, printable);
1582 #endif
1583 }
1584