xref: /btstack/src/classic/hfp_hf.c (revision af7c3ae6cd1e2bcfd24e6d0654508ecf775c9e5d)
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 BLUEKITCHEN
24  * GMBH 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_hf.c"
39 
40 // *****************************************************************************
41 //
42 // HFP Hands-Free (HF) unit
43 //
44 // *****************************************************************************
45 
46 #include "btstack_config.h"
47 
48 #include <stdint.h>
49 #include <stdio.h>
50 #include <string.h>
51 
52 #include "bluetooth_sdp.h"
53 #include "btstack_debug.h"
54 #include "btstack_event.h"
55 #include "btstack_memory.h"
56 #include "btstack_run_loop.h"
57 #include "classic/core.h"
58 #include "classic/hfp.h"
59 #include "classic/hfp_hf.h"
60 #include "classic/sdp_client_rfcomm.h"
61 #include "classic/sdp_server.h"
62 #include "classic/sdp_util.h"
63 #include "hci.h"
64 #include "hci_cmd.h"
65 #include "hci_dump.h"
66 #include "l2cap.h"
67 
68 // const
69 static const char hfp_hf_default_service_name[] = "Hands-Free unit";
70 
71 // globals
72 
73 // higher layer callbacks
74 static btstack_packet_handler_t hfp_hf_callback;
75 
76 static btstack_packet_callback_registration_t hfp_hf_hci_event_callback_registration;
77 
78 static uint16_t hfp_hf_supported_features;
79 static uint8_t  hfp_hf_codecs_nr;
80 static uint8_t  hfp_hf_codecs[HFP_MAX_NUM_CODECS];
81 
82 static uint8_t  hfp_hf_indicators_nr;
83 static uint8_t  hfp_hf_indicators[HFP_MAX_NUM_INDICATORS];
84 static uint32_t hfp_hf_indicators_value[HFP_MAX_NUM_INDICATORS];
85 
86 static uint8_t  hfp_hf_speaker_gain;
87 static uint8_t  hfp_hf_microphone_gain;
88 
89 static hfp_call_status_t      hfp_hf_call_status;
90 static hfp_callsetup_status_t hfp_hf_callsetup_status;
91 static hfp_callheld_status_t  hfp_hf_callheld_status;
92 
93 static char hfp_hf_phone_number[25];
94 
95 
96 static int has_codec_negotiation_feature(hfp_connection_t * hfp_connection){
97 	int hf = get_bit(hfp_hf_supported_features, HFP_HFSF_CODEC_NEGOTIATION);
98 	int ag = get_bit(hfp_connection->remote_supported_features, HFP_AGSF_CODEC_NEGOTIATION);
99 	return hf && ag;
100 }
101 
102 static int has_call_waiting_and_3way_calling_feature(hfp_connection_t * hfp_connection){
103 	int hf = get_bit(hfp_hf_supported_features, HFP_HFSF_THREE_WAY_CALLING);
104 	int ag = get_bit(hfp_connection->remote_supported_features, HFP_AGSF_THREE_WAY_CALLING);
105 	return hf && ag;
106 }
107 
108 
109 static int has_hf_indicators_feature(hfp_connection_t * hfp_connection){
110 	int hf = get_bit(hfp_hf_supported_features, HFP_HFSF_HF_INDICATORS);
111 	int ag = get_bit(hfp_connection->remote_supported_features, HFP_AGSF_HF_INDICATORS);
112 	return hf && ag;
113 }
114 
115 static bool hfp_hf_vra_flag_supported(hfp_connection_t * hfp_connection){
116     int hf = get_bit(hfp_hf_supported_features, HFP_HFSF_VOICE_RECOGNITION_FUNCTION);
117     int ag = get_bit(hfp_connection->remote_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION);
118     return hf && ag;
119 }
120 
121 static bool hfp_hf_enhanced_vra_flag_supported(hfp_connection_t * hfp_connection){
122     int hf = get_bit(hfp_hf_supported_features, HFP_HFSF_ENHANCED_VOICE_RECOGNITION_STATUS);
123     int ag = get_bit(hfp_connection->remote_supported_features, HFP_AGSF_ENHANCED_VOICE_RECOGNITION_STATUS);
124     return hf && ag;
125 }
126 
127 static hfp_connection_t * get_hfp_hf_connection_context_for_acl_handle(uint16_t handle){
128     btstack_linked_list_iterator_t it;
129     btstack_linked_list_iterator_init(&it, hfp_get_connections());
130     while (btstack_linked_list_iterator_has_next(&it)){
131         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
132         if (hfp_connection->acl_handle != handle)      continue;
133         if (hfp_connection->local_role != HFP_ROLE_HF) continue;
134         return hfp_connection;
135     }
136     return NULL;
137 }
138 
139 /* emit functinos */
140 
141 static void hfp_hf_emit_subscriber_information(const hfp_connection_t * hfp_connection, uint8_t status){
142     if (hfp_hf_callback == NULL) return;
143     uint8_t event[33];
144     event[0] = HCI_EVENT_HFP_META;
145     event[1] = sizeof(event) - 2;
146     event[2] = HFP_SUBEVENT_SUBSCRIBER_NUMBER_INFORMATION;
147     little_endian_store_16(event, 3, hfp_connection->acl_handle);
148     event[5] = status;
149     event[6] = hfp_connection->bnip_type;
150     uint16_t size = btstack_min(strlen(hfp_connection->bnip_number), sizeof(event) - 8);
151     strncpy((char*)&event[7], hfp_connection->bnip_number, size);
152     event[7 + size] = 0;
153     (*hfp_hf_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
154 }
155 
156 static void hfp_hf_emit_type_and_number(const hfp_connection_t * hfp_connection, uint8_t event_subtype){
157     if (hfp_hf_callback == NULL) return;
158     uint8_t event[32];
159     event[0] = HCI_EVENT_HFP_META;
160     event[1] = sizeof(event) - 2;
161     event[2] = event_subtype;
162     little_endian_store_16(event, 3, hfp_connection->acl_handle);
163     event[5] = hfp_connection->bnip_type;
164     uint16_t size = btstack_min(strlen(hfp_connection->bnip_number), sizeof(event) - 7);
165     strncpy((char*)&event[6], hfp_connection->bnip_number, size);
166     event[6 + size] = 0;
167     (*hfp_hf_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
168 }
169 
170 static void hfp_hf_emit_enhanced_call_status(const hfp_connection_t * hfp_connection){
171     if (hfp_hf_callback == NULL) return;
172     uint8_t event[38];
173     int pos = 0;
174     event[pos++] = HCI_EVENT_HFP_META;
175     event[pos++] = sizeof(event) - 2;
176     event[pos++] = HFP_SUBEVENT_ENHANCED_CALL_STATUS;
177     little_endian_store_16(event, pos, hfp_connection->acl_handle);
178     pos += 2;
179     event[pos++] = hfp_connection->clcc_idx;
180     event[pos++] = hfp_connection->clcc_dir;
181     event[pos++] = hfp_connection->clcc_status;
182     event[pos++] = hfp_connection->clcc_mode;
183     event[pos++] = hfp_connection->clcc_mpty;
184     event[pos++] = hfp_connection->bnip_type;
185     uint16_t size = btstack_min(strlen(hfp_connection->bnip_number), sizeof(event) - pos - 1);
186     strncpy((char*)&event[pos], hfp_connection->bnip_number, size);
187     pos += size;
188     event[pos++] = 0;
189     (*hfp_hf_callback)(HCI_EVENT_PACKET, 0, event, pos);
190 }
191 
192 static void hfp_emit_ag_indicator_mapping_event(const hfp_connection_t * hfp_connection, const hfp_ag_indicator_t * indicator){
193     if (hfp_hf_callback == NULL) return;
194     uint8_t event[8+HFP_MAX_INDICATOR_DESC_SIZE+1];
195     int pos = 0;
196     event[pos++] = HCI_EVENT_HFP_META;
197     event[pos++] = sizeof(event) - 2;
198     event[pos++] = HFP_SUBEVENT_AG_INDICATOR_MAPPING;
199     little_endian_store_16(event, pos, hfp_connection->acl_handle);
200     pos += 2;
201     event[pos++] = indicator->index;
202     event[pos++] = indicator->min_range;
203     event[pos++] = indicator->max_range;
204     strncpy((char*)&event[pos], indicator->name, HFP_MAX_INDICATOR_DESC_SIZE);
205     pos += HFP_MAX_INDICATOR_DESC_SIZE;
206     event[pos] = 0;
207     (*hfp_hf_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
208 }
209 
210 static void hfp_emit_ag_indicator_status_event(const hfp_connection_t * hfp_connection, const hfp_ag_indicator_t * indicator){
211 	if (hfp_hf_callback == NULL) return;
212 	uint8_t event[12+HFP_MAX_INDICATOR_DESC_SIZE+1];
213 	int pos = 0;
214 	event[pos++] = HCI_EVENT_HFP_META;
215 	event[pos++] = sizeof(event) - 2;
216 	event[pos++] = HFP_SUBEVENT_AG_INDICATOR_STATUS_CHANGED;
217     little_endian_store_16(event, pos, hfp_connection->acl_handle);
218     pos += 2;
219 	event[pos++] = indicator->index;
220 	event[pos++] = indicator->status;
221 	event[pos++] = indicator->min_range;
222 	event[pos++] = indicator->max_range;
223 	event[pos++] = indicator->mandatory;
224 	event[pos++] = indicator->enabled;
225 	event[pos++] = indicator->status_changed;
226 	strncpy((char*)&event[pos], indicator->name, HFP_MAX_INDICATOR_DESC_SIZE);
227 	pos += HFP_MAX_INDICATOR_DESC_SIZE;
228 	event[pos] = 0;
229 	(*hfp_hf_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
230 }
231 
232 static void hfp_emit_network_operator_event(const hfp_connection_t * hfp_connection){
233     if (hfp_hf_callback == NULL) return;
234 	uint8_t event[7+HFP_MAX_NETWORK_OPERATOR_NAME_SIZE+1];
235 	event[0] = HCI_EVENT_HFP_META;
236 	event[1] = sizeof(event) - 2;
237 	event[2] = HFP_SUBEVENT_NETWORK_OPERATOR_CHANGED;
238     little_endian_store_16(event, 3, hfp_connection->acl_handle);
239 	event[5] = hfp_connection->network_operator.mode;
240 	event[6] = hfp_connection->network_operator.format;
241 	strncpy((char*)&event[7], hfp_connection->network_operator.name, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE);
242 	event[7+HFP_MAX_NETWORK_OPERATOR_NAME_SIZE] = 0;
243 	(*hfp_hf_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
244 }
245 
246 
247 static void hfp_hf_emit_enhanced_voice_recognition_text(hfp_connection_t * hfp_connection){
248     btstack_assert(hfp_connection != NULL);
249     uint8_t event[HFP_MAX_VR_TEXT_SIZE + 11];
250     int pos = 0;
251     event[pos++] = HCI_EVENT_HFP_META;
252     event[pos++] = sizeof(event) - 2;
253     event[pos++] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_AG_MESSAGE;
254     little_endian_store_16(event, pos, hfp_connection->acl_handle);
255     pos += 2;
256     little_endian_store_16(event, pos, hfp_connection->ag_msg.text_id);
257     pos += 2;
258     event[pos++] = hfp_connection->ag_msg.text_type;
259     event[pos++] = hfp_connection->ag_msg.text_operation;
260 
261     // length, zero ending is already in message
262     uint8_t * value = &hfp_connection->line_buffer[0];
263     uint16_t  value_length = hfp_connection->ag_vra_msg_length;
264 
265     little_endian_store_16(event, pos, value_length);
266     pos += 2;
267     memcpy(&event[pos], value, value_length);
268     pos += value_length;
269 
270     (*hfp_hf_callback)(HCI_EVENT_PACKET, 0, event, pos);
271 }
272 
273 /* send commands */
274 
275 static inline int hfp_hf_send_cmd(uint16_t cid, const char * cmd){
276     char buffer[20];
277     snprintf(buffer, sizeof(buffer), "AT%s\r", cmd);
278     return send_str_over_rfcomm(cid, buffer);
279 }
280 
281 static inline int hfp_hf_send_cmd_with_mark(uint16_t cid, const char * cmd, const char * mark){
282     char buffer[20];
283     snprintf(buffer, sizeof(buffer), "AT%s%s\r", cmd, mark);
284     return send_str_over_rfcomm(cid, buffer);
285 }
286 
287 static inline int hfp_hf_send_cmd_with_int(uint16_t cid, const char * cmd, uint16_t value){
288     char buffer[40];
289     snprintf(buffer, sizeof(buffer), "AT%s=%d\r", cmd, value);
290     return send_str_over_rfcomm(cid, buffer);
291 }
292 
293 static int hfp_hf_cmd_notify_on_codecs(uint16_t cid){
294     char buffer[30];
295     const int size = sizeof(buffer);
296     int offset = snprintf(buffer, size, "AT%s=", HFP_AVAILABLE_CODECS);
297     offset += join(buffer+offset, size-offset, hfp_hf_codecs, hfp_hf_codecs_nr);
298     offset += snprintf(buffer+offset, size-offset, "\r");
299     return send_str_over_rfcomm(cid, buffer);
300 }
301 
302 static int hfp_hf_cmd_activate_status_update_for_ag_indicator(uint16_t cid, uint32_t indicators_status, int indicators_nr){
303     char buffer[50];
304     const int size = sizeof(buffer);
305     int offset = snprintf(buffer, size, "AT%s=", HFP_UPDATE_ENABLE_STATUS_FOR_INDIVIDUAL_AG_INDICATORS);
306     offset += join_bitmap(buffer+offset, size-offset, indicators_status, indicators_nr);
307     offset += snprintf(buffer+offset, size-offset, "\r");
308     return send_str_over_rfcomm(cid, buffer);
309 }
310 
311 static int hfp_hf_cmd_list_supported_generic_status_indicators(uint16_t cid){
312     char buffer[30];
313     const int size = sizeof(buffer);
314     int offset = snprintf(buffer, size, "AT%s=", HFP_GENERIC_STATUS_INDICATOR);
315     offset += join(buffer+offset, size-offset, hfp_hf_indicators, hfp_hf_indicators_nr);
316     offset += snprintf(buffer+offset, size-offset, "\r");
317     return send_str_over_rfcomm(cid, buffer);
318 }
319 
320 static int hfp_hf_cmd_activate_status_update_for_all_ag_indicators(uint16_t cid, uint8_t activate){
321     char buffer[20];
322     snprintf(buffer, sizeof(buffer), "AT%s=3,0,0,%d\r", HFP_ENABLE_STATUS_UPDATE_FOR_AG_INDICATORS, activate);
323     return send_str_over_rfcomm(cid, buffer);
324 }
325 
326 static int hfp_hf_initiate_outgoing_call_cmd(uint16_t cid){
327     char buffer[40];
328     snprintf(buffer, sizeof(buffer), "%s%s;\r", HFP_CALL_PHONE_NUMBER, hfp_hf_phone_number);
329     return send_str_over_rfcomm(cid, buffer);
330 }
331 
332 static int hfp_hf_send_memory_dial_cmd(uint16_t cid, int memory_id){
333     char buffer[40];
334     snprintf(buffer, sizeof(buffer), "%s>%d;\r", HFP_CALL_PHONE_NUMBER, memory_id);
335     return send_str_over_rfcomm(cid, buffer);
336 }
337 
338 static int hfp_hf_send_chld(uint16_t cid, unsigned int number){
339     char buffer[40];
340     snprintf(buffer, sizeof(buffer), "AT%s=%u\r", HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES, number);
341     return send_str_over_rfcomm(cid, buffer);
342 }
343 
344 static int hfp_hf_send_dtmf(uint16_t cid, char code){
345     char buffer[20];
346     snprintf(buffer, sizeof(buffer), "AT%s=%c\r", HFP_TRANSMIT_DTMF_CODES, code);
347     return send_str_over_rfcomm(cid, buffer);
348 }
349 
350 static int hfp_hf_cmd_ata(uint16_t cid){
351     return send_str_over_rfcomm(cid, (char *) "ATA\r");
352 }
353 
354 static int hfp_hf_cmd_exchange_supported_features(uint16_t cid){
355     return hfp_hf_send_cmd_with_int(cid, HFP_SUPPORTED_FEATURES, hfp_hf_supported_features);
356 }
357 
358 static int hfp_hf_cmd_retrieve_indicators(uint16_t cid){
359     return hfp_hf_send_cmd_with_mark(cid, HFP_INDICATOR, "=?");
360 }
361 
362 static int hfp_hf_cmd_retrieve_indicators_status(uint16_t cid){
363     return hfp_hf_send_cmd_with_mark(cid, HFP_INDICATOR, "?");
364 }
365 
366 static int hfp_hf_cmd_retrieve_can_hold_call(uint16_t cid){
367     return hfp_hf_send_cmd_with_mark(cid, HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES, "=?");
368 }
369 
370 static int hfp_hf_cmd_retrieve_supported_generic_status_indicators(uint16_t cid){
371     return hfp_hf_send_cmd_with_mark(cid, HFP_GENERIC_STATUS_INDICATOR, "=?");
372 }
373 
374 static int hfp_hf_cmd_list_initital_supported_generic_status_indicators(uint16_t cid){
375     return hfp_hf_send_cmd_with_mark(cid, HFP_GENERIC_STATUS_INDICATOR, "?");
376 }
377 
378 static int hfp_hf_cmd_query_operator_name_format(uint16_t cid){
379     return hfp_hf_send_cmd_with_mark(cid, HFP_QUERY_OPERATOR_SELECTION, "=3,0");
380 }
381 
382 static int hfp_hf_cmd_query_operator_name(uint16_t cid){
383     return hfp_hf_send_cmd_with_mark(cid, HFP_QUERY_OPERATOR_SELECTION, "?");
384 }
385 
386 static int hfp_hf_cmd_trigger_codec_connection_setup(uint16_t cid){
387     return hfp_hf_send_cmd(cid, HFP_TRIGGER_CODEC_CONNECTION_SETUP);
388 }
389 
390 static int hfp_hf_set_microphone_gain_cmd(uint16_t cid, int gain){
391     return hfp_hf_send_cmd_with_int(cid, HFP_SET_MICROPHONE_GAIN, gain);
392 }
393 
394 static int hfp_hf_set_speaker_gain_cmd(uint16_t cid, int gain){
395     return hfp_hf_send_cmd_with_int(cid, HFP_SET_SPEAKER_GAIN, gain);
396 }
397 
398 static int hfp_hf_set_calling_line_notification_cmd(uint16_t cid, uint8_t activate){
399     return hfp_hf_send_cmd_with_int(cid, HFP_ENABLE_CLIP, activate);
400 }
401 
402 static int hfp_hf_set_voice_recognition_notification_cmd(uint16_t cid, uint8_t activate){
403     return hfp_hf_send_cmd_with_int(cid, HFP_ACTIVATE_VOICE_RECOGNITION, activate);
404 }
405 
406 static int hfp_hf_set_call_waiting_notification_cmd(uint16_t cid, uint8_t activate){
407     return hfp_hf_send_cmd_with_int(cid, HFP_ENABLE_CALL_WAITING_NOTIFICATION, activate);
408 }
409 
410 static int hfp_hf_cmd_confirm_codec(uint16_t cid, uint8_t codec){
411     return hfp_hf_send_cmd_with_int(cid, HFP_CONFIRM_COMMON_CODEC, codec);
412 }
413 
414 static int hfp_hf_cmd_enable_extended_audio_gateway_error_report(uint16_t cid, uint8_t enable){
415     return hfp_hf_send_cmd_with_int(cid, HFP_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR, enable);
416 }
417 
418 static int hfp_hf_send_redial_last_number_cmd(uint16_t cid){
419     return hfp_hf_send_cmd(cid, HFP_REDIAL_LAST_NUMBER);
420 }
421 
422 static int hfp_hf_send_chup(uint16_t cid){
423     return hfp_hf_send_cmd(cid, HFP_HANG_UP_CALL);
424 }
425 
426 static int hfp_hf_send_binp(uint16_t cid){
427     return hfp_hf_send_cmd_with_mark(cid, HFP_PHONE_NUMBER_FOR_VOICE_TAG, "=1");
428 }
429 
430 static int hfp_hf_send_clcc(uint16_t cid){
431     return hfp_hf_send_cmd(cid, HFP_LIST_CURRENT_CALLS);
432 }
433 
434 /* state machines */
435 
436 static int hfp_hf_run_for_context_service_level_connection(hfp_connection_t * hfp_connection){
437     if (hfp_connection->state >= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) return 0;
438     if (hfp_connection->ok_pending) return 0;
439     int done = 1;
440     log_info("hfp_hf_run_for_context_service_level_connection state %d\n", hfp_connection->state);
441     switch (hfp_connection->state){
442         case HFP_EXCHANGE_SUPPORTED_FEATURES:
443             hfp_hf_drop_mSBC_if_eSCO_not_supported(hfp_hf_codecs, &hfp_hf_codecs_nr);
444             hfp_connection->state = HFP_W4_EXCHANGE_SUPPORTED_FEATURES;
445             hfp_hf_cmd_exchange_supported_features(hfp_connection->rfcomm_cid);
446             break;
447         case HFP_NOTIFY_ON_CODECS:
448             hfp_connection->state = HFP_W4_NOTIFY_ON_CODECS;
449             hfp_hf_cmd_notify_on_codecs(hfp_connection->rfcomm_cid);
450             break;
451         case HFP_RETRIEVE_INDICATORS:
452             hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS;
453             hfp_hf_cmd_retrieve_indicators(hfp_connection->rfcomm_cid);
454             break;
455         case HFP_RETRIEVE_INDICATORS_STATUS:
456             hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS_STATUS;
457             hfp_hf_cmd_retrieve_indicators_status(hfp_connection->rfcomm_cid);
458             break;
459         case HFP_ENABLE_INDICATORS_STATUS_UPDATE:
460             hfp_connection->state = HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE;
461             hfp_hf_cmd_activate_status_update_for_all_ag_indicators(hfp_connection->rfcomm_cid, 1);
462             break;
463         case HFP_RETRIEVE_CAN_HOLD_CALL:
464             hfp_connection->state = HFP_W4_RETRIEVE_CAN_HOLD_CALL;
465             hfp_hf_cmd_retrieve_can_hold_call(hfp_connection->rfcomm_cid);
466             break;
467         case HFP_LIST_GENERIC_STATUS_INDICATORS:
468             hfp_connection->state = HFP_W4_LIST_GENERIC_STATUS_INDICATORS;
469             hfp_hf_cmd_list_supported_generic_status_indicators(hfp_connection->rfcomm_cid);
470             break;
471         case HFP_RETRIEVE_GENERIC_STATUS_INDICATORS:
472             hfp_connection->state = HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS;
473             hfp_hf_cmd_retrieve_supported_generic_status_indicators(hfp_connection->rfcomm_cid);
474             break;
475         case HFP_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS:
476             hfp_connection->state = HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS;
477             hfp_hf_cmd_list_initital_supported_generic_status_indicators(hfp_connection->rfcomm_cid);
478             break;
479         default:
480             done = 0;
481             break;
482     }
483     return done;
484 }
485 
486 
487 static int hfp_hf_run_for_context_service_level_connection_queries(hfp_connection_t * hfp_connection){
488     if (hfp_connection->state != HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) return 0;
489     if (hfp_connection->ok_pending){
490         return 0;
491     }
492     int done = 0;
493     if (hfp_connection->enable_status_update_for_ag_indicators != 0xFF){
494         hfp_connection->ok_pending = 1;
495         done = 1;
496         hfp_hf_cmd_activate_status_update_for_all_ag_indicators(hfp_connection->rfcomm_cid, hfp_connection->enable_status_update_for_ag_indicators);
497         return done;
498     };
499     if (hfp_connection->change_status_update_for_individual_ag_indicators){
500         hfp_connection->ok_pending = 1;
501         done = 1;
502         hfp_hf_cmd_activate_status_update_for_ag_indicator(hfp_connection->rfcomm_cid,
503                 hfp_connection->ag_indicators_status_update_bitmap,
504                 hfp_connection->ag_indicators_nr);
505         return done;
506     }
507 
508     switch (hfp_connection->hf_query_operator_state){
509         case HFP_HF_QUERY_OPERATOR_SET_FORMAT:
510             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_W4_SET_FORMAT_OK;
511             hfp_connection->ok_pending = 1;
512             hfp_hf_cmd_query_operator_name_format(hfp_connection->rfcomm_cid);
513             return 1;
514         case HFP_HF_QUERY_OPERATOR_SEND_QUERY:
515             hfp_connection->hf_query_operator_state = HPF_HF_QUERY_OPERATOR_W4_RESULT;
516             hfp_connection->ok_pending = 1;
517             hfp_hf_cmd_query_operator_name(hfp_connection->rfcomm_cid);
518             return 1;
519         default:
520             break;
521     }
522 
523     if (hfp_connection->enable_extended_audio_gateway_error_report){
524         hfp_connection->ok_pending = 1;
525         done = 1;
526         hfp_hf_cmd_enable_extended_audio_gateway_error_report(hfp_connection->rfcomm_cid, hfp_connection->enable_extended_audio_gateway_error_report);
527         return done;
528     }
529 
530     return done;
531 }
532 
533 static int hfp_hf_voice_recognition_state_machine(hfp_connection_t * hfp_connection){
534     if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) {
535         return 0;
536     }
537     int done = 0;
538 
539     if (hfp_connection->ok_pending == 1){
540         return 0;
541     }
542     // voice recognition activated from AG
543     if (hfp_connection->command == HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION){
544         switch(hfp_connection->vra_state_requested){
545             case HFP_VRA_W4_VOICE_RECOGNITION_ACTIVATED:
546             case HFP_VRA_W4_VOICE_RECOGNITION_OFF:
547             case HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
548                 // ignore AG command, continue to wait for OK
549                 return 0;
550 
551             default:
552                 if (hfp_connection->ag_vra_msg_length > 0){
553                     hfp_hf_emit_enhanced_voice_recognition_text(hfp_connection);
554                     hfp_connection->ag_vra_msg_length = 0;
555                     break;
556                 }
557                 switch(hfp_connection->ag_vra_state){
558                     case HFP_VOICE_RECOGNITION_STATE_AG_READY:
559                         switch (hfp_connection->ag_vra_status){
560                             case 0:
561                                 hfp_connection->vra_state_requested = HFP_VRA_W4_VOICE_RECOGNITION_OFF;
562                                 break;
563                             case 1:
564                                 hfp_connection->vra_state_requested = HFP_VRA_W4_VOICE_RECOGNITION_ACTIVATED;
565                                 break;
566                             case 2:
567                                 hfp_connection->vra_state_requested = HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO;
568                                 break;
569                             default:
570                                 break;
571                         }
572                         break;
573                     default:
574                         // state messages from AG
575                         hfp_emit_enhanced_voice_recognition_state_event(hfp_connection, ERROR_CODE_SUCCESS);
576                         hfp_connection->ag_vra_state = HFP_VOICE_RECOGNITION_STATE_AG_READY;
577                         break;
578                 }
579                 break;
580         }
581         hfp_connection->command = HFP_CMD_NONE;
582     }
583 
584 
585     switch (hfp_connection->vra_state_requested){
586         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF:
587             done = hfp_hf_set_voice_recognition_notification_cmd(hfp_connection->rfcomm_cid, 0);
588             if (done != 0){
589                 hfp_connection->vra_state_requested = HFP_VRA_W4_VOICE_RECOGNITION_OFF;
590                 hfp_connection->ok_pending = 1;
591             }
592             return 1;
593 
594 
595         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED:
596             done = hfp_hf_set_voice_recognition_notification_cmd(hfp_connection->rfcomm_cid, 1);
597             if (done != 0){
598                 hfp_connection->vra_state_requested = HFP_VRA_W4_VOICE_RECOGNITION_ACTIVATED;
599                 hfp_connection->ok_pending = 1;
600                 return 1;
601             }
602             break;
603 
604         case HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
605             done = hfp_hf_set_voice_recognition_notification_cmd(hfp_connection->rfcomm_cid, 2);
606             if (done != 0){
607                 hfp_connection->vra_state_requested = HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO;
608                 hfp_connection->ok_pending = 1;
609                 return 1;
610             }
611             break;
612 
613         case HFP_VRA_W4_VOICE_RECOGNITION_OFF:
614             hfp_connection->vra_state = HFP_VRA_VOICE_RECOGNITION_OFF;
615             hfp_connection->vra_state_requested = hfp_connection->vra_state;
616             hfp_connection->activate_voice_recognition = false;
617             if (hfp_connection->activate_voice_recognition){
618                 hfp_connection->enhanced_voice_recognition_enabled = hfp_hf_enhanced_vra_flag_supported(hfp_connection);
619                 hfp_hf_activate_voice_recognition(hfp_connection->acl_handle);
620             } else {
621                 hfp_emit_voice_recognition_disabled(hfp_connection, ERROR_CODE_SUCCESS);
622             }
623             break;
624 
625         case HFP_VRA_W4_VOICE_RECOGNITION_ACTIVATED:
626             hfp_connection->vra_state = HFP_VRA_VOICE_RECOGNITION_ACTIVATED;
627             hfp_connection->vra_state_requested = hfp_connection->vra_state;
628             hfp_connection->activate_voice_recognition = false;
629             if (hfp_connection->deactivate_voice_recognition){
630                 hfp_hf_deactivate_voice_recognition(hfp_connection->acl_handle);
631             } else {
632                 hfp_connection->enhanced_voice_recognition_enabled = hfp_hf_enhanced_vra_flag_supported(hfp_connection);
633                 if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
634                     hfp_emit_voice_recognition_enabled(hfp_connection, ERROR_CODE_SUCCESS);
635                 } else {
636                     // postpone VRA event to simplify application logic
637                     hfp_connection->emit_vra_enabled_after_audio_established = true;
638                 }
639             }
640             break;
641 
642 
643         case HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
644             hfp_connection->vra_state = HFP_VRA_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO;
645             hfp_connection->vra_state_requested = hfp_connection->vra_state;
646             hfp_connection->activate_voice_recognition = false;
647             if (hfp_connection->deactivate_voice_recognition){
648                 hfp_hf_deactivate_voice_recognition(hfp_connection->acl_handle);
649             } else {
650                 hfp_emit_enhanced_voice_recognition_hf_ready_for_audio_event(hfp_connection, ERROR_CODE_SUCCESS);
651             }
652             break;
653 
654         default:
655             break;
656     }
657     return done;
658 }
659 
660 
661 static int codecs_exchange_state_machine(hfp_connection_t * hfp_connection){
662     if (hfp_connection->ok_pending) return 0;
663 
664     if (hfp_connection->trigger_codec_exchange){
665 		hfp_connection->trigger_codec_exchange = 0;
666 
667 		hfp_connection->ok_pending = 1;
668 		hfp_hf_cmd_trigger_codec_connection_setup(hfp_connection->rfcomm_cid);
669 		return 1;
670     }
671 
672     if (hfp_connection->hf_send_codec_confirm){
673 		hfp_connection->hf_send_codec_confirm = false;
674 
675 		hfp_connection->ok_pending = 1;
676 		hfp_hf_cmd_confirm_codec(hfp_connection->rfcomm_cid, hfp_connection->codec_confirmed);
677 		return 1;
678     }
679 
680     if (hfp_connection->hf_send_supported_codecs){
681 		hfp_connection->hf_send_supported_codecs = false;
682 
683 		hfp_connection->ok_pending = 1;
684 		hfp_hf_cmd_notify_on_codecs(hfp_connection->rfcomm_cid);
685 		return 1;
686     }
687 
688     return 0;
689 }
690 
691 static int hfp_hf_run_for_audio_connection(hfp_connection_t * hfp_connection){
692     if ((hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) ||
693         (hfp_connection->state > HFP_W2_DISCONNECT_SCO)) return 0;
694 
695     if (hfp_connection->release_audio_connection){
696         hfp_connection->state = HFP_W4_SCO_DISCONNECTED;
697         hfp_connection->release_audio_connection = 0;
698         gap_disconnect(hfp_connection->sco_handle);
699         return 1;
700     }
701 
702     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
703 
704     // run codecs exchange
705     int done = codecs_exchange_state_machine(hfp_connection);
706     if (done) return 1;
707 
708     if (hfp_connection->codecs_state != HFP_CODECS_EXCHANGED) return 0;
709     if (hfp_connection->establish_audio_connection){
710         hfp_connection->state = HFP_W4_SCO_CONNECTED;
711         hfp_connection->establish_audio_connection = 0;
712         hfp_setup_synchronous_connection(hfp_connection);
713         return 1;
714     }
715     return 0;
716 }
717 
718 
719 static int call_setup_state_machine(hfp_connection_t * hfp_connection){
720 
721 	if (hfp_connection->ok_pending) return 0;
722 
723     if (hfp_connection->hf_answer_incoming_call){
724         hfp_hf_cmd_ata(hfp_connection->rfcomm_cid);
725         hfp_connection->hf_answer_incoming_call = 0;
726         return 1;
727     }
728     return 0;
729 }
730 
731 static void hfp_hf_run_for_context(hfp_connection_t * hfp_connection){
732 
733 	btstack_assert(hfp_connection != NULL);
734 	btstack_assert(hfp_connection->local_role == HFP_ROLE_HF);
735 
736 	// during SDP query, RFCOMM CID is not set
737 	if (hfp_connection->rfcomm_cid == 0) return;
738 
739     // emit postponed VRA event
740     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED && hfp_connection->emit_vra_enabled_after_audio_established){
741         hfp_connection->emit_vra_enabled_after_audio_established = false;
742         hfp_emit_voice_recognition_enabled(hfp_connection, ERROR_CODE_SUCCESS);
743     }
744 
745 	// assert command could be sent
746 	if (hci_can_send_command_packet_now() == 0) return;
747 
748 #ifdef ENABLE_CC256X_ASSISTED_HFP
749     // WBS Disassociate
750     if (hfp_connection->cc256x_send_wbs_disassociate){
751         hfp_connection->cc256x_send_wbs_disassociate = false;
752         hci_send_cmd(&hci_ti_wbs_disassociate);
753         return;
754     }
755     // Write Codec Config
756     if (hfp_connection->cc256x_send_write_codec_config){
757         hfp_connection->cc256x_send_write_codec_config = false;
758         hfp_cc256x_write_codec_config(hfp_connection);
759         return;
760     }
761     // WBS Associate
762     if (hfp_connection->cc256x_send_wbs_associate){
763         hfp_connection->cc256x_send_wbs_associate = false;
764         hci_send_cmd(&hci_ti_wbs_associate, hfp_connection->acl_handle);
765         return;
766     }
767 #endif
768 #ifdef ENABLE_BCM_PCM_WBS
769     // Enable WBS
770     if (hfp_connection->bcm_send_enable_wbs){
771         hfp_connection->bcm_send_enable_wbs = false;
772         hci_send_cmd(&hci_bcm_enable_wbs, 1, 2);
773         return;
774     }
775     // Write I2S/PCM params
776     if (hfp_connection->bcm_send_write_i2spcm_interface_param){
777         hfp_connection->bcm_send_write_i2spcm_interface_param = false;
778         hfp_bcm_write_i2spcm_interface_param(hfp_connection);
779         return;
780     }
781     // Disable WBS
782     if (hfp_connection->bcm_send_disable_wbs){
783         hfp_connection->bcm_send_disable_wbs = false;
784         hci_send_cmd(&hci_bcm_enable_wbs, 0, 2);
785         return;
786     }
787 #endif
788 #ifdef ENABLE_RTK_PCM_WBS
789     if (hfp_connection->rtk_send_sco_config){
790         hfp_connection->rtk_send_sco_config = false;
791         if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
792             log_info("RTK SCO: 16k + mSBC");
793             hci_send_cmd(&hci_rtk_configure_sco_routing, 0x81, 0x90, 0x00, 0x00, 0x1a, 0x0c, 0x00, 0x00, 0x41);
794         } else {
795             log_info("RTK SCO: 16k + CVSD");
796             hci_send_cmd(&hci_rtk_configure_sco_routing, 0x81, 0x90, 0x00, 0x00, 0x1a, 0x0c, 0x0c, 0x00, 0x01);
797         }
798         return;
799     }
800 #endif
801 #if defined (ENABLE_CC256X_ASSISTED_HFP) || defined (ENABLE_BCM_PCM_WBS)
802     if (hfp_connection->state == HFP_W4_WBS_SHUTDOWN){
803         hfp_finalize_connection_context(hfp_connection);
804         return;
805     }
806 #endif
807 
808     if (hfp_connection->accept_sco){
809         bool incoming_eSCO = hfp_connection->accept_sco == 2;
810         hfp_connection->accept_sco = 0;
811         // notify about codec selection if not done already
812         if (hfp_connection->negotiated_codec == 0){
813             hfp_connection->negotiated_codec = HFP_CODEC_CVSD;
814         }
815         hfp_accept_synchronous_connection(hfp_connection, incoming_eSCO);
816         return;
817     }
818 
819     if (!rfcomm_can_send_packet_now(hfp_connection->rfcomm_cid)) {
820         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
821         return;
822     }
823     int done = hfp_hf_run_for_context_service_level_connection(hfp_connection);
824     if (!done){
825         done = hfp_hf_run_for_context_service_level_connection_queries(hfp_connection);
826     }
827     if (!done){
828         done = hfp_hf_run_for_audio_connection(hfp_connection);
829     }
830     if (!done){
831         done = hfp_hf_voice_recognition_state_machine(hfp_connection);
832     }
833     if (!done){
834         done = call_setup_state_machine(hfp_connection);
835     }
836 
837     // don't send a new command while ok still pending or SLC is not established
838     if (hfp_connection->ok_pending || (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED)){
839         return;
840     }
841 
842     if (hfp_connection->send_microphone_gain){
843         hfp_connection->send_microphone_gain = 0;
844         hfp_connection->ok_pending = 1;
845         hfp_hf_set_microphone_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->microphone_gain);
846         return;
847     }
848 
849     if (hfp_connection->send_speaker_gain){
850         hfp_connection->send_speaker_gain = 0;
851         hfp_connection->ok_pending = 1;
852         hfp_hf_set_speaker_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->speaker_gain);
853         return;
854     }
855 
856     if (hfp_connection->hf_deactivate_calling_line_notification){
857         hfp_connection->hf_deactivate_calling_line_notification = 0;
858         hfp_connection->ok_pending = 1;
859         hfp_hf_set_calling_line_notification_cmd(hfp_connection->rfcomm_cid, 0);
860         return;
861     }
862 
863     if (hfp_connection->hf_activate_calling_line_notification){
864         hfp_connection->hf_activate_calling_line_notification = 0;
865         hfp_connection->ok_pending = 1;
866         hfp_hf_set_calling_line_notification_cmd(hfp_connection->rfcomm_cid, 1);
867         return;
868     }
869 
870     if (hfp_connection->hf_deactivate_echo_canceling_and_noise_reduction){
871         hfp_connection->hf_deactivate_echo_canceling_and_noise_reduction = 0;
872         hfp_connection->response_pending_for_command = HFP_CMD_TURN_OFF_EC_AND_NR;
873         hfp_connection->ok_pending = 1;
874         hfp_hf_send_cmd_with_int(hfp_connection->rfcomm_cid, HFP_TURN_OFF_EC_AND_NR, 0);
875         return;
876     }
877 
878     if (hfp_connection->hf_deactivate_call_waiting_notification){
879         hfp_connection->hf_deactivate_call_waiting_notification = 0;
880         hfp_connection->ok_pending = 1;
881         hfp_hf_set_call_waiting_notification_cmd(hfp_connection->rfcomm_cid, 0);
882         return;
883     }
884 
885     if (hfp_connection->hf_activate_call_waiting_notification){
886         hfp_connection->hf_activate_call_waiting_notification = 0;
887         hfp_connection->ok_pending = 1;
888         hfp_hf_set_call_waiting_notification_cmd(hfp_connection->rfcomm_cid, 1);
889         return;
890     }
891 
892     if (hfp_connection->hf_initiate_outgoing_call){
893         hfp_connection->hf_initiate_outgoing_call = 0;
894         hfp_connection->ok_pending = 1;
895         hfp_hf_initiate_outgoing_call_cmd(hfp_connection->rfcomm_cid);
896         return;
897     }
898 
899     if (hfp_connection->hf_initiate_memory_dialing){
900         hfp_connection->hf_initiate_memory_dialing = 0;
901         hfp_connection->ok_pending = 1;
902         hfp_hf_send_memory_dial_cmd(hfp_connection->rfcomm_cid, hfp_connection->memory_id);
903         return;
904     }
905 
906     if (hfp_connection->hf_initiate_redial_last_number){
907         hfp_connection->hf_initiate_redial_last_number = 0;
908         hfp_connection->ok_pending = 1;
909         hfp_hf_send_redial_last_number_cmd(hfp_connection->rfcomm_cid);
910         return;
911     }
912 
913     if (hfp_connection->hf_send_chup){
914         hfp_connection->hf_send_chup = 0;
915         hfp_connection->ok_pending = 1;
916         hfp_hf_send_chup(hfp_connection->rfcomm_cid);
917         return;
918     }
919 
920     if (hfp_connection->hf_send_chld_0){
921         hfp_connection->hf_send_chld_0 = 0;
922         hfp_connection->ok_pending = 1;
923         hfp_hf_send_chld(hfp_connection->rfcomm_cid, 0);
924         return;
925     }
926 
927     if (hfp_connection->hf_send_chld_1){
928         hfp_connection->hf_send_chld_1 = 0;
929         hfp_connection->ok_pending = 1;
930         hfp_hf_send_chld(hfp_connection->rfcomm_cid, 1);
931         return;
932     }
933 
934     if (hfp_connection->hf_send_chld_2){
935         hfp_connection->hf_send_chld_2 = 0;
936         hfp_connection->ok_pending = 1;
937         hfp_hf_send_chld(hfp_connection->rfcomm_cid, 2);
938         return;
939     }
940 
941     if (hfp_connection->hf_send_chld_3){
942         hfp_connection->hf_send_chld_3 = 0;
943         hfp_connection->ok_pending = 1;
944         hfp_hf_send_chld(hfp_connection->rfcomm_cid, 3);
945         return;
946     }
947 
948     if (hfp_connection->hf_send_chld_4){
949         hfp_connection->hf_send_chld_4 = 0;
950         hfp_connection->ok_pending = 1;
951         hfp_hf_send_chld(hfp_connection->rfcomm_cid, 4);
952         return;
953     }
954 
955     if (hfp_connection->hf_send_chld_x){
956         hfp_connection->hf_send_chld_x = 0;
957         hfp_connection->ok_pending = 1;
958         hfp_hf_send_chld(hfp_connection->rfcomm_cid, hfp_connection->hf_send_chld_x_index);
959         return;
960     }
961 
962     if (hfp_connection->hf_send_dtmf_code){
963         char code = hfp_connection->hf_send_dtmf_code;
964         hfp_connection->hf_send_dtmf_code = 0;
965         hfp_connection->ok_pending = 1;
966         hfp_hf_send_dtmf(hfp_connection->rfcomm_cid, code);
967         return;
968     }
969 
970     if (hfp_connection->hf_send_binp){
971         hfp_connection->hf_send_binp = 0;
972         hfp_connection->ok_pending = 1;
973         hfp_hf_send_binp(hfp_connection->rfcomm_cid);
974         return;
975     }
976 
977     if (hfp_connection->hf_send_clcc){
978         hfp_connection->hf_send_clcc = 0;
979         hfp_connection->ok_pending = 1;
980         hfp_hf_send_clcc(hfp_connection->rfcomm_cid);
981         return;
982     }
983 
984     if (hfp_connection->hf_send_rrh){
985         hfp_connection->hf_send_rrh = 0;
986         char buffer[20];
987         switch (hfp_connection->hf_send_rrh_command){
988             case '?':
989                 snprintf(buffer, sizeof(buffer), "AT%s?\r",
990                          HFP_RESPONSE_AND_HOLD);
991                 buffer[sizeof(buffer) - 1] = 0;
992                 send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
993                 return;
994             case '0':
995             case '1':
996             case '2':
997                 snprintf(buffer, sizeof(buffer), "AT%s=%c\r",
998                          HFP_RESPONSE_AND_HOLD,
999                          hfp_connection->hf_send_rrh_command);
1000                 buffer[sizeof(buffer) - 1] = 0;
1001                 send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1002                 return;
1003             default:
1004                 break;
1005         }
1006         return;
1007     }
1008 
1009     if (hfp_connection->hf_send_cnum){
1010         hfp_connection->hf_send_cnum = 0;
1011         char buffer[20];
1012         snprintf(buffer, sizeof(buffer), "AT%s\r",
1013                  HFP_SUBSCRIBER_NUMBER_INFORMATION);
1014         buffer[sizeof(buffer) - 1] = 0;
1015         send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1016         return;
1017     }
1018 
1019     // update HF indicators
1020     if (hfp_connection->generic_status_update_bitmap){
1021         int i;
1022         for (i=0; i < hfp_hf_indicators_nr; i++){
1023             if (get_bit(hfp_connection->generic_status_update_bitmap, i)){
1024                 if (hfp_connection->generic_status_indicators[i].state){
1025                     hfp_connection->ok_pending = 1;
1026                     hfp_connection->generic_status_update_bitmap = store_bit(hfp_connection->generic_status_update_bitmap, i, 0);
1027                     char buffer[30];
1028                     snprintf(buffer, sizeof(buffer), "AT%s=%u,%u\r",
1029                              HFP_TRANSFER_HF_INDICATOR_STATUS,
1030                              hfp_hf_indicators[i],
1031                              (unsigned int)hfp_hf_indicators_value[i]);
1032                     buffer[sizeof(buffer) - 1] = 0;
1033                     send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1034                 } else {
1035                     log_info("Not sending HF indicator %u as it is disabled", hfp_hf_indicators[i]);
1036                 }
1037                 return;
1038             }
1039         }
1040     }
1041 
1042     if (done) return;
1043     // deal with disconnect
1044     switch (hfp_connection->state){
1045         case HFP_W2_DISCONNECT_RFCOMM:
1046             hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED;
1047             rfcomm_disconnect(hfp_connection->rfcomm_cid);
1048             break;
1049 
1050         default:
1051             break;
1052     }
1053 }
1054 
1055 static void hfp_ag_slc_established(hfp_connection_t * hfp_connection){
1056     hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1057 
1058     hfp_emit_slc_connection_event(hfp_connection, 0, hfp_connection->acl_handle, hfp_connection->remote_addr);
1059 
1060     uint8_t i;
1061     for (i = 0; i < hfp_connection->ag_indicators_nr; i++){
1062         hfp_emit_ag_indicator_mapping_event(hfp_connection, &hfp_connection->ag_indicators[i]);
1063     }
1064 
1065     for (i = 0; i < hfp_connection->ag_indicators_nr; i++){
1066         hfp_connection->ag_indicators[i].status_changed = 0;
1067         hfp_emit_ag_indicator_status_event(hfp_connection, &hfp_connection->ag_indicators[i]);
1068     }
1069 
1070     // restore volume settings
1071     hfp_connection->speaker_gain = hfp_hf_speaker_gain;
1072     hfp_connection->send_speaker_gain = 1;
1073     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SPEAKER_VOLUME, hfp_hf_speaker_gain);
1074     hfp_connection->microphone_gain = hfp_hf_microphone_gain;
1075     hfp_connection->send_microphone_gain = 1;
1076     hfp_emit_event(hfp_connection, HFP_SUBEVENT_MICROPHONE_VOLUME, hfp_hf_microphone_gain);
1077     // enable all indicators
1078     for (i=0; i < hfp_hf_indicators_nr; i++){
1079         hfp_connection->generic_status_indicators[i].uuid = hfp_hf_indicators[i];
1080         hfp_connection->generic_status_indicators[i].state = 1;
1081     }
1082 }
1083 
1084 static void hfp_hf_handle_suggested_codec(hfp_connection_t * hfp_connection){
1085 	if (hfp_supports_codec(hfp_connection->suggested_codec, hfp_hf_codecs_nr, hfp_hf_codecs)){
1086 		// Codec supported, confirm
1087 		hfp_connection->negotiated_codec = hfp_connection->suggested_codec;
1088 		hfp_connection->codec_confirmed = hfp_connection->suggested_codec;
1089 		log_info("hfp: codec confirmed: %s", (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? "mSBC" : "CVSD");
1090 		hfp_connection->codecs_state = HFP_CODECS_HF_CONFIRMED_CODEC;
1091 
1092 		hfp_connection->hf_send_codec_confirm = true;
1093 	} else {
1094 		// Codec not supported, send supported codecs
1095 		hfp_connection->codec_confirmed = 0;
1096 		hfp_connection->suggested_codec = 0;
1097 		hfp_connection->negotiated_codec = 0;
1098 		hfp_connection->codecs_state = HFP_CODECS_W4_AG_COMMON_CODEC;
1099 
1100 		hfp_connection->hf_send_supported_codecs = true;
1101 	}
1102 }
1103 
1104 static bool hfp_hf_switch_on_ok_pending(hfp_connection_t *hfp_connection, uint8_t status){
1105     bool event_emited = true;
1106 
1107     switch (hfp_connection->response_pending_for_command){
1108         case HFP_CMD_TURN_OFF_EC_AND_NR:
1109             hfp_emit_event(hfp_connection, HFP_SUBEVENT_ECHO_CANCELING_AND_NOISE_REDUCTION_DEACTIVATE, status);
1110             break;
1111         default:
1112             event_emited = false;
1113 
1114             switch (hfp_connection->state){
1115                 case HFP_W4_EXCHANGE_SUPPORTED_FEATURES:
1116                     if (has_codec_negotiation_feature(hfp_connection)){
1117                         hfp_connection->state = HFP_NOTIFY_ON_CODECS;
1118                         break;
1119                     }
1120                     hfp_connection->state = HFP_RETRIEVE_INDICATORS;
1121                     break;
1122 
1123                 case HFP_W4_NOTIFY_ON_CODECS:
1124                     hfp_connection->state = HFP_RETRIEVE_INDICATORS;
1125                     break;
1126 
1127                 case HFP_W4_RETRIEVE_INDICATORS:
1128                     hfp_connection->state = HFP_RETRIEVE_INDICATORS_STATUS;
1129                     break;
1130 
1131                 case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1132                     hfp_connection->state = HFP_ENABLE_INDICATORS_STATUS_UPDATE;
1133                     break;
1134 
1135                 case HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE:
1136                     if (has_call_waiting_and_3way_calling_feature(hfp_connection)){
1137                         hfp_connection->state = HFP_RETRIEVE_CAN_HOLD_CALL;
1138                         break;
1139                     }
1140                     if (has_hf_indicators_feature(hfp_connection)){
1141                         hfp_connection->state = HFP_LIST_GENERIC_STATUS_INDICATORS;
1142                         break;
1143                     }
1144                     hfp_ag_slc_established(hfp_connection);
1145                     break;
1146 
1147                 case HFP_W4_RETRIEVE_CAN_HOLD_CALL:
1148                     if (has_hf_indicators_feature(hfp_connection)){
1149                         hfp_connection->state = HFP_LIST_GENERIC_STATUS_INDICATORS;
1150                         break;
1151                     }
1152                     hfp_ag_slc_established(hfp_connection);
1153                     break;
1154 
1155                 case HFP_W4_LIST_GENERIC_STATUS_INDICATORS:
1156                     hfp_connection->state = HFP_RETRIEVE_GENERIC_STATUS_INDICATORS;
1157                     break;
1158 
1159                 case HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS:
1160                     hfp_connection->state = HFP_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS;
1161                     break;
1162 
1163                 case HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS:
1164                     hfp_ag_slc_established(hfp_connection);
1165                     break;
1166                 case HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED:
1167                     if (hfp_connection->enable_status_update_for_ag_indicators != 0xFF){
1168                         hfp_connection->enable_status_update_for_ag_indicators = 0xFF;
1169                         hfp_emit_event(hfp_connection, HFP_SUBEVENT_COMPLETE, 0);
1170                         break;
1171                     }
1172 
1173                     if (hfp_connection->change_status_update_for_individual_ag_indicators == 1){
1174                         hfp_connection->change_status_update_for_individual_ag_indicators = 0;
1175                         hfp_emit_event(hfp_connection, HFP_SUBEVENT_COMPLETE, 0);
1176                         break;
1177                     }
1178 
1179                     switch (hfp_connection->hf_query_operator_state){
1180                         case HFP_HF_QUERY_OPERATOR_W4_SET_FORMAT_OK:
1181                             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_SEND_QUERY;
1182                             break;
1183                         case HPF_HF_QUERY_OPERATOR_W4_RESULT:
1184                             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_FORMAT_SET;
1185                             hfp_emit_network_operator_event(hfp_connection);
1186                             break;
1187                         default:
1188                             break;
1189                     }
1190 
1191                     if (hfp_connection->enable_extended_audio_gateway_error_report){
1192                         hfp_connection->enable_extended_audio_gateway_error_report = 0;
1193                         break;
1194                     }
1195 
1196                     switch (hfp_connection->codecs_state){
1197                         case HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE:
1198                             hfp_connection->codecs_state = HFP_CODECS_W4_AG_COMMON_CODEC;
1199                             break;
1200                         case HFP_CODECS_HF_CONFIRMED_CODEC:
1201                             hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
1202                             break;
1203                         default:
1204                             break;
1205                     }
1206                     hfp_hf_voice_recognition_state_machine(hfp_connection);
1207                     break;
1208                 case HFP_AUDIO_CONNECTION_ESTABLISHED:
1209                     hfp_hf_voice_recognition_state_machine(hfp_connection);
1210                     break;
1211                 default:
1212                     break;
1213             }
1214             break;
1215     }
1216 
1217     // done
1218     hfp_connection->response_pending_for_command = HFP_CMD_NONE;
1219     hfp_connection->ok_pending = 0;
1220     hfp_connection->command = HFP_CMD_NONE;
1221     return event_emited;
1222 }
1223 
1224 static bool hfp_is_ringing(hfp_callsetup_status_t callsetup_status){
1225     switch (callsetup_status){
1226         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1227         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1228             return true;
1229         default:
1230             return false;
1231    }
1232 }
1233 
1234 static void hfp_hf_handle_transfer_ag_indicator_status(hfp_connection_t * hfp_connection) {
1235     uint16_t i;
1236 
1237     for (i = 0; i < hfp_connection->ag_indicators_nr; i++){
1238         if (hfp_connection->ag_indicators[i].status_changed) {
1239             if (strcmp(hfp_connection->ag_indicators[i].name, "callsetup") == 0){
1240                 hfp_callsetup_status_t new_hf_callsetup_status = (hfp_callsetup_status_t) hfp_connection->ag_indicators[i].status;
1241                 bool ringing_old = hfp_is_ringing(hfp_hf_callsetup_status);
1242                 bool ringing_new = hfp_is_ringing(new_hf_callsetup_status);
1243                 if (ringing_old != ringing_new){
1244                     if (ringing_new){
1245                         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_START_RINGING);
1246                     } else {
1247                         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_STOP_RINGING);
1248                     }
1249                 }
1250                 hfp_hf_callsetup_status = new_hf_callsetup_status;
1251             } else if (strcmp(hfp_connection->ag_indicators[i].name, "callheld") == 0){
1252                 hfp_hf_callheld_status = (hfp_callheld_status_t) hfp_connection->ag_indicators[i].status;
1253                 // avoid set but not used warning
1254                 (void) hfp_hf_callheld_status;
1255             } else if (strcmp(hfp_connection->ag_indicators[i].name, "call") == 0){
1256                 hfp_call_status_t new_hf_call_status = (hfp_call_status_t) hfp_connection->ag_indicators[i].status;
1257                 if (hfp_hf_call_status != new_hf_call_status){
1258                     if (new_hf_call_status == HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS){
1259                         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_TERMINATED);
1260                     } else {
1261                         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_ANSWERED);
1262                     }
1263                 }
1264                 hfp_hf_call_status = new_hf_call_status;
1265             }
1266             hfp_connection->ag_indicators[i].status_changed = 0;
1267             hfp_emit_ag_indicator_status_event(hfp_connection, &hfp_connection->ag_indicators[i]);
1268             break;
1269         }
1270     }
1271 }
1272 
1273 static void hfp_hf_handle_rfcomm_command(hfp_connection_t * hfp_connection){
1274     int value;
1275     int i;
1276     bool event_emited;
1277 
1278     switch (hfp_connection->command){
1279         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1280             hfp_connection->command = HFP_CMD_NONE;
1281             hfp_hf_emit_subscriber_information(hfp_connection, 0);
1282             break;
1283         case HFP_CMD_RESPONSE_AND_HOLD_STATUS:
1284             hfp_connection->command = HFP_CMD_NONE;
1285             hfp_emit_event(hfp_connection, HFP_SUBEVENT_RESPONSE_AND_HOLD_STATUS, btstack_atoi((char *)&hfp_connection->line_buffer[0]));
1286             break;
1287         case HFP_CMD_LIST_CURRENT_CALLS:
1288             hfp_connection->command = HFP_CMD_NONE;
1289             hfp_hf_emit_enhanced_call_status(hfp_connection);
1290             break;
1291         case HFP_CMD_SET_SPEAKER_GAIN:
1292             hfp_connection->command = HFP_CMD_NONE;
1293             value = btstack_atoi((char*)hfp_connection->line_buffer);
1294             hfp_hf_speaker_gain = value;
1295             hfp_emit_event(hfp_connection, HFP_SUBEVENT_SPEAKER_VOLUME, value);
1296             break;
1297         case HFP_CMD_SET_MICROPHONE_GAIN:
1298             hfp_connection->command = HFP_CMD_NONE;
1299             value = btstack_atoi((char*)hfp_connection->line_buffer);
1300             hfp_hf_microphone_gain = value;
1301             hfp_emit_event(hfp_connection, HFP_SUBEVENT_MICROPHONE_VOLUME, value);
1302             break;
1303         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1304             hfp_connection->command = HFP_CMD_NONE;
1305             hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_NUMBER_FOR_VOICE_TAG, hfp_connection->bnip_number);
1306             break;
1307         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1308             hfp_connection->command = HFP_CMD_NONE;
1309             hfp_hf_emit_type_and_number(hfp_connection, HFP_SUBEVENT_CALL_WAITING_NOTIFICATION);
1310             break;
1311         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1312             hfp_connection->command = HFP_CMD_NONE;
1313             hfp_hf_emit_type_and_number(hfp_connection, HFP_SUBEVENT_CALLING_LINE_IDENTIFICATION_NOTIFICATION);
1314             break;
1315         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1316             hfp_connection->command = HFP_CMD_NONE;
1317             hfp_connection->ok_pending = 0;
1318             hfp_connection->extended_audio_gateway_error = 0;
1319             hfp_emit_event(hfp_connection, HFP_SUBEVENT_EXTENDED_AUDIO_GATEWAY_ERROR, hfp_connection->extended_audio_gateway_error_value);
1320             break;
1321         case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1322             break;
1323         case HFP_CMD_ERROR:
1324             switch (hfp_connection->state){
1325                 case HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED:
1326                     switch (hfp_connection->codecs_state){
1327                         case HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE:
1328                             hfp_reset_context_flags(hfp_connection);
1329                             hfp_emit_sco_event(hfp_connection, HFP_REMOTE_REJECTS_AUDIO_CONNECTION, 0, hfp_connection->remote_addr, hfp_connection->negotiated_codec);
1330                             return;
1331                         default:
1332                             break;
1333                     }
1334                     break;
1335                 default:
1336                     break;
1337             }
1338 
1339             // handle error response for voice activation (HF initiated)
1340             switch(hfp_connection->vra_state_requested){
1341                 case HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1342                     hfp_emit_enhanced_voice_recognition_hf_ready_for_audio_event(hfp_connection, ERROR_CODE_UNSPECIFIED_ERROR);
1343                     break;
1344                 default:
1345                     if (hfp_connection->vra_state_requested == hfp_connection->vra_state){
1346                         break;
1347                     }
1348                     hfp_connection->vra_state_requested = hfp_connection->vra_state;
1349                     hfp_emit_voice_recognition_enabled(hfp_connection, ERROR_CODE_UNSPECIFIED_ERROR);
1350                     hfp_reset_context_flags(hfp_connection);
1351                     return;
1352             }
1353             event_emited = hfp_hf_switch_on_ok_pending(hfp_connection, ERROR_CODE_UNSPECIFIED_ERROR);
1354             if (!event_emited){
1355                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_COMPLETE, 1);
1356             }
1357             hfp_reset_context_flags(hfp_connection);
1358             break;
1359 
1360         case HFP_CMD_OK:
1361             hfp_hf_switch_on_ok_pending(hfp_connection, ERROR_CODE_SUCCESS);
1362             break;
1363         case HFP_CMD_RING:
1364             hfp_connection->command = HFP_CMD_NONE;
1365             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_RING);
1366             break;
1367         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1368             hfp_connection->command = HFP_CMD_NONE;
1369             hfp_hf_handle_transfer_ag_indicator_status(hfp_connection);
1370             break;
1371         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1372             hfp_connection->command = HFP_CMD_NONE;
1373             // report status after SLC established
1374             if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
1375                 break;
1376             }
1377             for (i = 0; i < hfp_connection->ag_indicators_nr; i++){
1378                 hfp_emit_ag_indicator_mapping_event(hfp_connection, &hfp_connection->ag_indicators[i]);
1379             }
1380             break;
1381     	case HFP_CMD_AG_SUGGESTED_CODEC:
1382             hfp_connection->command = HFP_CMD_NONE;
1383     		hfp_hf_handle_suggested_codec(hfp_connection);
1384 			break;
1385         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1386             hfp_emit_event(hfp_connection, HFP_SUBEVENT_IN_BAND_RING_TONE, get_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE));
1387         default:
1388             break;
1389     }
1390 }
1391 
1392 static int hfp_parser_is_end_of_line(uint8_t byte){
1393 	return (byte == '\n') || (byte == '\r');
1394 }
1395 
1396 static void hfp_hf_handle_rfcomm_data(hfp_connection_t * hfp_connection, uint8_t *packet, uint16_t size){
1397     // assertion: size >= 1 as rfcomm.c does not deliver empty packets
1398     if (size < 1) return;
1399 
1400     hfp_log_rfcomm_message("HFP_HF_RX", packet, size);
1401 #ifdef ENABLE_HFP_AT_MESSAGES
1402     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_RECEIVED, (char *) packet);
1403 #endif
1404 
1405     // process messages byte-wise
1406     uint8_t pos;
1407     for (pos = 0; pos < size; pos++){
1408         hfp_parse(hfp_connection, packet[pos], 1);
1409         // parse until end of line "\r" or "\n"
1410         if (!hfp_parser_is_end_of_line(packet[pos])) continue;
1411         hfp_hf_handle_rfcomm_command(hfp_connection);
1412     }
1413 }
1414 
1415 static void hfp_hf_run(void){
1416     btstack_linked_list_iterator_t it;
1417     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1418     while (btstack_linked_list_iterator_has_next(&it)){
1419         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1420         if (hfp_connection->local_role != HFP_ROLE_HF) continue;
1421         hfp_hf_run_for_context(hfp_connection);
1422     }
1423 }
1424 
1425 static void hfp_hf_rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1426     hfp_connection_t * hfp_connection;
1427     switch (packet_type){
1428         case RFCOMM_DATA_PACKET:
1429             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(channel);
1430             if (!hfp_connection) return;
1431             hfp_hf_handle_rfcomm_data(hfp_connection, packet, size);
1432             hfp_hf_run_for_context(hfp_connection);
1433             return;
1434         case HCI_EVENT_PACKET:
1435             if (packet[0] == RFCOMM_EVENT_CAN_SEND_NOW){
1436                 uint16_t rfcomm_cid = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
1437                 hfp_hf_run_for_context(get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid));
1438                 return;
1439             }
1440             hfp_handle_rfcomm_event(packet_type, channel, packet, size, HFP_ROLE_HF);
1441             break;
1442         default:
1443             break;
1444     }
1445     hfp_hf_run();
1446 }
1447 
1448 static void hfp_hf_hci_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1449     hfp_handle_hci_event(packet_type, channel, packet, size, HFP_ROLE_HF);
1450     hfp_hf_run();
1451 }
1452 
1453 static void hfp_hf_set_defaults(void){
1454     hfp_hf_supported_features = HFP_DEFAULT_HF_SUPPORTED_FEATURES;
1455     hfp_hf_call_status = HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS;
1456     hfp_hf_callsetup_status = HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1457     hfp_hf_callheld_status= HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1458     hfp_hf_codecs_nr = 0;
1459     hfp_hf_speaker_gain = 9;
1460     hfp_hf_microphone_gain = 9;
1461     hfp_hf_indicators_nr = 0;
1462 }
1463 
1464 uint8_t hfp_hf_init(uint16_t rfcomm_channel_nr){
1465     uint8_t status = rfcomm_register_service(hfp_hf_rfcomm_packet_handler, rfcomm_channel_nr, 0xffff);
1466     if (status != ERROR_CODE_SUCCESS){
1467         return status;
1468     }
1469 
1470     hfp_init();
1471     hfp_hf_set_defaults();
1472 
1473     hfp_hf_hci_event_callback_registration.callback = &hfp_hf_hci_event_packet_handler;
1474     hci_add_event_handler(&hfp_hf_hci_event_callback_registration);
1475 
1476     // used to set packet handler for outgoing rfcomm connections - could be handled by emitting an event to us
1477     hfp_set_hf_rfcomm_packet_handler(&hfp_hf_rfcomm_packet_handler);
1478     return ERROR_CODE_SUCCESS;
1479 }
1480 
1481 void hfp_hf_deinit(void){
1482     hfp_deinit();
1483     hfp_hf_set_defaults();
1484 
1485     hfp_hf_callback = NULL;
1486     (void) memset(&hfp_hf_hci_event_callback_registration, 0, sizeof(btstack_packet_callback_registration_t));
1487     (void) memset(hfp_hf_phone_number, 0, sizeof(hfp_hf_phone_number));
1488 }
1489 
1490 void hfp_hf_init_codecs(int codecs_nr, const uint8_t * codecs){
1491     btstack_assert(codecs_nr < HFP_MAX_NUM_CODECS);
1492 
1493     hfp_hf_codecs_nr = codecs_nr;
1494     int i;
1495     for (i=0; i<codecs_nr; i++){
1496         hfp_hf_codecs[i] = codecs[i];
1497     }
1498 }
1499 
1500 void hfp_hf_init_supported_features(uint32_t supported_features){
1501     hfp_hf_supported_features = supported_features;
1502 }
1503 
1504 void hfp_hf_init_hf_indicators(int indicators_nr, const uint16_t * indicators){
1505     btstack_assert(hfp_hf_indicators_nr < HFP_MAX_NUM_INDICATORS);
1506 
1507     hfp_hf_indicators_nr = indicators_nr;
1508     int i;
1509     for (i = 0; i < hfp_hf_indicators_nr ; i++){
1510         hfp_hf_indicators[i] = indicators[i];
1511     }
1512 }
1513 
1514 uint8_t hfp_hf_establish_service_level_connection(bd_addr_t bd_addr){
1515     return hfp_establish_service_level_connection(bd_addr, BLUETOOTH_SERVICE_CLASS_HANDSFREE_AUDIO_GATEWAY, HFP_ROLE_HF);
1516 }
1517 
1518 uint8_t hfp_hf_release_service_level_connection(hci_con_handle_t acl_handle){
1519     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1520     if (!hfp_connection){
1521         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1522     }
1523     hfp_trigger_release_service_level_connection(hfp_connection);
1524     hfp_hf_run_for_context(hfp_connection);
1525     return ERROR_CODE_SUCCESS;
1526 }
1527 
1528 static uint8_t hfp_hf_set_status_update_for_all_ag_indicators(hci_con_handle_t acl_handle, uint8_t enable){
1529     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1530     if (!hfp_connection) {
1531         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1532     }
1533     hfp_connection->enable_status_update_for_ag_indicators = enable;
1534     hfp_hf_run_for_context(hfp_connection);
1535     return ERROR_CODE_SUCCESS;
1536 }
1537 
1538 uint8_t hfp_hf_enable_status_update_for_all_ag_indicators(hci_con_handle_t acl_handle){
1539     return hfp_hf_set_status_update_for_all_ag_indicators(acl_handle, 1);
1540 }
1541 
1542 uint8_t hfp_hf_disable_status_update_for_all_ag_indicators(hci_con_handle_t acl_handle){
1543     return hfp_hf_set_status_update_for_all_ag_indicators(acl_handle, 0);
1544 }
1545 
1546 // TODO: returned ERROR - wrong format
1547 uint8_t hfp_hf_set_status_update_for_individual_ag_indicators(hci_con_handle_t acl_handle, uint32_t indicators_status_bitmap){
1548     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1549     if (!hfp_connection) {
1550         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1551     }
1552     hfp_connection->change_status_update_for_individual_ag_indicators = 1;
1553     hfp_connection->ag_indicators_status_update_bitmap = indicators_status_bitmap;
1554     hfp_hf_run_for_context(hfp_connection);
1555     return ERROR_CODE_SUCCESS;
1556 }
1557 
1558 uint8_t hfp_hf_query_operator_selection(hci_con_handle_t acl_handle){
1559     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1560     if (!hfp_connection) {
1561         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1562     }
1563 
1564     switch (hfp_connection->hf_query_operator_state){
1565         case HFP_HF_QUERY_OPERATOR_FORMAT_NOT_SET:
1566             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_SET_FORMAT;
1567             break;
1568         case HFP_HF_QUERY_OPERATOR_FORMAT_SET:
1569             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_SEND_QUERY;
1570             break;
1571         default:
1572             return ERROR_CODE_COMMAND_DISALLOWED;
1573     }
1574     hfp_hf_run_for_context(hfp_connection);
1575     return ERROR_CODE_SUCCESS;
1576 }
1577 
1578 static uint8_t hfp_hf_set_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle, uint8_t enable){
1579     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1580     if (!hfp_connection) {
1581         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1582     }
1583     hfp_connection->enable_extended_audio_gateway_error_report = enable;
1584     hfp_hf_run_for_context(hfp_connection);
1585     return ERROR_CODE_SUCCESS;
1586 }
1587 
1588 
1589 uint8_t hfp_hf_enable_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle){
1590     return hfp_hf_set_report_extended_audio_gateway_error_result_code(acl_handle, 1);
1591 }
1592 
1593 uint8_t hfp_hf_disable_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle){
1594     return hfp_hf_set_report_extended_audio_gateway_error_result_code(acl_handle, 0);
1595 }
1596 
1597 static uint8_t hfp_hf_esco_s4_supported(hfp_connection_t * hfp_connection){
1598     return (hfp_connection->remote_supported_features & (1<<HFP_AGSF_ESCO_S4)) &&  (hfp_hf_supported_features & (1 << HFP_HFSF_ESCO_S4));
1599 }
1600 
1601 uint8_t hfp_hf_establish_audio_connection(hci_con_handle_t acl_handle){
1602     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1603     if (!hfp_connection) {
1604         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1605     }
1606 
1607     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
1608         return ERROR_CODE_COMMAND_DISALLOWED;
1609     }
1610 
1611     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO){
1612         return ERROR_CODE_COMMAND_DISALLOWED;
1613     }
1614     if (has_codec_negotiation_feature(hfp_connection)) {
1615         switch (hfp_connection->codecs_state) {
1616             case HFP_CODECS_W4_AG_COMMON_CODEC:
1617                 break;
1618             case HFP_CODECS_EXCHANGED:
1619                 hfp_connection->trigger_codec_exchange = 1;
1620                 break;
1621             default:
1622                 hfp_connection->codec_confirmed = 0;
1623                 hfp_connection->suggested_codec = 0;
1624                 hfp_connection->negotiated_codec = 0;
1625                 hfp_connection->codecs_state = HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE;
1626                 hfp_connection->trigger_codec_exchange = 1;
1627                 break;
1628         }
1629     } else {
1630         log_info("no codec negotiation feature, use CVSD");
1631         hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
1632         hfp_connection->suggested_codec = HFP_CODEC_CVSD;
1633         hfp_connection->codec_confirmed = hfp_connection->suggested_codec;
1634         hfp_connection->negotiated_codec = hfp_connection->suggested_codec;
1635         hfp_init_link_settings(hfp_connection, hfp_hf_esco_s4_supported(hfp_connection));
1636         hfp_connection->establish_audio_connection = 1;
1637         hfp_connection->state = HFP_W4_SCO_CONNECTED;
1638     }
1639 
1640     hfp_hf_run_for_context(hfp_connection);
1641     return ERROR_CODE_SUCCESS;
1642 }
1643 
1644 uint8_t hfp_hf_release_audio_connection(hci_con_handle_t acl_handle){
1645     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1646     if (!hfp_connection) {
1647         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1648     }
1649     if (hfp_connection->vra_state == HFP_VRA_VOICE_RECOGNITION_ACTIVATED){
1650         return ERROR_CODE_COMMAND_DISALLOWED;
1651     }
1652     uint8_t status = hfp_trigger_release_audio_connection(hfp_connection);
1653     if (status == ERROR_CODE_SUCCESS){
1654         hfp_hf_run_for_context(hfp_connection);
1655     }
1656     return ERROR_CODE_SUCCESS;
1657 }
1658 
1659 uint8_t hfp_hf_answer_incoming_call(hci_con_handle_t acl_handle){
1660     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1661     if (!hfp_connection) {
1662         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1663     }
1664 
1665     if (hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
1666         hfp_connection->hf_answer_incoming_call = 1;
1667         hfp_hf_run_for_context(hfp_connection);
1668     } else {
1669         log_error("HFP HF: answering incoming call with wrong callsetup status %u", hfp_hf_callsetup_status);
1670         return ERROR_CODE_COMMAND_DISALLOWED;
1671     }
1672     return ERROR_CODE_SUCCESS;
1673 }
1674 
1675 uint8_t hfp_hf_terminate_call(hci_con_handle_t acl_handle){
1676     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1677     if (!hfp_connection) {
1678         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1679     }
1680     hfp_connection->hf_send_chup = 1;
1681     hfp_hf_run_for_context(hfp_connection);
1682     return ERROR_CODE_SUCCESS;
1683 }
1684 
1685 uint8_t hfp_hf_reject_incoming_call(hci_con_handle_t acl_handle){
1686     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1687     if (!hfp_connection) {
1688         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1689     }
1690 
1691     if (hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
1692         hfp_connection->hf_send_chup = 1;
1693         hfp_hf_run_for_context(hfp_connection);
1694     }
1695     return ERROR_CODE_SUCCESS;
1696 }
1697 
1698 uint8_t hfp_hf_user_busy(hci_con_handle_t acl_handle){
1699     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1700     if (!hfp_connection) {
1701         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1702     }
1703 
1704     if (hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
1705         hfp_connection->hf_send_chld_0 = 1;
1706         hfp_hf_run_for_context(hfp_connection);
1707     }
1708     return ERROR_CODE_SUCCESS;
1709 }
1710 
1711 uint8_t hfp_hf_end_active_and_accept_other(hci_con_handle_t acl_handle){
1712     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1713     if (!hfp_connection) {
1714         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1715     }
1716 
1717     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1718         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1719         hfp_connection->hf_send_chld_1 = 1;
1720         hfp_hf_run_for_context(hfp_connection);
1721     }
1722     return ERROR_CODE_SUCCESS;
1723 }
1724 
1725 uint8_t hfp_hf_swap_calls(hci_con_handle_t acl_handle){
1726     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1727     if (!hfp_connection) {
1728         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1729     }
1730 
1731     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1732         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1733         hfp_connection->hf_send_chld_2 = 1;
1734         hfp_hf_run_for_context(hfp_connection);
1735     }
1736     return ERROR_CODE_SUCCESS;
1737 }
1738 
1739 uint8_t hfp_hf_join_held_call(hci_con_handle_t acl_handle){
1740     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1741     if (!hfp_connection) {
1742         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1743     }
1744 
1745     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1746         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1747         hfp_connection->hf_send_chld_3 = 1;
1748         hfp_hf_run_for_context(hfp_connection);
1749     }
1750     return ERROR_CODE_SUCCESS;
1751 }
1752 
1753 uint8_t hfp_hf_connect_calls(hci_con_handle_t acl_handle){
1754     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1755     if (!hfp_connection) {
1756         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1757     }
1758 
1759     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1760         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1761         hfp_connection->hf_send_chld_4 = 1;
1762         hfp_hf_run_for_context(hfp_connection);
1763     }
1764     return ERROR_CODE_SUCCESS;
1765 }
1766 
1767 uint8_t hfp_hf_release_call_with_index(hci_con_handle_t acl_handle, int index){
1768     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1769     if (!hfp_connection) {
1770         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1771     }
1772 
1773     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1774         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1775         hfp_connection->hf_send_chld_x = 1;
1776         hfp_connection->hf_send_chld_x_index = 10 + index;
1777         hfp_hf_run_for_context(hfp_connection);
1778     }
1779     return ERROR_CODE_SUCCESS;
1780 }
1781 
1782 uint8_t hfp_hf_private_consultation_with_call(hci_con_handle_t acl_handle, int index){
1783     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1784     if (!hfp_connection) {
1785         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1786     }
1787 
1788     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1789         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1790         hfp_connection->hf_send_chld_x = 1;
1791         hfp_connection->hf_send_chld_x_index = 20 + index;
1792         hfp_hf_run_for_context(hfp_connection);
1793     }
1794     return ERROR_CODE_SUCCESS;
1795 }
1796 
1797 uint8_t hfp_hf_dial_number(hci_con_handle_t acl_handle, char * number){
1798     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1799     if (!hfp_connection) {
1800         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1801     }
1802 
1803     hfp_connection->hf_initiate_outgoing_call = 1;
1804     snprintf(hfp_hf_phone_number, sizeof(hfp_hf_phone_number), "%s", number);
1805     hfp_hf_run_for_context(hfp_connection);
1806     return ERROR_CODE_SUCCESS;
1807 }
1808 
1809 uint8_t hfp_hf_dial_memory(hci_con_handle_t acl_handle, int memory_id){
1810     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1811     if (!hfp_connection) {
1812         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1813     }
1814 
1815     hfp_connection->hf_initiate_memory_dialing = 1;
1816     hfp_connection->memory_id = memory_id;
1817 
1818     hfp_hf_run_for_context(hfp_connection);
1819     return ERROR_CODE_SUCCESS;
1820 }
1821 
1822 uint8_t hfp_hf_redial_last_number(hci_con_handle_t acl_handle){
1823     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1824     if (!hfp_connection) {
1825         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1826     }
1827 
1828     hfp_connection->hf_initiate_redial_last_number = 1;
1829     hfp_hf_run_for_context(hfp_connection);
1830     return ERROR_CODE_SUCCESS;
1831 }
1832 
1833 uint8_t hfp_hf_activate_call_waiting_notification(hci_con_handle_t acl_handle){
1834     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1835     if (!hfp_connection) {
1836         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1837     }
1838 
1839     hfp_connection->hf_activate_call_waiting_notification = 1;
1840     hfp_hf_run_for_context(hfp_connection);
1841     return ERROR_CODE_SUCCESS;
1842 }
1843 
1844 
1845 uint8_t hfp_hf_deactivate_call_waiting_notification(hci_con_handle_t acl_handle){
1846     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1847     if (!hfp_connection) {
1848         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1849     }
1850 
1851     hfp_connection->hf_deactivate_call_waiting_notification = 1;
1852     hfp_hf_run_for_context(hfp_connection);
1853     return ERROR_CODE_SUCCESS;
1854 }
1855 
1856 
1857 uint8_t hfp_hf_activate_calling_line_notification(hci_con_handle_t acl_handle){
1858     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1859     if (!hfp_connection) {
1860         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1861     }
1862 
1863     hfp_connection->hf_activate_calling_line_notification = 1;
1864     hfp_hf_run_for_context(hfp_connection);
1865     return ERROR_CODE_SUCCESS;
1866 }
1867 
1868 uint8_t hfp_hf_deactivate_calling_line_notification(hci_con_handle_t acl_handle){
1869     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1870     if (!hfp_connection) {
1871         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1872     }
1873 
1874     hfp_connection->hf_deactivate_calling_line_notification = 1;
1875     hfp_hf_run_for_context(hfp_connection);
1876     return ERROR_CODE_SUCCESS;
1877 }
1878 
1879 static bool hfp_hf_echo_canceling_and_noise_reduction_supported(hfp_connection_t * hfp_connection){
1880     int ag = get_bit(hfp_connection->remote_supported_features, HFP_AGSF_EC_NR_FUNCTION);
1881     int hf = get_bit(hfp_hf_supported_features, HFP_HFSF_EC_NR_FUNCTION);
1882     return hf && ag;
1883 }
1884 
1885 uint8_t hfp_hf_deactivate_echo_canceling_and_noise_reduction(hci_con_handle_t acl_handle){
1886     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1887     if (!hfp_connection) {
1888         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1889     }
1890     if (!hfp_hf_echo_canceling_and_noise_reduction_supported(hfp_connection)){
1891         return ERROR_CODE_COMMAND_DISALLOWED;
1892     }
1893 
1894     hfp_connection->hf_deactivate_echo_canceling_and_noise_reduction = 1;
1895     hfp_hf_run_for_context(hfp_connection);
1896     return ERROR_CODE_SUCCESS;
1897 }
1898 
1899 uint8_t hfp_hf_activate_voice_recognition(hci_con_handle_t acl_handle){
1900      hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1901     if (!hfp_connection) {
1902         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1903     }
1904     if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED || hfp_connection->state > HFP_AUDIO_CONNECTION_ESTABLISHED){
1905         return ERROR_CODE_COMMAND_DISALLOWED;
1906     }
1907 
1908     bool enhanced_vra_supported = hfp_hf_enhanced_vra_flag_supported(hfp_connection);
1909     bool legacy_vra_supported   = hfp_hf_vra_flag_supported(hfp_connection);
1910     if (!enhanced_vra_supported && !legacy_vra_supported){
1911         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1912     }
1913 
1914     switch (hfp_connection->vra_state){
1915         case HFP_VRA_VOICE_RECOGNITION_OFF:
1916         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF:
1917             hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED;
1918             hfp_connection->enhanced_voice_recognition_enabled = enhanced_vra_supported;
1919             break;
1920         case HFP_VRA_W4_VOICE_RECOGNITION_OFF:
1921             hfp_connection->activate_voice_recognition = true;
1922             break;
1923         default:
1924             return ERROR_CODE_COMMAND_DISALLOWED;
1925     }
1926 
1927     hfp_hf_run_for_context(hfp_connection);
1928     return ERROR_CODE_SUCCESS;
1929 }
1930 
1931 uint8_t hfp_hf_enhanced_voice_recognition_report_ready_for_audio(hci_con_handle_t acl_handle){
1932     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1933     if (!hfp_connection) {
1934         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1935     }
1936 
1937     if (hfp_connection->emit_vra_enabled_after_audio_established){
1938         return ERROR_CODE_COMMAND_DISALLOWED;
1939     }
1940 
1941     if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED){
1942         return ERROR_CODE_COMMAND_DISALLOWED;
1943     }
1944 
1945     bool enhanced_vra_supported = hfp_hf_enhanced_vra_flag_supported(hfp_connection);
1946     if (!enhanced_vra_supported){
1947         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1948     }
1949 
1950     switch (hfp_connection->vra_state){
1951         case HFP_VRA_VOICE_RECOGNITION_ACTIVATED:
1952         case HFP_VRA_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1953             hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO;
1954             break;
1955         default:
1956             return ERROR_CODE_COMMAND_DISALLOWED;
1957     }
1958 
1959     hfp_hf_run_for_context(hfp_connection);
1960     return ERROR_CODE_SUCCESS;
1961 }
1962 
1963 
1964 uint8_t hfp_hf_deactivate_voice_recognition(hci_con_handle_t acl_handle){
1965     // return deactivate_voice_recognition(acl_handle, false);
1966     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1967     if (!hfp_connection) {
1968         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1969     }
1970 
1971     if (hfp_connection->emit_vra_enabled_after_audio_established){
1972         return ERROR_CODE_COMMAND_DISALLOWED;
1973     }
1974 
1975     if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED ||
1976         hfp_connection->state > HFP_AUDIO_CONNECTION_ESTABLISHED){
1977         return ERROR_CODE_COMMAND_DISALLOWED;
1978     }
1979 
1980     bool enhanced_vra_supported = hfp_hf_enhanced_vra_flag_supported(hfp_connection);
1981     bool legacy_vra_supported   = hfp_hf_vra_flag_supported(hfp_connection);
1982     if (!enhanced_vra_supported && !legacy_vra_supported){
1983         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1984     }
1985 
1986     switch (hfp_connection->vra_state){
1987         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED:
1988         case HFP_VRA_VOICE_RECOGNITION_ACTIVATED:
1989         case HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1990         case HFP_VRA_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1991             hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF;
1992             break;
1993 
1994         case HFP_VRA_W4_VOICE_RECOGNITION_ACTIVATED:
1995         case HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1996             hfp_connection->deactivate_voice_recognition = true;
1997             break;
1998 
1999         case HFP_VRA_VOICE_RECOGNITION_OFF:
2000         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF:
2001         case HFP_VRA_W4_VOICE_RECOGNITION_OFF:
2002         default:
2003             return ERROR_CODE_COMMAND_DISALLOWED;
2004     }
2005 
2006     hfp_hf_run_for_context(hfp_connection);
2007     return ERROR_CODE_SUCCESS;
2008 }
2009 
2010 uint8_t hfp_hf_set_microphone_gain(hci_con_handle_t acl_handle, int gain){
2011     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2012     if (!hfp_connection) {
2013         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2014     }
2015 
2016     if (hfp_connection->microphone_gain == gain) {
2017         return ERROR_CODE_SUCCESS;
2018     }
2019 
2020     if ((gain < 0) || (gain > 15)){
2021         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
2022         return ERROR_CODE_COMMAND_DISALLOWED;
2023     }
2024 
2025     hfp_connection->microphone_gain = gain;
2026     hfp_connection->send_microphone_gain = 1;
2027     hfp_hf_run_for_context(hfp_connection);
2028     return ERROR_CODE_SUCCESS;
2029 }
2030 
2031 uint8_t hfp_hf_set_speaker_gain(hci_con_handle_t acl_handle, int gain){
2032     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2033     if (!hfp_connection) {
2034         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2035     }
2036 
2037     if (hfp_connection->speaker_gain == gain){
2038         return ERROR_CODE_SUCCESS;
2039     }
2040 
2041     if ((gain < 0) || (gain > 15)){
2042         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
2043         return ERROR_CODE_COMMAND_DISALLOWED;
2044     }
2045 
2046     hfp_connection->speaker_gain = gain;
2047     hfp_connection->send_speaker_gain = 1;
2048     hfp_hf_run_for_context(hfp_connection);
2049     return ERROR_CODE_SUCCESS;
2050 }
2051 
2052 uint8_t hfp_hf_send_dtmf_code(hci_con_handle_t acl_handle, char code){
2053     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2054     if (!hfp_connection) {
2055         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2056     }
2057     hfp_connection->hf_send_dtmf_code = code;
2058     hfp_hf_run_for_context(hfp_connection);
2059     return ERROR_CODE_SUCCESS;
2060 }
2061 
2062 uint8_t hfp_hf_request_phone_number_for_voice_tag(hci_con_handle_t acl_handle){
2063     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2064     if (!hfp_connection) {
2065         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2066     }
2067     hfp_connection->hf_send_binp = 1;
2068     hfp_hf_run_for_context(hfp_connection);
2069     return ERROR_CODE_SUCCESS;
2070 }
2071 
2072 uint8_t hfp_hf_query_current_call_status(hci_con_handle_t acl_handle){
2073     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2074     if (!hfp_connection) {
2075         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2076     }
2077     hfp_connection->hf_send_clcc = 1;
2078     hfp_hf_run_for_context(hfp_connection);
2079     return ERROR_CODE_SUCCESS;
2080 }
2081 
2082 
2083 uint8_t hfp_hf_rrh_query_status(hci_con_handle_t acl_handle){
2084     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2085     if (!hfp_connection) {
2086         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2087     }
2088     hfp_connection->hf_send_rrh = 1;
2089     hfp_connection->hf_send_rrh_command = '?';
2090     hfp_hf_run_for_context(hfp_connection);
2091     return ERROR_CODE_SUCCESS;
2092 }
2093 
2094 uint8_t hfp_hf_rrh_hold_call(hci_con_handle_t acl_handle){
2095     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2096     if (!hfp_connection) {
2097         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2098     }
2099     hfp_connection->hf_send_rrh = 1;
2100     hfp_connection->hf_send_rrh_command = '0';
2101     hfp_hf_run_for_context(hfp_connection);
2102     return ERROR_CODE_SUCCESS;
2103 }
2104 
2105 uint8_t hfp_hf_rrh_accept_held_call(hci_con_handle_t acl_handle){
2106     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2107     if (!hfp_connection) {
2108         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2109     }
2110     hfp_connection->hf_send_rrh = 1;
2111     hfp_connection->hf_send_rrh_command = '1';
2112     hfp_hf_run_for_context(hfp_connection);
2113     return ERROR_CODE_SUCCESS;
2114 }
2115 
2116 uint8_t hfp_hf_rrh_reject_held_call(hci_con_handle_t acl_handle){
2117     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2118     if (!hfp_connection) {
2119         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2120     }
2121     hfp_connection->hf_send_rrh = 1;
2122     hfp_connection->hf_send_rrh_command = '2';
2123     hfp_hf_run_for_context(hfp_connection);
2124     return ERROR_CODE_SUCCESS;
2125 }
2126 
2127 uint8_t hfp_hf_query_subscriber_number(hci_con_handle_t acl_handle){
2128     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2129     if (!hfp_connection) {
2130         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2131     }
2132     hfp_connection->hf_send_cnum = 1;
2133     hfp_hf_run_for_context(hfp_connection);
2134     return ERROR_CODE_SUCCESS;
2135 }
2136 
2137 uint8_t hfp_hf_set_hf_indicator(hci_con_handle_t acl_handle, int assigned_number, int value){
2138     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2139     if (!hfp_connection) {
2140         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2141     }
2142     // find index for assigned number
2143     int i;
2144     for (i = 0; i < hfp_hf_indicators_nr ; i++){
2145         if (hfp_hf_indicators[i] == assigned_number){
2146             // set value
2147             hfp_hf_indicators_value[i] = value;
2148             // mark for update
2149             if (hfp_connection->state > HFP_LIST_GENERIC_STATUS_INDICATORS){
2150                 hfp_connection->generic_status_update_bitmap |= (1<<i);
2151                 // send update
2152                 hfp_hf_run_for_context(hfp_connection);
2153             }
2154             return ERROR_CODE_SUCCESS;
2155         }
2156     }
2157     return ERROR_CODE_SUCCESS;
2158 }
2159 
2160 int hfp_hf_in_band_ringtone_active(hci_con_handle_t acl_handle){
2161     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2162     if (!hfp_connection) {
2163         return 0;
2164     }
2165     return get_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE);
2166 }
2167 
2168 void hfp_hf_create_sdp_record(uint8_t * service, uint32_t service_record_handle, int rfcomm_channel_nr, const char * name, uint16_t supported_features, int wide_band_speech){
2169 	if (!name){
2170 		name = hfp_hf_default_service_name;
2171 	}
2172 	hfp_create_sdp_record(service, service_record_handle, BLUETOOTH_SERVICE_CLASS_HANDSFREE, rfcomm_channel_nr, name);
2173 
2174 	// Construct SupportedFeatures for SDP bitmap:
2175 	//
2176 	// "The values of the “SupportedFeatures” bitmap given in Table 5.4 shall be the same as the values
2177 	//  of the Bits 0 to 4 of the unsolicited result code +BRSF"
2178 	//
2179 	// Wide band speech (bit 5) requires Codec negotiation
2180 	//
2181 	uint16_t sdp_features = supported_features & 0x1f;
2182 	if ( (wide_band_speech != 0) && (supported_features & (1 << HFP_HFSF_CODEC_NEGOTIATION))){
2183 		sdp_features |= 1 << 5;
2184 	}
2185 
2186     if (supported_features & (1 << HFP_HFSF_ENHANCED_VOICE_RECOGNITION_STATUS)){
2187         sdp_features |= 1 << 6;
2188     }
2189 
2190     if (supported_features & (1 << HFP_HFSF_VOICE_RECOGNITION_TEXT)){
2191         sdp_features |= 1 << 7;
2192     }
2193 
2194 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);    // Hands-Free Profile - SupportedFeatures
2195 	de_add_number(service, DE_UINT, DE_SIZE_16, sdp_features);
2196 }
2197 
2198 void hfp_hf_register_packet_handler(btstack_packet_handler_t callback){
2199 	btstack_assert(callback != NULL);
2200 
2201 	hfp_hf_callback = callback;
2202 	hfp_set_hf_callback(callback);
2203 }
2204