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