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