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