xref: /btstack/src/classic/hfp.c (revision 1884f13fb9884b15dacdfc04d9536827c4949e99)
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){
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) {
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){
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){
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){
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){
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);
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 static void hfp_handle_failed_sco_connection(uint8_t status){
524 
525     if (!sco_establishment_active){
526         log_error("(e)SCO Connection failed but not started by us");
527         return;
528     }
529     log_error("(e)SCO Connection failed status 0x%02x", status);
530 
531     // invalid params / unspecified error
532     if (status != 0x11 && status != 0x1f) return;
533 
534      switch (sco_establishment_active->link_setting){
535         case HFP_LINK_SETTINGS_D0:
536             return; // 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     sco_establishment_active->establish_audio_connection = 1;
564     sco_establishment_active = 0;
565 }
566 
567 
568 void hfp_handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
569     UNUSED(channel);    // ok: no channel
570 
571     bd_addr_t event_addr;
572     hci_con_handle_t handle;
573     hfp_connection_t * hfp_connection = NULL;
574     uint8_t status;
575 
576     log_debug("HFP HCI event handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
577 
578     switch (hci_event_packet_get_type(packet)) {
579 
580         case HCI_EVENT_CONNECTION_REQUEST:
581             switch(hci_event_connection_request_get_link_type(packet)){
582                 case 0: //  SCO
583                 case 2: // eSCO
584                     hci_event_connection_request_get_bd_addr(packet, event_addr);
585                     hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr);
586                     if (!hfp_connection) break;
587                     log_info("hf accept sco\n");
588                     hfp_connection->hf_accept_sco = 1;
589                     if (!hfp_hf_run_for_context) break;
590                     (*hfp_hf_run_for_context)(hfp_connection);
591                     break;
592                 default:
593                     break;
594             }
595             break;
596 
597         case HCI_EVENT_COMMAND_STATUS:
598             if (hci_event_command_status_get_command_opcode(packet) == hci_setup_synchronous_connection.opcode) {
599                 status = hci_event_command_status_get_status(packet);
600                 if (status) {
601                     hfp_handle_failed_sco_connection(hci_event_command_status_get_status(packet));
602                }
603             }
604             break;
605 
606         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
607             hci_event_synchronous_connection_complete_get_bd_addr(packet, event_addr);
608             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr);
609             if (!hfp_connection) {
610                 log_error("HFP: connection does not exist for remote with addr %s.", bd_addr_to_str(event_addr));
611                 return;
612             }
613 
614             status = hci_event_synchronous_connection_complete_get_status(packet);
615             if (status != 0){
616                 hfp_connection->hf_accept_sco = 0;
617                 hfp_handle_failed_sco_connection(status);
618                 break;
619             }
620 
621             uint16_t sco_handle = hci_event_synchronous_connection_complete_get_handle(packet);
622             uint8_t  link_type = hci_event_synchronous_connection_complete_get_link_type(packet);
623             uint8_t  transmission_interval = hci_event_synchronous_connection_complete_get_transmission_interval(packet);  // measured in slots
624             uint8_t  retransmission_interval = hci_event_synchronous_connection_complete_get_retransmission_interval(packet);// measured in slots
625             uint16_t rx_packet_length = hci_event_synchronous_connection_complete_get_rx_packet_length(packet); // measured in bytes
626             uint16_t tx_packet_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet); // measured in bytes
627             uint8_t  air_mode = hci_event_synchronous_connection_complete_get_air_mode(packet);
628 
629             switch (link_type){
630                 case 0x00:
631                     log_info("SCO Connection established.");
632                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
633                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
634                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
635                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
636                     break;
637                 case 0x02:
638                     log_info("eSCO Connection established. \n");
639                     break;
640                 default:
641                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
642                     break;
643             }
644             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
645                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)\n", sco_handle,
646                  bd_addr_to_str(event_addr), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length, air_mode);
647 
648             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr);
649 
650             if (!hfp_connection) {
651                 log_error("SCO link created, hfp_connection for address %s not found.", bd_addr_to_str(event_addr));
652                 break;
653             }
654 
655             if (hfp_connection->state == HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){
656                 log_info("SCO about to disconnect: HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN");
657                 hfp_connection->state = HFP_W2_DISCONNECT_SCO;
658                 break;
659             }
660             hfp_connection->sco_handle = sco_handle;
661             hfp_connection->establish_audio_connection = 0;
662             hfp_connection->state = HFP_AUDIO_CONNECTION_ESTABLISHED;
663             hfp_emit_sco_event(hfp_connection, packet[2], sco_handle, event_addr, hfp_connection->negotiated_codec);
664             break;
665         }
666 
667         case HCI_EVENT_DISCONNECTION_COMPLETE:
668             handle = little_endian_read_16(packet,3);
669             hfp_connection = get_hfp_connection_context_for_sco_handle(handle);
670 
671             if (!hfp_connection) break;
672 
673             if (hfp_connection->state != HFP_W4_SCO_DISCONNECTED){
674                 log_info("Received gap disconnect in wrong hfp state");
675             }
676             log_info("Check SCO handle: incoming 0x%02x, hfp_connection 0x%02x\n", handle, hfp_connection->sco_handle);
677 
678             if (handle == hfp_connection->sco_handle){
679                 log_info("SCO disconnected, w2 disconnect RFCOMM\n");
680                 hfp_connection->sco_handle = 0;
681                 hfp_connection->release_audio_connection = 0;
682                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
683                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_AUDIO_CONNECTION_RELEASED, 0);
684                 break;
685             }
686             break;
687 
688         default:
689             break;
690     }
691 }
692 
693 void hfp_handle_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
694     UNUSED(channel);    // ok: no channel
695 
696     bd_addr_t event_addr;
697     uint16_t rfcomm_cid;
698     hfp_connection_t * hfp_connection = NULL;
699     uint8_t status;
700 
701     log_debug("HFP packet_handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
702 
703     switch (hci_event_packet_get_type(packet)) {
704 
705         case RFCOMM_EVENT_INCOMING_CONNECTION:
706             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
707             rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
708             hfp_connection = provide_hfp_connection_context_for_bd_addr(event_addr, local_role);
709             if (!hfp_connection){
710                 log_info("hfp: no memory to accept incoming connection - decline");
711                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
712                 return;
713             }
714             if (hfp_connection->state != HFP_IDLE) {
715                 log_error("hfp: incoming connection but state != HFP_IDLE");
716                 return;
717             }
718 
719             hfp_connection->rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
720             hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
721             // printf("RFCOMM channel %u requested for %s\n", hfp_connection->rfcomm_cid, bd_addr_to_str(hfp_connection->remote_addr));
722             rfcomm_accept_connection(hfp_connection->rfcomm_cid);
723             break;
724 
725         case RFCOMM_EVENT_CHANNEL_OPENED:
726             // data: event(8), len(8), status (8), address (48), handle(16), server channel(8), rfcomm_cid(16), max frame size(16)
727 
728             rfcomm_event_channel_opened_get_bd_addr(packet, event_addr);
729             status = rfcomm_event_channel_opened_get_status(packet);
730 
731             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr);
732             if (!hfp_connection || hfp_connection->state != HFP_W4_RFCOMM_CONNECTED) return;
733 
734             if (status) {
735                 hfp_emit_slc_connection_event(hfp_connection, status, rfcomm_event_channel_opened_get_con_handle(packet), event_addr);
736                 remove_hfp_connection_context(hfp_connection);
737             } else {
738                 hfp_connection->acl_handle = rfcomm_event_channel_opened_get_con_handle(packet);
739                 hfp_connection->rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
740                 bd_addr_copy(hfp_connection->remote_addr, event_addr);
741                 // uint16_t mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
742                 // 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);
743 
744                 switch (hfp_connection->state){
745                     case HFP_W4_RFCOMM_CONNECTED:
746                         hfp_connection->state = HFP_EXCHANGE_SUPPORTED_FEATURES;
747                         break;
748                     case HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN:
749                         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
750                         // printf("Shutting down RFCOMM.\n");
751                         break;
752                     default:
753                         break;
754                 }
755                 rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
756             }
757             break;
758 
759         case RFCOMM_EVENT_CHANNEL_CLOSED:
760             rfcomm_cid = little_endian_read_16(packet,2);
761             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
762             if (!hfp_connection) break;
763             if (hfp_connection->state == HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART){
764                 hfp_connection->state = HFP_IDLE;
765                 hfp_establish_service_level_connection(hfp_connection->remote_addr, hfp_connection->service_uuid, local_role);
766                 break;
767             }
768 
769             hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
770             remove_hfp_connection_context(hfp_connection);
771             break;
772 
773         default:
774             break;
775     }
776 }
777 // translates command string into hfp_command_t CMD
778 static hfp_command_t parse_command(const char * line_buffer, int isHandsFree){
779     log_info("command '%s', handsfree %u", line_buffer, isHandsFree);
780     int offset = isHandsFree ? 0 : 2;
781 
782     if (strncmp(line_buffer+offset, HFP_LIST_CURRENT_CALLS, strlen(HFP_LIST_CURRENT_CALLS)) == 0){
783         return HFP_CMD_LIST_CURRENT_CALLS;
784     }
785 
786     if (strncmp(line_buffer+offset, HFP_SUBSCRIBER_NUMBER_INFORMATION, strlen(HFP_SUBSCRIBER_NUMBER_INFORMATION)) == 0){
787         return HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION;
788     }
789 
790     if (strncmp(line_buffer+offset, HFP_PHONE_NUMBER_FOR_VOICE_TAG, strlen(HFP_PHONE_NUMBER_FOR_VOICE_TAG)) == 0){
791         if (isHandsFree) return HFP_CMD_AG_SENT_PHONE_NUMBER;
792         return HFP_CMD_HF_REQUEST_PHONE_NUMBER;
793     }
794 
795     if (strncmp(line_buffer+offset, HFP_TRANSMIT_DTMF_CODES, strlen(HFP_TRANSMIT_DTMF_CODES)) == 0){
796         return HFP_CMD_TRANSMIT_DTMF_CODES;
797     }
798 
799     if (strncmp(line_buffer+offset, HFP_SET_MICROPHONE_GAIN, strlen(HFP_SET_MICROPHONE_GAIN)) == 0){
800         return HFP_CMD_SET_MICROPHONE_GAIN;
801     }
802 
803     if (strncmp(line_buffer+offset, HFP_SET_SPEAKER_GAIN, strlen(HFP_SET_SPEAKER_GAIN)) == 0){
804         return HFP_CMD_SET_SPEAKER_GAIN;
805     }
806 
807     if (strncmp(line_buffer+offset, HFP_ACTIVATE_VOICE_RECOGNITION, strlen(HFP_ACTIVATE_VOICE_RECOGNITION)) == 0){
808         if (isHandsFree) return HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
809         return HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION;
810     }
811 
812     if (strncmp(line_buffer+offset, HFP_TURN_OFF_EC_AND_NR, strlen(HFP_TURN_OFF_EC_AND_NR)) == 0){
813         return HFP_CMD_TURN_OFF_EC_AND_NR;
814     }
815 
816     if (strncmp(line_buffer, HFP_ANSWER_CALL, strlen(HFP_ANSWER_CALL)) == 0){
817         return HFP_CMD_CALL_ANSWERED;
818     }
819 
820     if (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0){
821         return HFP_CMD_CALL_PHONE_NUMBER;
822     }
823 
824     if (strncmp(line_buffer+offset, HFP_REDIAL_LAST_NUMBER, strlen(HFP_REDIAL_LAST_NUMBER)) == 0){
825         return HFP_CMD_REDIAL_LAST_NUMBER;
826     }
827 
828     if (strncmp(line_buffer+offset, HFP_CHANGE_IN_BAND_RING_TONE_SETTING, strlen(HFP_CHANGE_IN_BAND_RING_TONE_SETTING)) == 0){
829         return HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING;
830     }
831 
832     if (strncmp(line_buffer+offset, HFP_HANG_UP_CALL, strlen(HFP_HANG_UP_CALL)) == 0){
833         return HFP_CMD_HANG_UP_CALL;
834     }
835 
836     if (strncmp(line_buffer+offset, HFP_ERROR, strlen(HFP_ERROR)) == 0){
837         return HFP_CMD_ERROR;
838     }
839 
840     if (strncmp(line_buffer+offset, HFP_RING, strlen(HFP_RING)) == 0){
841         return HFP_CMD_RING;
842     }
843 
844     if (isHandsFree && strncmp(line_buffer+offset, HFP_OK, strlen(HFP_OK)) == 0){
845         return HFP_CMD_OK;
846     }
847 
848     if (strncmp(line_buffer+offset, HFP_SUPPORTED_FEATURES, strlen(HFP_SUPPORTED_FEATURES)) == 0){
849         return HFP_CMD_SUPPORTED_FEATURES;
850     }
851 
852     if (strncmp(line_buffer+offset, HFP_TRANSFER_HF_INDICATOR_STATUS, strlen(HFP_TRANSFER_HF_INDICATOR_STATUS)) == 0){
853         return HFP_CMD_HF_INDICATOR_STATUS;
854     }
855 
856     if (strncmp(line_buffer+offset, HFP_RESPONSE_AND_HOLD, strlen(HFP_RESPONSE_AND_HOLD)) == 0){
857         if (strncmp(line_buffer+strlen(HFP_RESPONSE_AND_HOLD)+offset, "?", 1) == 0){
858             return HFP_CMD_RESPONSE_AND_HOLD_QUERY;
859         }
860         if (strncmp(line_buffer+strlen(HFP_RESPONSE_AND_HOLD)+offset, "=", 1) == 0){
861             return HFP_CMD_RESPONSE_AND_HOLD_COMMAND;
862         }
863         return HFP_CMD_RESPONSE_AND_HOLD_STATUS;
864     }
865 
866     if (strncmp(line_buffer+offset, HFP_INDICATOR, strlen(HFP_INDICATOR)) == 0){
867         if (strncmp(line_buffer+strlen(HFP_INDICATOR)+offset, "?", 1) == 0){
868             return HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
869         }
870 
871         if (strncmp(line_buffer+strlen(HFP_INDICATOR)+offset, "=?", 2) == 0){
872             return HFP_CMD_RETRIEVE_AG_INDICATORS;
873         }
874     }
875 
876     if (strncmp(line_buffer+offset, HFP_AVAILABLE_CODECS, strlen(HFP_AVAILABLE_CODECS)) == 0){
877         return HFP_CMD_AVAILABLE_CODECS;
878     }
879 
880     if (strncmp(line_buffer+offset, HFP_ENABLE_STATUS_UPDATE_FOR_AG_INDICATORS, strlen(HFP_ENABLE_STATUS_UPDATE_FOR_AG_INDICATORS)) == 0){
881         return HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE;
882     }
883 
884     if (strncmp(line_buffer+offset, HFP_ENABLE_CLIP, strlen(HFP_ENABLE_CLIP)) == 0){
885         if (isHandsFree) return HFP_CMD_AG_SENT_CLIP_INFORMATION;
886         return HFP_CMD_ENABLE_CLIP;
887     }
888 
889     if (strncmp(line_buffer+offset, HFP_ENABLE_CALL_WAITING_NOTIFICATION, strlen(HFP_ENABLE_CALL_WAITING_NOTIFICATION)) == 0){
890         if (isHandsFree) return HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE;
891         return HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION;
892     }
893 
894     if (strncmp(line_buffer+offset, HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES, strlen(HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES)) == 0){
895 
896         if (isHandsFree) return HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES;
897 
898         if (strncmp(line_buffer+strlen(HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES)+offset, "=?", 2) == 0){
899             return HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES;
900         }
901         if (strncmp(line_buffer+strlen(HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES)+offset, "=", 1) == 0){
902             return HFP_CMD_CALL_HOLD;
903         }
904 
905         return HFP_CMD_UNKNOWN;
906     }
907 
908     if (strncmp(line_buffer+offset, HFP_GENERIC_STATUS_INDICATOR, strlen(HFP_GENERIC_STATUS_INDICATOR)) == 0){
909         if (isHandsFree) {
910             return HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS;
911         }
912         if (strncmp(line_buffer+strlen(HFP_GENERIC_STATUS_INDICATOR)+offset, "=?", 2) == 0){
913             return HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS;
914         }
915         if (strncmp(line_buffer+strlen(HFP_GENERIC_STATUS_INDICATOR)+offset, "=", 1) == 0){
916             return HFP_CMD_LIST_GENERIC_STATUS_INDICATORS;
917         }
918         return HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE;
919     }
920 
921     if (strncmp(line_buffer+offset, HFP_UPDATE_ENABLE_STATUS_FOR_INDIVIDUAL_AG_INDICATORS, strlen(HFP_UPDATE_ENABLE_STATUS_FOR_INDIVIDUAL_AG_INDICATORS)) == 0){
922         return HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE;
923     }
924 
925 
926     if (strncmp(line_buffer+offset, HFP_QUERY_OPERATOR_SELECTION, strlen(HFP_QUERY_OPERATOR_SELECTION)) == 0){
927         if (strncmp(line_buffer+strlen(HFP_QUERY_OPERATOR_SELECTION)+offset, "=", 1) == 0){
928             return HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT;
929         }
930         return HFP_CMD_QUERY_OPERATOR_SELECTION_NAME;
931     }
932 
933     if (strncmp(line_buffer+offset, HFP_TRANSFER_AG_INDICATOR_STATUS, strlen(HFP_TRANSFER_AG_INDICATOR_STATUS)) == 0){
934         return HFP_CMD_TRANSFER_AG_INDICATOR_STATUS;
935     }
936 
937     if (isHandsFree && strncmp(line_buffer+offset, HFP_EXTENDED_AUDIO_GATEWAY_ERROR, strlen(HFP_EXTENDED_AUDIO_GATEWAY_ERROR)) == 0){
938         return HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR;
939     }
940 
941     if (!isHandsFree && strncmp(line_buffer+offset, HFP_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR, strlen(HFP_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR)) == 0){
942         return HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR;
943     }
944 
945     if (strncmp(line_buffer+offset, HFP_TRIGGER_CODEC_CONNECTION_SETUP, strlen(HFP_TRIGGER_CODEC_CONNECTION_SETUP)) == 0){
946         return HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP;
947     }
948 
949     if (strncmp(line_buffer+offset, HFP_CONFIRM_COMMON_CODEC, strlen(HFP_CONFIRM_COMMON_CODEC)) == 0){
950         if (isHandsFree){
951             return HFP_CMD_AG_SUGGESTED_CODEC;
952         } else {
953             return HFP_CMD_HF_CONFIRMED_CODEC;
954         }
955     }
956 
957     if (strncmp(line_buffer+offset, "AT+", 3) == 0){
958         log_info("process unknown HF command %s \n", line_buffer);
959         return HFP_CMD_UNKNOWN;
960     }
961 
962     if (strncmp(line_buffer+offset, "+", 1) == 0){
963         log_info(" process unknown AG command %s \n", line_buffer);
964         return HFP_CMD_UNKNOWN;
965     }
966 
967     if (strncmp(line_buffer+offset, "NOP", 3) == 0){
968         return HFP_CMD_NONE;
969     }
970 
971     return HFP_CMD_NONE;
972 }
973 
974 static void hfp_parser_store_byte(hfp_connection_t * hfp_connection, uint8_t byte){
975     // printf("hfp_parser_store_byte %c at pos %u\n", (char) byte, context->line_size);
976     // TODO: add limit
977     hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
978     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
979 }
980 static int hfp_parser_is_buffer_empty(hfp_connection_t * hfp_connection){
981     return hfp_connection->line_size == 0;
982 }
983 
984 static int hfp_parser_is_end_of_line(uint8_t byte){
985     return byte == '\n' || byte == '\r';
986 }
987 
988 static int hfp_parser_is_end_of_header(uint8_t byte){
989     return hfp_parser_is_end_of_line(byte) || byte == ':' || byte == '?';
990 }
991 
992 static int hfp_parser_found_separator(hfp_connection_t * hfp_connection, uint8_t byte){
993     if (hfp_connection->keep_byte == 1) return 1;
994 
995     int found_separator =   byte == ',' || byte == '\n'|| byte == '\r'||
996                             byte == ')' || byte == '(' || byte == ':' ||
997                             byte == '-' || byte == '"' ||  byte == '?'|| byte == '=';
998     return found_separator;
999 }
1000 
1001 static void hfp_parser_next_state(hfp_connection_t * hfp_connection, uint8_t byte){
1002     hfp_connection->line_size = 0;
1003     if (hfp_parser_is_end_of_line(byte)){
1004         hfp_connection->parser_item_index = 0;
1005         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1006         return;
1007     }
1008     switch (hfp_connection->parser_state){
1009         case HFP_PARSER_CMD_HEADER:
1010             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1011             if (hfp_connection->keep_byte == 1){
1012                 hfp_parser_store_byte(hfp_connection, byte);
1013                 hfp_connection->keep_byte = 0;
1014             }
1015             break;
1016         case HFP_PARSER_CMD_SEQUENCE:
1017             switch (hfp_connection->command){
1018                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1019                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1020                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1021                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1022                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1023                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1024                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1025                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1026                 case HFP_CMD_HF_INDICATOR_STATUS:
1027                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
1028                     break;
1029                 default:
1030                     break;
1031             }
1032             break;
1033         case HFP_PARSER_SECOND_ITEM:
1034             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
1035             break;
1036         case HFP_PARSER_THIRD_ITEM:
1037             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){
1038                 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1039                 break;
1040             }
1041             hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1042             break;
1043     }
1044 }
1045 
1046 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1047     // handle ATD<dial_string>;
1048     if (strncmp((const char*)hfp_connection->line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0){
1049         // check for end-of-line or ';'
1050         if (byte == ';' || hfp_parser_is_end_of_line(byte)){
1051             hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1052             hfp_connection->line_size = 0;
1053             hfp_connection->command = HFP_CMD_CALL_PHONE_NUMBER;
1054         } else {
1055             hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
1056         }
1057         return;
1058     }
1059 
1060     // TODO: handle space inside word
1061     if (byte == ' ' && hfp_connection->parser_state > HFP_PARSER_CMD_HEADER) return;
1062 
1063     if (byte == ',' && hfp_connection->command == HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE){
1064         if (hfp_connection->line_size == 0){
1065             hfp_connection->line_buffer[0] = 0;
1066             hfp_connection->ignore_value = 1;
1067             parse_sequence(hfp_connection);
1068             return;
1069         }
1070     }
1071 
1072     if (!hfp_parser_found_separator(hfp_connection, byte)){
1073         hfp_parser_store_byte(hfp_connection, byte);
1074         return;
1075     }
1076 
1077     if (hfp_parser_is_end_of_line(byte)) {
1078         if (hfp_parser_is_buffer_empty(hfp_connection)){
1079             hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1080         }
1081     }
1082     if (hfp_parser_is_buffer_empty(hfp_connection)) return;
1083 
1084     switch (hfp_connection->parser_state){
1085         case HFP_PARSER_CMD_HEADER: // header
1086             if (byte == '='){
1087                 hfp_connection->keep_byte = 1;
1088                 hfp_parser_store_byte(hfp_connection, byte);
1089                 return;
1090             }
1091 
1092             if (byte == '?'){
1093                 hfp_connection->keep_byte = 0;
1094                 hfp_parser_store_byte(hfp_connection, byte);
1095                 return;
1096             }
1097 
1098             if (byte == ','){
1099                 hfp_connection->resolve_byte = 1;
1100             }
1101 
1102             // printf(" parse header 2 %s, keep separator $ %d\n", hfp_connection->line_buffer, hfp_connection->keep_byte);
1103             if (hfp_parser_is_end_of_header(byte) || hfp_connection->keep_byte == 1){
1104                 // printf(" parse header 3 %s, keep separator $ %d\n", hfp_connection->line_buffer, hfp_connection->keep_byte);
1105                 char * line_buffer = (char *)hfp_connection->line_buffer;
1106                 hfp_connection->command = parse_command(line_buffer, isHandsFree);
1107 
1108                 /* resolve command name according to hfp_connection */
1109                 if (hfp_connection->command == HFP_CMD_UNKNOWN){
1110                     switch(hfp_connection->state){
1111                         case HFP_W4_LIST_GENERIC_STATUS_INDICATORS:
1112                             hfp_connection->command = HFP_CMD_LIST_GENERIC_STATUS_INDICATORS;
1113                             break;
1114                         case HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS:
1115                             hfp_connection->command = HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS;
1116                             break;
1117                         case HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS:
1118                             hfp_connection->command = HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE;
1119                             break;
1120                         case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1121                             hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
1122                             break;
1123                         case HFP_W4_RETRIEVE_INDICATORS:
1124                             hfp_connection->send_ag_indicators_segment = 0;
1125                             hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS;
1126                             break;
1127                         default:
1128                             break;
1129                     }
1130                 }
1131             }
1132             break;
1133 
1134         case HFP_PARSER_CMD_SEQUENCE:
1135             parse_sequence(hfp_connection);
1136             break;
1137         case HFP_PARSER_SECOND_ITEM:
1138             switch (hfp_connection->command){
1139                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1140                     log_info("format %s, ", hfp_connection->line_buffer);
1141                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1142                     break;
1143                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1144                     log_info("format %s \n", hfp_connection->line_buffer);
1145                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1146                     break;
1147                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1148                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1149                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1150                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1151                     break;
1152                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1153                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1154                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1155                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1156                     break;
1157                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1158                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer);
1159                     log_info("%s, ", hfp_connection->line_buffer);
1160                     break;
1161                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1162                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1163                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1164                     hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1165                     break;
1166                 default:
1167                     break;
1168             }
1169             break;
1170 
1171         case HFP_PARSER_THIRD_ITEM:
1172              switch (hfp_connection->command){
1173                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1174                     strncpy(hfp_connection->network_operator.name, (char *)hfp_connection->line_buffer, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE);
1175                     hfp_connection->network_operator.name[HFP_MAX_NETWORK_OPERATOR_NAME_SIZE - 1] = 0;
1176                     log_info("name %s\n", hfp_connection->line_buffer);
1177                     break;
1178                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1179                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer);
1180                     hfp_connection->parser_item_index++;
1181                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1182                     log_info("%s)\n", hfp_connection->line_buffer);
1183                     break;
1184                 default:
1185                     break;
1186             }
1187             break;
1188     }
1189     hfp_parser_next_state(hfp_connection, byte);
1190 
1191     if (hfp_connection->resolve_byte && hfp_connection->command == HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE){
1192         hfp_connection->resolve_byte = 0;
1193         hfp_connection->ignore_value = 1;
1194         parse_sequence(hfp_connection);
1195         hfp_connection->line_buffer[0] = 0;
1196         hfp_connection->line_size = 0;
1197     }
1198 }
1199 
1200 static void parse_sequence(hfp_connection_t * hfp_connection){
1201     int value;
1202     switch (hfp_connection->command){
1203         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1204             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1205             int i;
1206             switch (hfp_connection->parser_item_index){
1207                 case 0:
1208                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1209                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1210                             hfp_connection->parser_indicator_index = i;
1211                             break;
1212                         }
1213                     }
1214                     break;
1215                 case 1:
1216                     if (hfp_connection->parser_indicator_index <0) break;
1217                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1218                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1219                      hfp_connection->parser_item_index, value);
1220                     break;
1221                 default:
1222                     break;
1223             }
1224             hfp_connection->parser_item_index++;
1225             break;
1226 
1227         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1228             switch(hfp_connection->parser_item_index){
1229                 case 0:
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 1:
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_LIST_CURRENT_CALLS:
1243             switch(hfp_connection->parser_item_index){
1244                 case 0:
1245                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1246                     hfp_connection->clcc_idx = value;
1247                     break;
1248                 case 1:
1249                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1250                     hfp_connection->clcc_dir = value;
1251                     break;
1252                 case 2:
1253                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1254                     hfp_connection->clcc_status = value;
1255                     break;
1256                 case 3:
1257                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1258                     hfp_connection->clcc_mpty = value;
1259                     break;
1260                 case 4:
1261                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1262                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1263                     break;
1264                 case 5:
1265                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1266                     hfp_connection->bnip_type = value;
1267                     break;
1268                 default:
1269                     break;
1270             }
1271             hfp_connection->parser_item_index++;
1272             break;
1273         case HFP_CMD_SET_MICROPHONE_GAIN:
1274             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1275             hfp_connection->microphone_gain = value;
1276             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1277             break;
1278         case HFP_CMD_SET_SPEAKER_GAIN:
1279             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1280             hfp_connection->speaker_gain = value;
1281             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1282             break;
1283         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1284             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1285             hfp_connection->ag_activate_voice_recognition = value;
1286             log_info("hfp parse HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION %d\n", value);
1287             break;
1288         case HFP_CMD_TURN_OFF_EC_AND_NR:
1289             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1290             hfp_connection->ag_echo_and_noise_reduction = value;
1291             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1292             break;
1293         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1294             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1295             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1296             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1297             break;
1298         case HFP_CMD_HF_CONFIRMED_CODEC:
1299             hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer);
1300             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1301             break;
1302         case HFP_CMD_AG_SUGGESTED_CODEC:
1303             hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer);
1304             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1305             break;
1306         case HFP_CMD_SUPPORTED_FEATURES:
1307             hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer);
1308             log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features);
1309             break;
1310         case HFP_CMD_AVAILABLE_CODECS:
1311             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1312             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1313             hfp_connection->parser_item_index++;
1314             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1315             break;
1316         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1317             strncpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name,  (char *)hfp_connection->line_buffer, HFP_MAX_INDICATOR_DESC_SIZE);
1318             hfp_connection->ag_indicators[hfp_connection->parser_item_index].name[HFP_MAX_INDICATOR_DESC_SIZE-1] = 0;
1319             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1320             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1321             break;
1322         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1323             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1324             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer);
1325             hfp_connection->parser_item_index++;
1326             break;
1327         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1328             hfp_connection->parser_item_index++;
1329             if (hfp_connection->parser_item_index != 4) break;
1330             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1331             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1332             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1333             break;
1334         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1335             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1336             if (hfp_connection->line_size > 2 ) break;
1337             strncpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_nr].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE);
1338             hfp_connection->remote_call_services[hfp_connection->remote_call_services_nr].name[HFP_CALL_SERVICE_SIZE - 1] = 0;
1339             hfp_connection->remote_call_services_nr++;
1340             break;
1341         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1342         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1343             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1344             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1345             hfp_connection->parser_item_index++;
1346             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1347             break;
1348         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1349             // HF parses inital AG gen. ind. state
1350             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1351             hfp_connection->parser_item_index = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1352             break;
1353         case HFP_CMD_HF_INDICATOR_STATUS:
1354             hfp_connection->parser_indicator_index = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1355             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1356             break;
1357         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1358             // AG parses new gen. ind. state
1359             if (hfp_connection->ignore_value){
1360                 hfp_connection->ignore_value = 0;
1361                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1362                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1363             }
1364             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1365                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1366                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1367             } else {
1368                 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1369                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1370                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1371                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1372             }
1373             hfp_connection->parser_item_index++;
1374             break;
1375         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1376             // indicators are indexed starting with 1
1377             hfp_connection->parser_item_index = btstack_atoi((char *)&hfp_connection->line_buffer[0]) - 1;
1378             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1379             break;
1380         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1381             hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1382             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1383             break;
1384         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1385             if (hfp_connection->line_buffer[0] == '3'){
1386                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1387                 break;
1388             }
1389             // TODO emit ERROR, wrong format
1390             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1391             break;
1392         case HFP_CMD_ERROR:
1393             break;
1394         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1395             hfp_connection->extended_audio_gateway_error = 1;
1396             hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1397             break;
1398         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1399             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1400             hfp_connection->ok_pending = 1;
1401             hfp_connection->extended_audio_gateway_error = 0;
1402             break;
1403         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1404         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1405         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1406             strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1407             hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1408             break;
1409         default:
1410             break;
1411     }
1412 }
1413 
1414 void hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){
1415     hfp_connection_t * hfp_connection = provide_hfp_connection_context_for_bd_addr(bd_addr, local_role);
1416     log_info("hfp_connect %s, hfp_connection %p", bd_addr_to_str(bd_addr), hfp_connection);
1417 
1418     if (!hfp_connection) {
1419         log_error("hfp_establish_service_level_connection for addr %s failed", bd_addr_to_str(bd_addr));
1420         return;
1421     }
1422 
1423     switch (hfp_connection->state){
1424         case HFP_W2_DISCONNECT_RFCOMM:
1425             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1426             return;
1427         case HFP_W4_RFCOMM_DISCONNECTED:
1428             hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART;
1429             return;
1430         case HFP_IDLE:
1431             memcpy(hfp_connection->remote_addr, bd_addr, 6);
1432             hfp_connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1433             connection_doing_sdp_query = hfp_connection;
1434             hfp_connection->service_uuid = service_uuid;
1435             sdp_client_query_rfcomm_channel_and_name_for_uuid(&handle_query_rfcomm_event, hfp_connection->remote_addr, service_uuid);
1436             break;
1437         default:
1438             break;
1439     }
1440 }
1441 
1442 void hfp_release_service_level_connection(hfp_connection_t * hfp_connection){
1443     if (!hfp_connection) return;
1444     hfp_release_audio_connection(hfp_connection);
1445 
1446     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1447         hfp_connection->state = HFP_IDLE;
1448         return;
1449     }
1450 
1451     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1452         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1453         return;
1454     }
1455 
1456     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1457         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1458         return;
1459     }
1460 
1461     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1462         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1463         return;
1464     }
1465 
1466     return;
1467 }
1468 
1469 void hfp_release_audio_connection(hfp_connection_t * hfp_connection){
1470     if (!hfp_connection) return;
1471     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
1472     hfp_connection->release_audio_connection = 1;
1473 }
1474 
1475 static const struct link_settings {
1476     const uint16_t max_latency;
1477     const uint8_t  retransmission_effort;
1478     const uint16_t packet_types;
1479 } hfp_link_settings [] = {
1480     { 0xffff, 0xff, 0x03c1 }, // HFP_LINK_SETTINGS_D0,   HV1
1481     { 0xffff, 0xff, 0x03c4 }, // HFP_LINK_SETTINGS_D1,   HV3
1482     { 0x0007, 0x01, 0x03c8 }, // HFP_LINK_SETTINGS_S1,   EV3
1483     { 0x0007, 0x01, 0x0380 }, // HFP_LINK_SETTINGS_S2, 2-EV3
1484     { 0x000a, 0x01, 0x0380 }, // HFP_LINK_SETTINGS_S3, 2-EV3
1485     { 0x000c, 0x02, 0x0380 }, // HFP_LINK_SETTINGS_S4, 2-EV3
1486     { 0x0008, 0x02, 0x03c8 }, // HFP_LINK_SETTINGS_T1,   EV3
1487     { 0x000d, 0x02, 0x0380 }  // HFP_LINK_SETTINGS_T2, 2-EV3
1488 };
1489 
1490 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){
1491     // all packet types, fixed bandwidth
1492     int setting = hfp_connection->link_setting;
1493     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1494     sco_establishment_active = hfp_connection;
1495     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1496     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1497         sco_voice_setting = 0x0043; // Transparent data
1498     }
1499     hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency,
1500         sco_voice_setting, hfp_link_settings[setting].retransmission_effort, hfp_link_settings[setting].packet_types); // all types 0x003f, only 2-ev3 0x380
1501 }
1502 
1503 void hfp_set_hf_callback(btstack_packet_handler_t callback){
1504     hfp_hf_callback = callback;
1505 }
1506 
1507 void hfp_set_ag_callback(btstack_packet_handler_t callback){
1508     hfp_ag_callback = callback;
1509 }
1510 
1511 void hfp_set_ag_rfcomm_packet_handler(btstack_packet_handler_t handler){
1512     hfp_ag_rfcomm_packet_handler = handler;
1513 }
1514 
1515 void hfp_set_hf_rfcomm_packet_handler(btstack_packet_handler_t handler){
1516     hfp_hf_rfcomm_packet_handler = handler;
1517 }
1518 
1519 void hfp_set_hf_run_for_context(void (*callback)(hfp_connection_t * hfp_connection)){
1520     hfp_hf_run_for_context = callback;
1521 }
1522 
1523 void hfp_init(void){
1524 }
1525 
1526 #define HFP_HF_RX_DEBUG_PRINT_LINE 80
1527 
1528 void hfp_log_rfcomm_message(const char * tag, uint8_t * packet, uint16_t size){
1529 #ifdef ENABLE_LOG_INFO
1530     // encode \n\r
1531     char printable[HFP_HF_RX_DEBUG_PRINT_LINE+2];
1532     int i;
1533     int pos;
1534     for (i=0,pos=0;(pos < size) && (i < (HFP_HF_RX_DEBUG_PRINT_LINE - 3)); pos++){
1535         switch (packet[pos]){
1536             case '\n':
1537                 printable[i++] = '\\';
1538                 printable[i++] = 'n';
1539                 break;
1540             case '\r':
1541                 printable[i++] = '\\';
1542                 printable[i++] = 'r';
1543                 break;
1544             default:
1545                 printable[i++] = packet[pos];
1546                 break;
1547         }
1548     }
1549     printable[i] = 0;
1550     log_info("%s: '%s'", tag, printable);
1551 #endif
1552 }
1553