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