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