xref: /btstack/src/classic/hfp.c (revision b3fcedb9c9ccbcc9680da165cd86f394be5d84a8)
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 
39 #include "btstack_config.h"
40 
41 #include <stdint.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <inttypes.h>
46 
47 #include "btstack_debug.h"
48 #include "btstack_event.h"
49 #include "btstack_memory.h"
50 #include "btstack_run_loop.h"
51 #include "classic/core.h"
52 #include "classic/sdp_client_rfcomm.h"
53 #include "classic/sdp_server.h"
54 #include "classic/sdp_util.h"
55 #include "hci.h"
56 #include "hci_cmd.h"
57 #include "hci_dump.h"
58 #include "l2cap.h"
59 
60 #define HFP_HF_FEATURES_SIZE 10
61 #define HFP_AG_FEATURES_SIZE 12
62 
63 
64 static const char * hfp_hf_features[] = {
65     "EC and/or NR function",
66     "Three-way calling",
67     "CLI presentation capability",
68     "Voice recognition activation",
69     "Remote volume control",
70 
71     "Enhanced call status",
72     "Enhanced call control",
73 
74     "Codec negotiation",
75 
76     "HF Indicators",
77     "eSCO S4 (and T2) Settings Supported",
78     "Reserved for future definition"
79 };
80 
81 static const char * hfp_ag_features[] = {
82     "Three-way calling",
83     "EC and/or NR function",
84     "Voice recognition function",
85     "In-band ring tone capability",
86     "Attach a number to a voice tag",
87     "Ability to reject a call",
88     "Enhanced call status",
89     "Enhanced call control",
90     "Extended Error Result Codes",
91     "Codec negotiation",
92     "HF Indicators",
93     "eSCO S4 (and T2) Settings Supported",
94     "Reserved for future definition"
95 };
96 
97 static btstack_linked_list_t hfp_connections = NULL;
98 static void parse_sequence(hfp_connection_t * context);
99 static hfp_callback_t hfp_callback;
100 static btstack_packet_handler_t rfcomm_packet_handler;
101 
102 void hfp_set_callback(hfp_callback_t callback){
103     hfp_callback = callback;
104 }
105 
106 const char * hfp_hf_feature(int index){
107     if (index > HFP_HF_FEATURES_SIZE){
108         return hfp_hf_features[HFP_HF_FEATURES_SIZE];
109     }
110     return hfp_hf_features[index];
111 }
112 
113 const char * hfp_ag_feature(int index){
114     if (index > HFP_AG_FEATURES_SIZE){
115         return hfp_ag_features[HFP_AG_FEATURES_SIZE];
116     }
117     return hfp_ag_features[index];
118 }
119 
120 int send_str_over_rfcomm(uint16_t cid, char * command){
121     if (!rfcomm_can_send_packet_now(cid)) return 1;
122     log_info("HFP_TX %s", command);
123     int err = rfcomm_send(cid, (uint8_t*) command, strlen(command));
124     if (err){
125         log_error("rfcomm_send -> error 0x%02x \n", err);
126     }
127     return 1;
128 }
129 
130 #if 0
131 void hfp_set_codec(hfp_connection_t * hfp_connection, uint8_t *packet, uint16_t size){
132     // parse available codecs
133     int pos = 0;
134     int i;
135     for (i=0; i<size; i++){
136         pos+=8;
137         if (packet[pos] > hfp_connection->negotiated_codec){
138             hfp_connection->negotiated_codec = packet[pos];
139         }
140     }
141     printf("Negotiated Codec 0x%02x\n", hfp_connection->negotiated_codec);
142 }
143 #endif
144 
145 // UTILS
146 int get_bit(uint16_t bitmap, int position){
147     return (bitmap >> position) & 1;
148 }
149 
150 int store_bit(uint32_t bitmap, int position, uint8_t value){
151     if (value){
152         bitmap |= 1 << position;
153     } else {
154         bitmap &= ~ (1 << position);
155     }
156     return bitmap;
157 }
158 
159 int join(char * buffer, int buffer_size, uint8_t * values, int values_nr){
160     if (buffer_size < values_nr * 3) return 0;
161     int i;
162     int offset = 0;
163     for (i = 0; i < values_nr-1; i++) {
164       offset += snprintf(buffer+offset, buffer_size-offset, "%d,", values[i]); // puts string into buffer
165     }
166     if (i<values_nr){
167         offset += snprintf(buffer+offset, buffer_size-offset, "%d", values[i]);
168     }
169     return offset;
170 }
171 
172 int join_bitmap(char * buffer, int buffer_size, uint32_t values, int values_nr){
173     if (buffer_size < values_nr * 3) return 0;
174 
175     int i;
176     int offset = 0;
177     for (i = 0; i < values_nr-1; i++) {
178       offset += snprintf(buffer+offset, buffer_size-offset, "%d,", get_bit(values,i)); // puts string into buffer
179     }
180 
181     if (i<values_nr){
182         offset += snprintf(buffer+offset, buffer_size-offset, "%d", get_bit(values,i));
183     }
184     return offset;
185 }
186 
187 void hfp_emit_simple_event(hfp_callback_t callback, uint8_t event_subtype){
188     if (!callback) return;
189     uint8_t event[3];
190     event[0] = HCI_EVENT_HFP_META;
191     event[1] = sizeof(event) - 2;
192     event[2] = event_subtype;
193     (*callback)(event, sizeof(event));
194 }
195 
196 void hfp_emit_event(hfp_callback_t callback, uint8_t event_subtype, uint8_t value){
197     if (!callback) return;
198     uint8_t event[4];
199     event[0] = HCI_EVENT_HFP_META;
200     event[1] = sizeof(event) - 2;
201     event[2] = event_subtype;
202     event[3] = value; // status 0 == OK
203     (*callback)(event, sizeof(event));
204 }
205 
206 void hfp_emit_connection_event(hfp_callback_t callback, uint8_t event_subtype, uint8_t status, hci_con_handle_t con_handle){
207     if (!callback) return;
208     uint8_t event[6];
209     event[0] = HCI_EVENT_HFP_META;
210     event[1] = sizeof(event) - 2;
211     event[2] = event_subtype;
212     event[3] = status; // status 0 == OK
213     little_endian_store_16(event, 4, con_handle);
214     (*callback)(event, sizeof(event));
215 }
216 
217 void hfp_emit_string_event(hfp_callback_t callback, uint8_t event_subtype, const char * value){
218     if (!callback) return;
219     uint8_t event[40];
220     event[0] = HCI_EVENT_HFP_META;
221     event[1] = sizeof(event) - 2;
222     event[2] = event_subtype;
223     int size = (strlen(value) < sizeof(event) - 4) ? strlen(value) : sizeof(event) - 4;
224     strncpy((char*)&event[3], value, size);
225     event[3 + size] = 0;
226     (*callback)(event, sizeof(event));
227 }
228 
229 btstack_linked_list_t * hfp_get_connections(void){
230     return (btstack_linked_list_t *) &hfp_connections;
231 }
232 
233 hfp_connection_t * get_hfp_connection_context_for_rfcomm_cid(uint16_t cid){
234     btstack_linked_list_iterator_t it;
235     btstack_linked_list_iterator_init(&it, hfp_get_connections());
236     while (btstack_linked_list_iterator_has_next(&it)){
237         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
238         if (hfp_connection->rfcomm_cid == cid){
239             return hfp_connection;
240         }
241     }
242     return NULL;
243 }
244 
245 hfp_connection_t * get_hfp_connection_context_for_bd_addr(bd_addr_t bd_addr){
246     btstack_linked_list_iterator_t it;
247     btstack_linked_list_iterator_init(&it, hfp_get_connections());
248     while (btstack_linked_list_iterator_has_next(&it)){
249         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
250         if (memcmp(hfp_connection->remote_addr, bd_addr, 6) == 0) {
251             return hfp_connection;
252         }
253     }
254     return NULL;
255 }
256 
257 hfp_connection_t * get_hfp_connection_context_for_sco_handle(uint16_t handle){
258     btstack_linked_list_iterator_t it;
259     btstack_linked_list_iterator_init(&it, hfp_get_connections());
260     while (btstack_linked_list_iterator_has_next(&it)){
261         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
262         if (hfp_connection->sco_handle == handle){
263             return hfp_connection;
264         }
265     }
266     return NULL;
267 }
268 
269 void hfp_reset_context_flags(hfp_connection_t * hfp_connection){
270     if (!hfp_connection) return;
271     hfp_connection->ok_pending = 0;
272     hfp_connection->send_error = 0;
273 
274     hfp_connection->keep_byte = 0;
275 
276     hfp_connection->change_status_update_for_individual_ag_indicators = 0;
277     hfp_connection->operator_name_changed = 0;
278 
279     hfp_connection->enable_extended_audio_gateway_error_report = 0;
280     hfp_connection->extended_audio_gateway_error = 0;
281 
282     // establish codecs hfp_connection
283     hfp_connection->suggested_codec = 0;
284     hfp_connection->negotiated_codec = 0;
285     hfp_connection->codec_confirmed = 0;
286 
287     hfp_connection->establish_audio_connection = 0;
288     hfp_connection->call_waiting_notification_enabled = 0;
289     hfp_connection->command = HFP_CMD_NONE;
290     hfp_connection->enable_status_update_for_ag_indicators = 0xFF;
291 }
292 
293 static hfp_connection_t * create_hfp_connection_context(void){
294     hfp_connection_t * hfp_connection = btstack_memory_hfp_connection_get();
295     if (!hfp_connection) return NULL;
296     // init state
297     memset(hfp_connection,0, sizeof(hfp_connection_t));
298 
299     hfp_connection->state = HFP_IDLE;
300     hfp_connection->call_state = HFP_CALL_IDLE;
301     hfp_connection->codecs_state = HFP_CODECS_IDLE;
302 
303     hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
304     hfp_connection->command = HFP_CMD_NONE;
305 
306     hfp_reset_context_flags(hfp_connection);
307 
308     btstack_linked_list_add(&hfp_connections, (btstack_linked_item_t*)hfp_connection);
309     return hfp_connection;
310 }
311 
312 static void remove_hfp_connection_context(hfp_connection_t * hfp_connection){
313     btstack_linked_list_remove(&hfp_connections, (btstack_linked_item_t*) hfp_connection);
314 }
315 
316 static hfp_connection_t * provide_hfp_connection_context_for_bd_addr(bd_addr_t bd_addr){
317     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(bd_addr);
318     if (hfp_connection) return  hfp_connection;
319     hfp_connection = create_hfp_connection_context();
320     printf("created hfp_connection for address %s\n", bd_addr_to_str(bd_addr));
321     memcpy(hfp_connection->remote_addr, bd_addr, 6);
322     return hfp_connection;
323 }
324 
325 /* @param network.
326  * 0 == no ability to reject a call.
327  * 1 == ability to reject a call.
328  */
329 
330 /* @param suported_features
331  * HF bit 0: EC and/or NR function (yes/no, 1 = yes, 0 = no)
332  * HF bit 1: Call waiting or three-way calling(yes/no, 1 = yes, 0 = no)
333  * HF bit 2: CLI presentation capability (yes/no, 1 = yes, 0 = no)
334  * HF bit 3: Voice recognition activation (yes/no, 1= yes, 0 = no)
335  * HF bit 4: Remote volume control (yes/no, 1 = yes, 0 = no)
336  * HF bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
337  */
338  /* Bit position:
339  * AG bit 0: Three-way calling (yes/no, 1 = yes, 0 = no)
340  * AG bit 1: EC and/or NR function (yes/no, 1 = yes, 0 = no)
341  * AG bit 2: Voice recognition function (yes/no, 1 = yes, 0 = no)
342  * AG bit 3: In-band ring tone capability (yes/no, 1 = yes, 0 = no)
343  * AG bit 4: Attach a phone number to a voice tag (yes/no, 1 = yes, 0 = no)
344  * AG bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
345  */
346 
347 void hfp_create_sdp_record(uint8_t * service, uint32_t service_record_handle, uint16_t service_uuid, int rfcomm_channel_nr, const char * name){
348     uint8_t* attribute;
349     de_create_sequence(service);
350 
351     // 0x0000 "Service Record Handle"
352     de_add_number(service, DE_UINT, DE_SIZE_16, SDP_ServiceRecordHandle);
353     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
354 
355     // 0x0001 "Service Class ID List"
356     de_add_number(service,  DE_UINT, DE_SIZE_16, SDP_ServiceClassIDList);
357     attribute = de_push_sequence(service);
358     {
359         //  "UUID for Service"
360         de_add_number(attribute, DE_UUID, DE_SIZE_16, service_uuid);
361         de_add_number(attribute, DE_UUID, DE_SIZE_16, SDP_GenericAudio);
362     }
363     de_pop_sequence(service, attribute);
364 
365     // 0x0004 "Protocol Descriptor List"
366     de_add_number(service,  DE_UINT, DE_SIZE_16, SDP_ProtocolDescriptorList);
367     attribute = de_push_sequence(service);
368     {
369         uint8_t* l2cpProtocol = de_push_sequence(attribute);
370         {
371             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, SDP_L2CAPProtocol);
372         }
373         de_pop_sequence(attribute, l2cpProtocol);
374 
375         uint8_t* rfcomm = de_push_sequence(attribute);
376         {
377             de_add_number(rfcomm,  DE_UUID, DE_SIZE_16, SDP_RFCOMMProtocol);  // rfcomm_service
378             de_add_number(rfcomm,  DE_UINT, DE_SIZE_8,  rfcomm_channel_nr);  // rfcomm channel
379         }
380         de_pop_sequence(attribute, rfcomm);
381     }
382     de_pop_sequence(service, attribute);
383 
384 
385     // 0x0005 "Public Browse Group"
386     de_add_number(service,  DE_UINT, DE_SIZE_16, SDP_BrowseGroupList); // public browse group
387     attribute = de_push_sequence(service);
388     {
389         de_add_number(attribute,  DE_UUID, DE_SIZE_16, SDP_PublicBrowseGroup);
390     }
391     de_pop_sequence(service, attribute);
392 
393     // 0x0009 "Bluetooth Profile Descriptor List"
394     de_add_number(service,  DE_UINT, DE_SIZE_16, SDP_BluetoothProfileDescriptorList);
395     attribute = de_push_sequence(service);
396     {
397         uint8_t *sppProfile = de_push_sequence(attribute);
398         {
399             de_add_number(sppProfile,  DE_UUID, DE_SIZE_16, SDP_Handsfree);
400             de_add_number(sppProfile,  DE_UINT, DE_SIZE_16, 0x0107); // Verision 1.7
401         }
402         de_pop_sequence(attribute, sppProfile);
403     }
404     de_pop_sequence(service, attribute);
405 
406     // 0x0100 "Service Name"
407     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
408     de_add_data(service,  DE_STRING, strlen(name), (uint8_t *) name);
409 }
410 
411 static hfp_connection_t * connection_doing_sdp_query = NULL;
412 
413 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
414     hfp_connection_t * hfp_connection = connection_doing_sdp_query;
415 
416     if ( hfp_connection->state != HFP_W4_SDP_QUERY_COMPLETE) return;
417 
418     switch (hci_event_packet_get_type(packet)){
419         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
420             if (!hfp_connection) {
421                 log_error("handle_query_rfcomm_event alloc connection for RFCOMM port %u failed", sdp_event_query_rfcomm_service_get_rfcomm_channel(packet));
422                 return;
423             }
424             hfp_connection->rfcomm_channel_nr = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
425             break;
426         case SDP_EVENT_QUERY_COMPLETE:
427             connection_doing_sdp_query = NULL;
428             if (hfp_connection->rfcomm_channel_nr > 0){
429                 hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
430                 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);
431                 rfcomm_create_channel(rfcomm_packet_handler, hfp_connection->remote_addr, hfp_connection->rfcomm_channel_nr, NULL);
432                 break;
433             }
434             log_info("rfcomm service not found, status %u.", sdp_event_query_complete_get_status(packet));
435             break;
436         default:
437             break;
438     }
439 }
440 
441 void hfp_handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
442     bd_addr_t event_addr;
443     uint16_t rfcomm_cid, handle;
444     hfp_connection_t * hfp_connection = NULL;
445     uint8_t status;
446 
447     // printf("AG packet_handler type %u, event type %x, size %u\n", packet_type, hci_event_packet_get_type(packet), size);
448 
449     switch (hci_event_packet_get_type(packet)) {
450 
451         case RFCOMM_EVENT_INCOMING_CONNECTION:
452             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
453             rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
454             hfp_connection = provide_hfp_connection_context_for_bd_addr(event_addr);
455             if (!hfp_connection || hfp_connection->state != HFP_IDLE) return;
456 
457             hfp_connection->rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
458             hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
459             // printf("RFCOMM channel %u requested for %s\n", hfp_connection->rfcomm_cid, bd_addr_to_str(hfp_connection->remote_addr));
460             rfcomm_accept_connection(hfp_connection->rfcomm_cid);
461             break;
462 
463         case RFCOMM_EVENT_CHANNEL_OPENED:
464             // data: event(8), len(8), status (8), address (48), handle(16), server channel(8), rfcomm_cid(16), max frame size(16)
465 
466             rfcomm_event_channel_opened_get_bd_addr(packet, event_addr);
467             status = rfcomm_event_channel_opened_get_status(packet);
468             // printf("RFCOMM_EVENT_CHANNEL_OPENED packet_handler adddr %s, status %u\n", bd_addr_to_str(event_addr), status);
469 
470             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr);
471             if (!hfp_connection || hfp_connection->state != HFP_W4_RFCOMM_CONNECTED) return;
472 
473             if (status) {
474                 hfp_emit_connection_event(hfp_callback, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_ESTABLISHED, status, rfcomm_event_channel_opened_get_con_handle(packet));
475                 remove_hfp_connection_context(hfp_connection);
476             } else {
477                 hfp_connection->acl_handle = rfcomm_event_channel_opened_get_con_handle(packet);
478                 hfp_connection->rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
479                 // uint16_t mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
480                 // 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);
481 
482                 switch (hfp_connection->state){
483                     case HFP_W4_RFCOMM_CONNECTED:
484                         hfp_connection->state = HFP_EXCHANGE_SUPPORTED_FEATURES;
485                         break;
486                     case HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN:
487                         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
488                         // printf("Shutting down RFCOMM.\n");
489                         break;
490                     default:
491                         break;
492                 }
493             }
494             break;
495 
496         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
497 
498             reverse_bd_addr(&packet[5], event_addr);
499             int index = 2;
500             status = packet[index++];
501 
502             if (status != 0){
503                 log_error("(e)SCO Connection failed status %u", status);
504                 // if outgoing && link_setting != d0 && appropriate error
505                 if (status != 0x11 && status != 0x1f) break;  // invalid params / unspecified error
506                 hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr);
507                 if (!hfp_connection) break;
508                 switch (hfp_connection->link_setting){
509                     case HFP_LINK_SETTINGS_D0:
510                         return; // no other option left
511                     case HFP_LINK_SETTINGS_D1:
512                         // hfp_connection->link_setting = HFP_LINK_SETTINGS_D0;
513                         // break;
514                     case HFP_LINK_SETTINGS_S1:
515                         // hfp_connection->link_setting = HFP_LINK_SETTINGS_D1;
516                         // break;
517                     case HFP_LINK_SETTINGS_S2:
518                     case HFP_LINK_SETTINGS_S3:
519                     case HFP_LINK_SETTINGS_S4:
520                         // hfp_connection->link_setting = HFP_LINK_SETTINGS_S1;
521                         // break;
522                     case HFP_LINK_SETTINGS_T1:
523                     case HFP_LINK_SETTINGS_T2:
524                         // hfp_connection->link_setting = HFP_LINK_SETTINGS_S3;
525                         hfp_connection->link_setting = HFP_LINK_SETTINGS_D0;
526                         break;
527                 }
528                 hfp_connection->establish_audio_connection = 1;
529                 break;
530             }
531 
532             uint16_t sco_handle = little_endian_read_16(packet, index);
533             index+=2;
534 
535             reverse_bd_addr(&packet[index], event_addr);
536             index+=6;
537 
538             uint8_t link_type = packet[index++];
539             uint8_t transmission_interval = packet[index++];  // measured in slots
540             uint8_t retransmission_interval = packet[index++];// measured in slots
541             uint16_t rx_packet_length = little_endian_read_16(packet, index); // measured in bytes
542             index+=2;
543             uint16_t tx_packet_length = little_endian_read_16(packet, index); // measured in bytes
544             index+=2;
545             uint8_t air_mode = packet[index];
546 
547             switch (link_type){
548                 case 0x00:
549                     log_info("SCO Connection established.");
550                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
551                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
552                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
553                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
554                     break;
555                 case 0x02:
556                     log_info("eSCO Connection established. \n");
557                     break;
558                 default:
559                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
560                     break;
561             }
562             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
563                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)\n", sco_handle,
564                  bd_addr_to_str(event_addr), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length, air_mode);
565 
566             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr);
567 
568             if (!hfp_connection) {
569                 log_error("SCO link created, hfp_connection for address %s not found.", bd_addr_to_str(event_addr));
570                 break;
571             }
572 
573             if (hfp_connection->state == HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){
574                 log_info("SCO about to disconnect: HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN");
575                 hfp_connection->state = HFP_W2_DISCONNECT_SCO;
576                 break;
577             }
578             hfp_connection->sco_handle = sco_handle;
579             hfp_connection->establish_audio_connection = 0;
580             hfp_connection->state = HFP_AUDIO_CONNECTION_ESTABLISHED;
581             hfp_emit_connection_event(hfp_callback, HFP_SUBEVENT_AUDIO_CONNECTION_ESTABLISHED, packet[2], sco_handle);
582             break;
583         }
584 
585         case RFCOMM_EVENT_CHANNEL_CLOSED:
586             rfcomm_cid = little_endian_read_16(packet,2);
587             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
588             if (!hfp_connection) break;
589             if (hfp_connection->state == HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART){
590                 hfp_connection->state = HFP_IDLE;
591                 hfp_establish_service_level_connection(hfp_connection->remote_addr, hfp_connection->service_uuid);
592                 break;
593             }
594 
595             hfp_emit_event(hfp_callback, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
596             remove_hfp_connection_context(hfp_connection);
597             break;
598 
599         case HCI_EVENT_DISCONNECTION_COMPLETE:
600             handle = little_endian_read_16(packet,3);
601             hfp_connection = get_hfp_connection_context_for_sco_handle(handle);
602 
603             if (!hfp_connection) break;
604 
605             if (hfp_connection->state != HFP_W4_SCO_DISCONNECTED){
606                 log_info("Received gap disconnect in wrong hfp state");
607             }
608             log_info("Check SCO handle: incoming 0x%02x, hfp_connection 0x%02x\n", handle, hfp_connection->sco_handle);
609 
610             if (handle == hfp_connection->sco_handle){
611                 log_info("SCO disconnected, w2 disconnect RFCOMM\n");
612                 hfp_connection->sco_handle = 0;
613                 hfp_connection->release_audio_connection = 0;
614                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
615                 hfp_emit_event(hfp_callback, HFP_SUBEVENT_AUDIO_CONNECTION_RELEASED, 0);
616                 break;
617             }
618             break;
619 
620         default:
621             break;
622     }
623 }
624 
625 // translates command string into hfp_command_t CMD
626 static hfp_command_t parse_command(const char * line_buffer, int isHandsFree){
627     int offset = isHandsFree ? 0 : 2;
628 
629     if (strncmp(line_buffer+offset, HFP_LIST_CURRENT_CALLS, strlen(HFP_LIST_CURRENT_CALLS)) == 0){
630         return HFP_CMD_LIST_CURRENT_CALLS;
631     }
632 
633     if (strncmp(line_buffer+offset, HFP_SUBSCRIBER_NUMBER_INFORMATION, strlen(HFP_SUBSCRIBER_NUMBER_INFORMATION)) == 0){
634         return HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION;
635     }
636 
637     if (strncmp(line_buffer+offset, HFP_PHONE_NUMBER_FOR_VOICE_TAG, strlen(HFP_PHONE_NUMBER_FOR_VOICE_TAG)) == 0){
638         if (isHandsFree) return HFP_CMD_AG_SENT_PHONE_NUMBER;
639         return HFP_CMD_HF_REQUEST_PHONE_NUMBER;
640     }
641 
642     if (strncmp(line_buffer+offset, HFP_TRANSMIT_DTMF_CODES, strlen(HFP_TRANSMIT_DTMF_CODES)) == 0){
643         return HFP_CMD_TRANSMIT_DTMF_CODES;
644     }
645 
646     if (strncmp(line_buffer+offset, HFP_SET_MICROPHONE_GAIN, strlen(HFP_SET_MICROPHONE_GAIN)) == 0){
647         return HFP_CMD_SET_MICROPHONE_GAIN;
648     }
649 
650     if (strncmp(line_buffer+offset, HFP_SET_SPEAKER_GAIN, strlen(HFP_SET_SPEAKER_GAIN)) == 0){
651         return HFP_CMD_SET_SPEAKER_GAIN;
652     }
653 
654     if (strncmp(line_buffer+offset, HFP_ACTIVATE_VOICE_RECOGNITION, strlen(HFP_ACTIVATE_VOICE_RECOGNITION)) == 0){
655         if (isHandsFree) return HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
656         return HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION;
657     }
658 
659     if (strncmp(line_buffer+offset, HFP_TURN_OFF_EC_AND_NR, strlen(HFP_TURN_OFF_EC_AND_NR)) == 0){
660         return HFP_CMD_TURN_OFF_EC_AND_NR;
661     }
662 
663     if (strncmp(line_buffer, HFP_CALL_ANSWERED, strlen(HFP_CALL_ANSWERED)) == 0){
664         return HFP_CMD_CALL_ANSWERED;
665     }
666 
667     if (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0){
668         return HFP_CMD_CALL_PHONE_NUMBER;
669     }
670 
671     if (strncmp(line_buffer+offset, HFP_REDIAL_LAST_NUMBER, strlen(HFP_REDIAL_LAST_NUMBER)) == 0){
672         return HFP_CMD_REDIAL_LAST_NUMBER;
673     }
674 
675     if (strncmp(line_buffer+offset, HFP_CHANGE_IN_BAND_RING_TONE_SETTING, strlen(HFP_CHANGE_IN_BAND_RING_TONE_SETTING)) == 0){
676         return HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING;
677     }
678 
679     if (strncmp(line_buffer+offset, HFP_HANG_UP_CALL, strlen(HFP_HANG_UP_CALL)) == 0){
680         return HFP_CMD_HANG_UP_CALL;
681     }
682 
683     if (strncmp(line_buffer+offset, HFP_ERROR, strlen(HFP_ERROR)) == 0){
684         return HFP_CMD_ERROR;
685     }
686 
687     if (strncmp(line_buffer+offset, HFP_RING, strlen(HFP_RING)) == 0){
688         return HFP_CMD_RING;
689     }
690 
691     if (isHandsFree && strncmp(line_buffer+offset, HFP_OK, strlen(HFP_OK)) == 0){
692         return HFP_CMD_OK;
693     }
694 
695     if (strncmp(line_buffer+offset, HFP_SUPPORTED_FEATURES, strlen(HFP_SUPPORTED_FEATURES)) == 0){
696         return HFP_CMD_SUPPORTED_FEATURES;
697     }
698 
699     if (strncmp(line_buffer+offset, HFP_TRANSFER_HF_INDICATOR_STATUS, strlen(HFP_TRANSFER_HF_INDICATOR_STATUS)) == 0){
700         return HFP_CMD_HF_INDICATOR_STATUS;
701     }
702 
703     if (strncmp(line_buffer+offset, HFP_RESPONSE_AND_HOLD, strlen(HFP_RESPONSE_AND_HOLD)) == 0){
704         if (strncmp(line_buffer+strlen(HFP_RESPONSE_AND_HOLD)+offset, "?", 1) == 0){
705             return HFP_CMD_RESPONSE_AND_HOLD_QUERY;
706         }
707         if (strncmp(line_buffer+strlen(HFP_RESPONSE_AND_HOLD)+offset, "=", 1) == 0){
708             return HFP_CMD_RESPONSE_AND_HOLD_COMMAND;
709         }
710         return HFP_CMD_RESPONSE_AND_HOLD_STATUS;
711     }
712 
713     if (strncmp(line_buffer+offset, HFP_INDICATOR, strlen(HFP_INDICATOR)) == 0){
714         if (strncmp(line_buffer+strlen(HFP_INDICATOR)+offset, "?", 1) == 0){
715             return HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
716         }
717 
718         if (strncmp(line_buffer+strlen(HFP_INDICATOR)+offset, "=?", 2) == 0){
719             return HFP_CMD_RETRIEVE_AG_INDICATORS;
720         }
721     }
722 
723     if (strncmp(line_buffer+offset, HFP_AVAILABLE_CODECS, strlen(HFP_AVAILABLE_CODECS)) == 0){
724         return HFP_CMD_AVAILABLE_CODECS;
725     }
726 
727     if (strncmp(line_buffer+offset, HFP_ENABLE_STATUS_UPDATE_FOR_AG_INDICATORS, strlen(HFP_ENABLE_STATUS_UPDATE_FOR_AG_INDICATORS)) == 0){
728         return HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE;
729     }
730 
731     if (strncmp(line_buffer+offset, HFP_ENABLE_CLIP, strlen(HFP_ENABLE_CLIP)) == 0){
732         if (isHandsFree) return HFP_CMD_AG_SENT_CLIP_INFORMATION;
733         return HFP_CMD_ENABLE_CLIP;
734     }
735 
736     if (strncmp(line_buffer+offset, HFP_ENABLE_CALL_WAITING_NOTIFICATION, strlen(HFP_ENABLE_CALL_WAITING_NOTIFICATION)) == 0){
737         if (isHandsFree) return HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE;
738         return HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION;
739     }
740 
741     if (strncmp(line_buffer+offset, HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES, strlen(HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES)) == 0){
742 
743         if (isHandsFree) return HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES;
744 
745         if (strncmp(line_buffer+strlen(HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES)+offset, "=?", 2) == 0){
746             return HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES;
747         }
748         if (strncmp(line_buffer+strlen(HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES)+offset, "=", 1) == 0){
749             return HFP_CMD_CALL_HOLD;
750         }
751 
752         return HFP_CMD_UNKNOWN;
753     }
754 
755     if (strncmp(line_buffer+offset, HFP_GENERIC_STATUS_INDICATOR, strlen(HFP_GENERIC_STATUS_INDICATOR)) == 0){
756         if (isHandsFree) {
757             return HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS;
758         }
759         if (strncmp(line_buffer+strlen(HFP_GENERIC_STATUS_INDICATOR)+offset, "=?", 2) == 0){
760             return HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS;
761         }
762         if (strncmp(line_buffer+strlen(HFP_GENERIC_STATUS_INDICATOR)+offset, "=", 1) == 0){
763             return HFP_CMD_LIST_GENERIC_STATUS_INDICATORS;
764         }
765         return HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE;
766     }
767 
768     if (strncmp(line_buffer+offset, HFP_UPDATE_ENABLE_STATUS_FOR_INDIVIDUAL_AG_INDICATORS, strlen(HFP_UPDATE_ENABLE_STATUS_FOR_INDIVIDUAL_AG_INDICATORS)) == 0){
769         return HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE;
770     }
771 
772 
773     if (strncmp(line_buffer+offset, HFP_QUERY_OPERATOR_SELECTION, strlen(HFP_QUERY_OPERATOR_SELECTION)) == 0){
774         if (strncmp(line_buffer+strlen(HFP_QUERY_OPERATOR_SELECTION)+offset, "=", 1) == 0){
775             return HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT;
776         }
777         return HFP_CMD_QUERY_OPERATOR_SELECTION_NAME;
778     }
779 
780     if (strncmp(line_buffer+offset, HFP_TRANSFER_AG_INDICATOR_STATUS, strlen(HFP_TRANSFER_AG_INDICATOR_STATUS)) == 0){
781         return HFP_CMD_TRANSFER_AG_INDICATOR_STATUS;
782     }
783 
784     if (isHandsFree && strncmp(line_buffer+offset, HFP_EXTENDED_AUDIO_GATEWAY_ERROR, strlen(HFP_EXTENDED_AUDIO_GATEWAY_ERROR)) == 0){
785         return HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR;
786     }
787 
788     if (!isHandsFree && strncmp(line_buffer+offset, HFP_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR, strlen(HFP_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR)) == 0){
789         return HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR;
790     }
791 
792     if (strncmp(line_buffer+offset, HFP_TRIGGER_CODEC_CONNECTION_SETUP, strlen(HFP_TRIGGER_CODEC_CONNECTION_SETUP)) == 0){
793         return HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP;
794     }
795 
796     if (strncmp(line_buffer+offset, HFP_CONFIRM_COMMON_CODEC, strlen(HFP_CONFIRM_COMMON_CODEC)) == 0){
797         if (isHandsFree){
798             return HFP_CMD_AG_SUGGESTED_CODEC;
799         } else {
800             return HFP_CMD_HF_CONFIRMED_CODEC;
801         }
802     }
803 
804     if (strncmp(line_buffer+offset, "AT+", 3) == 0){
805         log_info("process unknown HF command %s \n", line_buffer);
806         return HFP_CMD_UNKNOWN;
807     }
808 
809     if (strncmp(line_buffer+offset, "+", 1) == 0){
810         log_info(" process unknown AG command %s \n", line_buffer);
811         return HFP_CMD_UNKNOWN;
812     }
813 
814     if (strncmp(line_buffer+offset, "NOP", 3) == 0){
815         return HFP_CMD_NONE;
816     }
817 
818     return HFP_CMD_NONE;
819 }
820 
821 static void hfp_parser_store_byte(hfp_connection_t * hfp_connection, uint8_t byte){
822     // printf("hfp_parser_store_byte %c at pos %u\n", (char) byte, context->line_size);
823     // TODO: add limit
824     hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
825     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
826 }
827 static int hfp_parser_is_buffer_empty(hfp_connection_t * hfp_connection){
828     return hfp_connection->line_size == 0;
829 }
830 
831 static int hfp_parser_is_end_of_line(uint8_t byte){
832     return byte == '\n' || byte == '\r';
833 }
834 
835 static int hfp_parser_is_end_of_header(uint8_t byte){
836     return hfp_parser_is_end_of_line(byte) || byte == ':' || byte == '?';
837 }
838 
839 static int hfp_parser_found_separator(hfp_connection_t * hfp_connection, uint8_t byte){
840     if (hfp_connection->keep_byte == 1) return 1;
841 
842     int found_separator =   byte == ',' || byte == '\n'|| byte == '\r'||
843                             byte == ')' || byte == '(' || byte == ':' ||
844                             byte == '-' || byte == '"' ||  byte == '?'|| byte == '=';
845     return found_separator;
846 }
847 
848 static void hfp_parser_next_state(hfp_connection_t * hfp_connection, uint8_t byte){
849     hfp_connection->line_size = 0;
850     if (hfp_parser_is_end_of_line(byte)){
851         hfp_connection->parser_item_index = 0;
852         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
853         return;
854     }
855     switch (hfp_connection->parser_state){
856         case HFP_PARSER_CMD_HEADER:
857             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
858             if (hfp_connection->keep_byte == 1){
859                 hfp_parser_store_byte(hfp_connection, byte);
860                 hfp_connection->keep_byte = 0;
861             }
862             break;
863         case HFP_PARSER_CMD_SEQUENCE:
864             switch (hfp_connection->command){
865                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
866                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
867                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
868                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
869                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
870                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
871                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
872                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
873                 case HFP_CMD_HF_INDICATOR_STATUS:
874                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
875                     break;
876                 default:
877                     break;
878             }
879             break;
880         case HFP_PARSER_SECOND_ITEM:
881             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
882             break;
883         case HFP_PARSER_THIRD_ITEM:
884             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){
885                 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
886                 break;
887             }
888             hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
889             break;
890     }
891 }
892 
893 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
894     // handle ATD<dial_string>;
895     if (strncmp((const char*)hfp_connection->line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0){
896         // check for end-of-line or ';'
897         if (byte == ';' || hfp_parser_is_end_of_line(byte)){
898             hfp_connection->line_buffer[hfp_connection->line_size] = 0;
899             hfp_connection->line_size = 0;
900             hfp_connection->command = HFP_CMD_CALL_PHONE_NUMBER;
901         } else {
902             hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
903         }
904         return;
905     }
906 
907     // TODO: handle space inside word
908     if (byte == ' ' && hfp_connection->parser_state > HFP_PARSER_CMD_HEADER) return;
909 
910     if (byte == ',' && hfp_connection->command == HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE){
911         if (hfp_connection->line_size == 0){
912             hfp_connection->line_buffer[0] = 0;
913             hfp_connection->ignore_value = 1;
914             parse_sequence(hfp_connection);
915             return;
916         }
917     }
918 
919     if (!hfp_parser_found_separator(hfp_connection, byte)){
920         hfp_parser_store_byte(hfp_connection, byte);
921         return;
922     }
923 
924     if (hfp_parser_is_end_of_line(byte)) {
925         if (hfp_parser_is_buffer_empty(hfp_connection)){
926             hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
927         }
928     }
929     if (hfp_parser_is_buffer_empty(hfp_connection)) return;
930 
931     switch (hfp_connection->parser_state){
932         case HFP_PARSER_CMD_HEADER: // header
933             if (byte == '='){
934                 hfp_connection->keep_byte = 1;
935                 hfp_parser_store_byte(hfp_connection, byte);
936                 return;
937             }
938 
939             if (byte == '?'){
940                 hfp_connection->keep_byte = 0;
941                 hfp_parser_store_byte(hfp_connection, byte);
942                 return;
943             }
944 
945             if (byte == ','){
946                 hfp_connection->resolve_byte = 1;
947             }
948 
949             // printf(" parse header 2 %s, keep separator $ %d\n", hfp_connection->line_buffer, hfp_connection->keep_byte);
950             if (hfp_parser_is_end_of_header(byte) || hfp_connection->keep_byte == 1){
951                 // printf(" parse header 3 %s, keep separator $ %d\n", hfp_connection->line_buffer, hfp_connection->keep_byte);
952                 char * line_buffer = (char *)hfp_connection->line_buffer;
953                 hfp_connection->command = parse_command(line_buffer, isHandsFree);
954 
955                 /* resolve command name according to hfp_connection */
956                 if (hfp_connection->command == HFP_CMD_UNKNOWN){
957                     switch(hfp_connection->state){
958                         case HFP_W4_LIST_GENERIC_STATUS_INDICATORS:
959                             hfp_connection->command = HFP_CMD_LIST_GENERIC_STATUS_INDICATORS;
960                             break;
961                         case HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS:
962                             hfp_connection->command = HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS;
963                             break;
964                         case HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS:
965                             hfp_connection->command = HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE;
966                             break;
967                         case HFP_W4_RETRIEVE_INDICATORS_STATUS:
968                             hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
969                             break;
970                         case HFP_W4_RETRIEVE_INDICATORS:
971                             hfp_connection->send_ag_indicators_segment = 0;
972                             hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS;
973                             break;
974                         default:
975                             break;
976                     }
977                 }
978             }
979             break;
980 
981         case HFP_PARSER_CMD_SEQUENCE:
982             parse_sequence(hfp_connection);
983             break;
984         case HFP_PARSER_SECOND_ITEM:
985             switch (hfp_connection->command){
986                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
987                     log_info("format %s, ", hfp_connection->line_buffer);
988                     hfp_connection->network_operator.format =  atoi((char *)&hfp_connection->line_buffer[0]);
989                     break;
990                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
991                     log_info("format %s \n", hfp_connection->line_buffer);
992                     hfp_connection->network_operator.format =  atoi((char *)&hfp_connection->line_buffer[0]);
993                     break;
994                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
995                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
996                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
997                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)atoi((char*)hfp_connection->line_buffer);
998                     break;
999                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1000                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)atoi((char*)hfp_connection->line_buffer);
1001                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1002                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1003                     break;
1004                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1005                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = atoi((char *)hfp_connection->line_buffer);
1006                     log_info("%s, ", hfp_connection->line_buffer);
1007                     break;
1008                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1009                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1010                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1011                     hfp_connection->bnip_type = (uint8_t)atoi((char*)hfp_connection->line_buffer);
1012                     break;
1013                 default:
1014                     break;
1015             }
1016             break;
1017 
1018         case HFP_PARSER_THIRD_ITEM:
1019              switch (hfp_connection->command){
1020                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1021                     strcpy(hfp_connection->network_operator.name, (char *)hfp_connection->line_buffer);
1022                     log_info("name %s\n", hfp_connection->line_buffer);
1023                     break;
1024                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1025                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = atoi((char *)hfp_connection->line_buffer);
1026                     hfp_connection->parser_item_index++;
1027                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1028                     log_info("%s)\n", hfp_connection->line_buffer);
1029                     break;
1030                 default:
1031                     break;
1032             }
1033             break;
1034     }
1035     hfp_parser_next_state(hfp_connection, byte);
1036 
1037     if (hfp_connection->resolve_byte && hfp_connection->command == HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE){
1038         hfp_connection->resolve_byte = 0;
1039         hfp_connection->ignore_value = 1;
1040         parse_sequence(hfp_connection);
1041         hfp_connection->line_buffer[0] = 0;
1042         hfp_connection->line_size = 0;
1043     }
1044 }
1045 
1046 static void parse_sequence(hfp_connection_t * hfp_connection){
1047     int value;
1048     switch (hfp_connection->command){
1049         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1050             value = atoi((char *)&hfp_connection->line_buffer[0]);
1051             int i;
1052             switch (hfp_connection->parser_item_index){
1053                 case 0:
1054                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1055                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1056                             hfp_connection->parser_indicator_index = i;
1057                             break;
1058                         }
1059                     }
1060                     break;
1061                 case 1:
1062                     if (hfp_connection->parser_indicator_index <0) break;
1063                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1064                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1065                      hfp_connection->parser_item_index, value);
1066                     break;
1067                 default:
1068                     break;
1069             }
1070             hfp_connection->parser_item_index++;
1071             break;
1072 
1073         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1074             switch(hfp_connection->parser_item_index){
1075                 case 0:
1076                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1077                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1078                     break;
1079                 case 1:
1080                     value = atoi((char *)&hfp_connection->line_buffer[0]);
1081                     hfp_connection->bnip_type = value;
1082                     break;
1083                 default:
1084                     break;
1085             }
1086             hfp_connection->parser_item_index++;
1087             break;
1088         case HFP_CMD_LIST_CURRENT_CALLS:
1089             switch(hfp_connection->parser_item_index){
1090                 case 0:
1091                     value = atoi((char *)&hfp_connection->line_buffer[0]);
1092                     hfp_connection->clcc_idx = value;
1093                     break;
1094                 case 1:
1095                     value = atoi((char *)&hfp_connection->line_buffer[0]);
1096                     hfp_connection->clcc_dir = value;
1097                     break;
1098                 case 2:
1099                     value = atoi((char *)&hfp_connection->line_buffer[0]);
1100                     hfp_connection->clcc_status = value;
1101                     break;
1102                 case 3:
1103                     value = atoi((char *)&hfp_connection->line_buffer[0]);
1104                     hfp_connection->clcc_mpty = value;
1105                     break;
1106                 case 4:
1107                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1108                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1109                     break;
1110                 case 5:
1111                     value = atoi((char *)&hfp_connection->line_buffer[0]);
1112                     hfp_connection->bnip_type = value;
1113                     break;
1114                 default:
1115                     break;
1116             }
1117             hfp_connection->parser_item_index++;
1118             break;
1119         case HFP_CMD_SET_MICROPHONE_GAIN:
1120             value = atoi((char *)&hfp_connection->line_buffer[0]);
1121             hfp_connection->microphone_gain = value;
1122             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1123             break;
1124         case HFP_CMD_SET_SPEAKER_GAIN:
1125             value = atoi((char *)&hfp_connection->line_buffer[0]);
1126             hfp_connection->speaker_gain = value;
1127             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1128             break;
1129         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1130             value = atoi((char *)&hfp_connection->line_buffer[0]);
1131             hfp_connection->ag_activate_voice_recognition = value;
1132             log_info("hfp parse HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION %d\n", value);
1133             break;
1134         case HFP_CMD_TURN_OFF_EC_AND_NR:
1135             value = atoi((char *)&hfp_connection->line_buffer[0]);
1136             hfp_connection->ag_echo_and_noise_reduction = value;
1137             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1138             break;
1139         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1140             value = atoi((char *)&hfp_connection->line_buffer[0]);
1141             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1142             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1143             break;
1144         case HFP_CMD_HF_CONFIRMED_CODEC:
1145             hfp_connection->codec_confirmed = atoi((char*)hfp_connection->line_buffer);
1146             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1147             break;
1148         case HFP_CMD_AG_SUGGESTED_CODEC:
1149             hfp_connection->suggested_codec = atoi((char*)hfp_connection->line_buffer);
1150             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1151             break;
1152         case HFP_CMD_SUPPORTED_FEATURES:
1153             hfp_connection->remote_supported_features = atoi((char*)hfp_connection->line_buffer);
1154             log_info("Parsed supported feature %d\n", hfp_connection->remote_supported_features);
1155             break;
1156         case HFP_CMD_AVAILABLE_CODECS:
1157             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1158             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint16_t)atoi((char*)hfp_connection->line_buffer);
1159             hfp_connection->parser_item_index++;
1160             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1161             break;
1162         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1163             strcpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name,  (char *)hfp_connection->line_buffer);
1164             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1165             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1166             break;
1167         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1168             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1169             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = atoi((char *) hfp_connection->line_buffer);
1170             hfp_connection->parser_item_index++;
1171             break;
1172         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1173             hfp_connection->parser_item_index++;
1174             if (hfp_connection->parser_item_index != 4) break;
1175             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1176             value = atoi((char *)&hfp_connection->line_buffer[0]);
1177             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1178             break;
1179         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1180             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1181             if (hfp_connection->line_size > 2 ) break;
1182             strcpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_nr].name,  (char *)hfp_connection->line_buffer);
1183             hfp_connection->remote_call_services_nr++;
1184             break;
1185         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1186         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1187             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1188             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)atoi((char*)hfp_connection->line_buffer);
1189             hfp_connection->parser_item_index++;
1190             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1191             break;
1192         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1193             // HF parses inital AG gen. ind. state
1194             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1195             hfp_connection->parser_item_index = (uint8_t)atoi((char*)hfp_connection->line_buffer);
1196             break;
1197         case HFP_CMD_HF_INDICATOR_STATUS:
1198             hfp_connection->parser_indicator_index = (uint8_t)atoi((char*)hfp_connection->line_buffer);
1199             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1200             break;
1201         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1202             // AG parses new gen. ind. state
1203             if (hfp_connection->ignore_value){
1204                 hfp_connection->ignore_value = 0;
1205                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1206                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1207             }
1208             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1209                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1210                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1211             } else {
1212                 value = atoi((char *)&hfp_connection->line_buffer[0]);
1213                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1214                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1215                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1216             }
1217             hfp_connection->parser_item_index++;
1218             break;
1219         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1220             // indicators are indexed starting with 1
1221             hfp_connection->parser_item_index = atoi((char *)&hfp_connection->line_buffer[0]) - 1;
1222             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1223             break;
1224         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1225             hfp_connection->network_operator.mode = atoi((char *)&hfp_connection->line_buffer[0]);
1226             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1227             break;
1228         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1229             if (hfp_connection->line_buffer[0] == '3'){
1230                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1231                 break;
1232             }
1233             // TODO emit ERROR, wrong format
1234             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1235             break;
1236         case HFP_CMD_ERROR:
1237             break;
1238         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1239             hfp_connection->extended_audio_gateway_error = 1;
1240             hfp_connection->extended_audio_gateway_error_value = (uint8_t)atoi((char*)hfp_connection->line_buffer);
1241             break;
1242         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1243             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)atoi((char*)hfp_connection->line_buffer);
1244             hfp_connection->ok_pending = 1;
1245             hfp_connection->extended_audio_gateway_error = 0;
1246             break;
1247         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1248         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1249         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1250             strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1251             hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1252             break;
1253         default:
1254             break;
1255     }
1256 }
1257 
1258 void hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid){
1259     hfp_connection_t * hfp_connection = provide_hfp_connection_context_for_bd_addr(bd_addr);
1260     log_info("hfp_connect %s, hfp_connection %p", bd_addr_to_str(bd_addr), hfp_connection);
1261 
1262     if (!hfp_connection) {
1263         log_error("hfp_establish_service_level_connection for addr %s failed", bd_addr_to_str(bd_addr));
1264         return;
1265     }
1266 
1267     switch (hfp_connection->state){
1268         case HFP_W2_DISCONNECT_RFCOMM:
1269             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1270             return;
1271         case HFP_W4_RFCOMM_DISCONNECTED:
1272             hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART;
1273             return;
1274         case HFP_IDLE:
1275             memcpy(hfp_connection->remote_addr, bd_addr, 6);
1276             hfp_connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1277             connection_doing_sdp_query = hfp_connection;
1278             hfp_connection->service_uuid = service_uuid;
1279             sdp_client_query_rfcomm_channel_and_name_for_uuid(&handle_query_rfcomm_event, hfp_connection->remote_addr, service_uuid);
1280             break;
1281         default:
1282             break;
1283     }
1284 }
1285 
1286 void hfp_release_service_level_connection(hfp_connection_t * hfp_connection){
1287     if (!hfp_connection) return;
1288     hfp_release_audio_connection(hfp_connection);
1289 
1290     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1291         hfp_connection->state = HFP_IDLE;
1292         return;
1293     }
1294 
1295     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1296         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1297         return;
1298     }
1299 
1300     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1301         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1302         return;
1303     }
1304 
1305     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1306         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1307         return;
1308     }
1309 
1310     return;
1311 }
1312 
1313 void hfp_release_audio_connection(hfp_connection_t * hfp_connection){
1314     if (!hfp_connection) return;
1315     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
1316     hfp_connection->release_audio_connection = 1;
1317 }
1318 
1319 static const struct link_settings {
1320     const uint16_t max_latency;
1321     const uint8_t  retransmission_effort;
1322     const uint16_t packet_types;
1323 } hfp_link_settings [] = {
1324     { 0xffff, 0xff, 0x03c1 }, // HFP_LINK_SETTINGS_D0,   HV1
1325     { 0xffff, 0xff, 0x03c4 }, // HFP_LINK_SETTINGS_D1,   HV3
1326     { 0x0007, 0x01, 0x03c8 }, // HFP_LINK_SETTINGS_S1,   EV3
1327     { 0x0007, 0x01, 0x0380 }, // HFP_LINK_SETTINGS_S2, 2-EV3
1328     { 0x000a, 0x01, 0x0380 }, // HFP_LINK_SETTINGS_S3, 2-EV3
1329     { 0x000c, 0x02, 0x0380 }, // HFP_LINK_SETTINGS_S4, 2-EV3
1330     { 0x0008, 0x02, 0x03c8 }, // HFP_LINK_SETTINGS_T1,   EV3
1331     { 0x000d, 0x02, 0x0380 }  // HFP_LINK_SETTINGS_T2, 2-EV3
1332 };
1333 
1334 void hfp_setup_synchronous_connection(hci_con_handle_t handle, hfp_link_setttings_t setting){
1335     // all packet types, fixed bandwidth
1336     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1337     hci_send_cmd(&hci_setup_synchronous_connection, handle, 8000, 8000, hfp_link_settings[setting].max_latency,
1338         hci_get_sco_voice_setting(), hfp_link_settings[setting].retransmission_effort, hfp_link_settings[setting].packet_types); // all types 0x003f, only 2-ev3 0x380
1339 }
1340 
1341 void hfp_set_packet_handler_for_rfcomm_connections(btstack_packet_handler_t handler){
1342     rfcomm_packet_handler = handler;
1343 }
1344 
1345