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