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