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