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