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