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