xref: /btstack/src/classic/hfp_hf.c (revision 016a59df11d7afd92296950c186211ac1944bc95)
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->local_role, 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     // last argument is still in line_buffer
1273 
1274     switch (hfp_connection->command){
1275         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1276             hfp_connection->command = HFP_CMD_NONE;
1277             hfp_hf_emit_subscriber_information(hfp_connection, 0);
1278             break;
1279         case HFP_CMD_RESPONSE_AND_HOLD_STATUS:
1280             hfp_connection->command = HFP_CMD_NONE;
1281             hfp_emit_event(hfp_connection, HFP_SUBEVENT_RESPONSE_AND_HOLD_STATUS, btstack_atoi((char *)&hfp_connection->line_buffer[0]));
1282             break;
1283         case HFP_CMD_LIST_CURRENT_CALLS:
1284             hfp_connection->command = HFP_CMD_NONE;
1285             hfp_hf_emit_enhanced_call_status(hfp_connection);
1286             break;
1287         case HFP_CMD_SET_SPEAKER_GAIN:
1288             hfp_connection->command = HFP_CMD_NONE;
1289             value = btstack_atoi((char*)hfp_connection->line_buffer);
1290             hfp_hf_speaker_gain = value;
1291             hfp_emit_event(hfp_connection, HFP_SUBEVENT_SPEAKER_VOLUME, value);
1292             break;
1293         case HFP_CMD_SET_MICROPHONE_GAIN:
1294             hfp_connection->command = HFP_CMD_NONE;
1295             value = btstack_atoi((char*)hfp_connection->line_buffer);
1296             hfp_hf_microphone_gain = value;
1297             hfp_emit_event(hfp_connection, HFP_SUBEVENT_MICROPHONE_VOLUME, value);
1298             break;
1299         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1300             hfp_connection->command = HFP_CMD_NONE;
1301             hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_NUMBER_FOR_VOICE_TAG, hfp_connection->bnip_number);
1302             break;
1303         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1304             hfp_connection->command = HFP_CMD_NONE;
1305             hfp_hf_emit_type_and_number(hfp_connection, HFP_SUBEVENT_CALL_WAITING_NOTIFICATION);
1306             break;
1307         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1308             hfp_connection->command = HFP_CMD_NONE;
1309             hfp_hf_emit_type_and_number(hfp_connection, HFP_SUBEVENT_CALLING_LINE_IDENTIFICATION_NOTIFICATION);
1310             break;
1311         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1312             hfp_connection->command = HFP_CMD_NONE;
1313             hfp_connection->ok_pending = 0;
1314             hfp_connection->extended_audio_gateway_error = 0;
1315             hfp_emit_event(hfp_connection, HFP_SUBEVENT_EXTENDED_AUDIO_GATEWAY_ERROR, hfp_connection->extended_audio_gateway_error_value);
1316             break;
1317         case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1318             break;
1319         case HFP_CMD_ERROR:
1320             switch (hfp_connection->state){
1321                 case HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED:
1322                     switch (hfp_connection->codecs_state){
1323                         case HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE:
1324                             hfp_reset_context_flags(hfp_connection);
1325                             hfp_emit_sco_event(hfp_connection, HFP_REMOTE_REJECTS_AUDIO_CONNECTION, 0, hfp_connection->remote_addr, hfp_connection->negotiated_codec);
1326                             return;
1327                         default:
1328                             break;
1329                     }
1330                     break;
1331                 default:
1332                     break;
1333             }
1334 
1335             // handle error response for voice activation (HF initiated)
1336             switch(hfp_connection->vra_state_requested){
1337                 case HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1338                     hfp_emit_enhanced_voice_recognition_hf_ready_for_audio_event(hfp_connection, ERROR_CODE_UNSPECIFIED_ERROR);
1339                     break;
1340                 default:
1341                     if (hfp_connection->vra_state_requested == hfp_connection->vra_state){
1342                         break;
1343                     }
1344                     hfp_connection->vra_state_requested = hfp_connection->vra_state;
1345                     hfp_emit_voice_recognition_enabled(hfp_connection, ERROR_CODE_UNSPECIFIED_ERROR);
1346                     hfp_reset_context_flags(hfp_connection);
1347                     return;
1348             }
1349             event_emited = hfp_hf_switch_on_ok_pending(hfp_connection, ERROR_CODE_UNSPECIFIED_ERROR);
1350             if (!event_emited){
1351                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_COMPLETE, 1);
1352             }
1353             hfp_reset_context_flags(hfp_connection);
1354             break;
1355 
1356         case HFP_CMD_OK:
1357             hfp_hf_switch_on_ok_pending(hfp_connection, ERROR_CODE_SUCCESS);
1358             break;
1359         case HFP_CMD_RING:
1360             hfp_connection->command = HFP_CMD_NONE;
1361             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_RING);
1362             break;
1363         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1364             hfp_connection->command = HFP_CMD_NONE;
1365             hfp_hf_handle_transfer_ag_indicator_status(hfp_connection);
1366             break;
1367         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1368             hfp_connection->command = HFP_CMD_NONE;
1369             // report status after SLC established
1370             if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
1371                 break;
1372             }
1373             for (i = 0; i < hfp_connection->ag_indicators_nr; i++){
1374                 hfp_emit_ag_indicator_mapping_event(hfp_connection, &hfp_connection->ag_indicators[i]);
1375             }
1376             break;
1377     	case HFP_CMD_AG_SUGGESTED_CODEC:
1378             hfp_connection->command = HFP_CMD_NONE;
1379     		hfp_hf_handle_suggested_codec(hfp_connection);
1380 			break;
1381         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1382             hfp_emit_event(hfp_connection, HFP_SUBEVENT_IN_BAND_RING_TONE, get_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE));
1383         default:
1384             break;
1385     }
1386 }
1387 
1388 static int hfp_parser_is_end_of_line(uint8_t byte){
1389 	return (byte == '\n') || (byte == '\r');
1390 }
1391 
1392 static void hfp_hf_handle_rfcomm_data(hfp_connection_t * hfp_connection, uint8_t *packet, uint16_t size){
1393     // assertion: size >= 1 as rfcomm.c does not deliver empty packets
1394     if (size < 1) return;
1395 
1396     hfp_log_rfcomm_message("HFP_HF_RX", packet, size);
1397 #ifdef ENABLE_HFP_AT_MESSAGES
1398     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_RECEIVED, (char *) packet);
1399 #endif
1400 
1401     // process messages byte-wise
1402     uint8_t pos;
1403     for (pos = 0; pos < size; pos++){
1404         hfp_parse(hfp_connection, packet[pos], 1);
1405         // parse until end of line "\r" or "\n"
1406         if (!hfp_parser_is_end_of_line(packet[pos])) continue;
1407         hfp_hf_handle_rfcomm_command(hfp_connection);
1408     }
1409 }
1410 
1411 static void hfp_hf_run(void){
1412     btstack_linked_list_iterator_t it;
1413     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1414     while (btstack_linked_list_iterator_has_next(&it)){
1415         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1416         if (hfp_connection->local_role != HFP_ROLE_HF) continue;
1417         hfp_hf_run_for_context(hfp_connection);
1418     }
1419 }
1420 
1421 static void hfp_hf_rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1422     hfp_connection_t * hfp_connection;
1423     switch (packet_type){
1424         case RFCOMM_DATA_PACKET:
1425             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(channel);
1426             if (!hfp_connection) return;
1427             hfp_hf_handle_rfcomm_data(hfp_connection, packet, size);
1428             hfp_hf_run_for_context(hfp_connection);
1429             return;
1430         case HCI_EVENT_PACKET:
1431             if (packet[0] == RFCOMM_EVENT_CAN_SEND_NOW){
1432                 uint16_t rfcomm_cid = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
1433                 hfp_hf_run_for_context(get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid));
1434                 return;
1435             }
1436             hfp_handle_rfcomm_event(packet_type, channel, packet, size, HFP_ROLE_HF);
1437             break;
1438         default:
1439             break;
1440     }
1441     hfp_hf_run();
1442 }
1443 
1444 static void hfp_hf_hci_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1445     hfp_handle_hci_event(packet_type, channel, packet, size, HFP_ROLE_HF);
1446     hfp_hf_run();
1447 }
1448 
1449 static void hfp_hf_set_defaults(void){
1450     hfp_hf_supported_features = HFP_DEFAULT_HF_SUPPORTED_FEATURES;
1451     hfp_hf_call_status = HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS;
1452     hfp_hf_callsetup_status = HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1453     hfp_hf_callheld_status= HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1454     hfp_hf_codecs_nr = 0;
1455     hfp_hf_speaker_gain = 9;
1456     hfp_hf_microphone_gain = 9;
1457     hfp_hf_indicators_nr = 0;
1458 }
1459 
1460 uint8_t hfp_hf_init(uint16_t rfcomm_channel_nr){
1461     uint8_t status = rfcomm_register_service(hfp_hf_rfcomm_packet_handler, rfcomm_channel_nr, 0xffff);
1462     if (status != ERROR_CODE_SUCCESS){
1463         return status;
1464     }
1465 
1466     hfp_init();
1467     hfp_hf_set_defaults();
1468 
1469     hfp_hf_hci_event_callback_registration.callback = &hfp_hf_hci_event_packet_handler;
1470     hci_add_event_handler(&hfp_hf_hci_event_callback_registration);
1471 
1472     // used to set packet handler for outgoing rfcomm connections - could be handled by emitting an event to us
1473     hfp_set_hf_rfcomm_packet_handler(&hfp_hf_rfcomm_packet_handler);
1474     return ERROR_CODE_SUCCESS;
1475 }
1476 
1477 void hfp_hf_deinit(void){
1478     hfp_deinit();
1479     hfp_hf_set_defaults();
1480 
1481     hfp_hf_callback = NULL;
1482     (void) memset(&hfp_hf_hci_event_callback_registration, 0, sizeof(btstack_packet_callback_registration_t));
1483     (void) memset(hfp_hf_phone_number, 0, sizeof(hfp_hf_phone_number));
1484 }
1485 
1486 void hfp_hf_init_codecs(int codecs_nr, const uint8_t * codecs){
1487     btstack_assert(codecs_nr < HFP_MAX_NUM_CODECS);
1488 
1489     hfp_hf_codecs_nr = codecs_nr;
1490     int i;
1491     for (i=0; i<codecs_nr; i++){
1492         hfp_hf_codecs[i] = codecs[i];
1493     }
1494 }
1495 
1496 void hfp_hf_init_supported_features(uint32_t supported_features){
1497     hfp_hf_supported_features = supported_features;
1498 }
1499 
1500 void hfp_hf_init_hf_indicators(int indicators_nr, const uint16_t * indicators){
1501     btstack_assert(hfp_hf_indicators_nr < HFP_MAX_NUM_INDICATORS);
1502 
1503     hfp_hf_indicators_nr = indicators_nr;
1504     int i;
1505     for (i = 0; i < hfp_hf_indicators_nr ; i++){
1506         hfp_hf_indicators[i] = indicators[i];
1507     }
1508 }
1509 
1510 uint8_t hfp_hf_establish_service_level_connection(bd_addr_t bd_addr){
1511     return hfp_establish_service_level_connection(bd_addr, BLUETOOTH_SERVICE_CLASS_HANDSFREE_AUDIO_GATEWAY, HFP_ROLE_HF);
1512 }
1513 
1514 uint8_t hfp_hf_release_service_level_connection(hci_con_handle_t acl_handle){
1515     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1516     if (!hfp_connection){
1517         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1518     }
1519     hfp_trigger_release_service_level_connection(hfp_connection);
1520     hfp_hf_run_for_context(hfp_connection);
1521     return ERROR_CODE_SUCCESS;
1522 }
1523 
1524 static uint8_t hfp_hf_set_status_update_for_all_ag_indicators(hci_con_handle_t acl_handle, uint8_t enable){
1525     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1526     if (!hfp_connection) {
1527         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1528     }
1529     hfp_connection->enable_status_update_for_ag_indicators = enable;
1530     hfp_hf_run_for_context(hfp_connection);
1531     return ERROR_CODE_SUCCESS;
1532 }
1533 
1534 uint8_t hfp_hf_enable_status_update_for_all_ag_indicators(hci_con_handle_t acl_handle){
1535     return hfp_hf_set_status_update_for_all_ag_indicators(acl_handle, 1);
1536 }
1537 
1538 uint8_t hfp_hf_disable_status_update_for_all_ag_indicators(hci_con_handle_t acl_handle){
1539     return hfp_hf_set_status_update_for_all_ag_indicators(acl_handle, 0);
1540 }
1541 
1542 // TODO: returned ERROR - wrong format
1543 uint8_t hfp_hf_set_status_update_for_individual_ag_indicators(hci_con_handle_t acl_handle, uint32_t indicators_status_bitmap){
1544     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1545     if (!hfp_connection) {
1546         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1547     }
1548     hfp_connection->change_status_update_for_individual_ag_indicators = 1;
1549     hfp_connection->ag_indicators_status_update_bitmap = indicators_status_bitmap;
1550     hfp_hf_run_for_context(hfp_connection);
1551     return ERROR_CODE_SUCCESS;
1552 }
1553 
1554 uint8_t hfp_hf_query_operator_selection(hci_con_handle_t acl_handle){
1555     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1556     if (!hfp_connection) {
1557         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1558     }
1559 
1560     switch (hfp_connection->hf_query_operator_state){
1561         case HFP_HF_QUERY_OPERATOR_FORMAT_NOT_SET:
1562             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_SET_FORMAT;
1563             break;
1564         case HFP_HF_QUERY_OPERATOR_FORMAT_SET:
1565             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_SEND_QUERY;
1566             break;
1567         default:
1568             return ERROR_CODE_COMMAND_DISALLOWED;
1569     }
1570     hfp_hf_run_for_context(hfp_connection);
1571     return ERROR_CODE_SUCCESS;
1572 }
1573 
1574 static uint8_t hfp_hf_set_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle, uint8_t enable){
1575     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1576     if (!hfp_connection) {
1577         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1578     }
1579     hfp_connection->enable_extended_audio_gateway_error_report = enable;
1580     hfp_hf_run_for_context(hfp_connection);
1581     return ERROR_CODE_SUCCESS;
1582 }
1583 
1584 
1585 uint8_t hfp_hf_enable_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle){
1586     return hfp_hf_set_report_extended_audio_gateway_error_result_code(acl_handle, 1);
1587 }
1588 
1589 uint8_t hfp_hf_disable_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle){
1590     return hfp_hf_set_report_extended_audio_gateway_error_result_code(acl_handle, 0);
1591 }
1592 
1593 static uint8_t hfp_hf_esco_s4_supported(hfp_connection_t * hfp_connection){
1594     return (hfp_connection->remote_supported_features & (1<<HFP_AGSF_ESCO_S4)) &&  (hfp_hf_supported_features & (1 << HFP_HFSF_ESCO_S4));
1595 }
1596 
1597 uint8_t hfp_hf_establish_audio_connection(hci_con_handle_t acl_handle){
1598     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1599     if (!hfp_connection) {
1600         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1601     }
1602 
1603     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
1604         return ERROR_CODE_COMMAND_DISALLOWED;
1605     }
1606 
1607     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO){
1608         return ERROR_CODE_COMMAND_DISALLOWED;
1609     }
1610     if (has_codec_negotiation_feature(hfp_connection)) {
1611         switch (hfp_connection->codecs_state) {
1612             case HFP_CODECS_W4_AG_COMMON_CODEC:
1613                 break;
1614             case HFP_CODECS_EXCHANGED:
1615                 hfp_connection->trigger_codec_exchange = 1;
1616                 break;
1617             default:
1618                 hfp_connection->codec_confirmed = 0;
1619                 hfp_connection->suggested_codec = 0;
1620                 hfp_connection->negotiated_codec = 0;
1621                 hfp_connection->codecs_state = HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE;
1622                 hfp_connection->trigger_codec_exchange = 1;
1623                 break;
1624         }
1625     } else {
1626         log_info("no codec negotiation feature, use CVSD");
1627         hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
1628         hfp_connection->suggested_codec = HFP_CODEC_CVSD;
1629         hfp_connection->codec_confirmed = hfp_connection->suggested_codec;
1630         hfp_connection->negotiated_codec = hfp_connection->suggested_codec;
1631         hfp_init_link_settings(hfp_connection, hfp_hf_esco_s4_supported(hfp_connection));
1632         hfp_connection->establish_audio_connection = 1;
1633         hfp_connection->state = HFP_W4_SCO_CONNECTED;
1634     }
1635 
1636     hfp_hf_run_for_context(hfp_connection);
1637     return ERROR_CODE_SUCCESS;
1638 }
1639 
1640 uint8_t hfp_hf_release_audio_connection(hci_con_handle_t acl_handle){
1641     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1642     if (!hfp_connection) {
1643         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1644     }
1645     if (hfp_connection->vra_state == HFP_VRA_VOICE_RECOGNITION_ACTIVATED){
1646         return ERROR_CODE_COMMAND_DISALLOWED;
1647     }
1648     uint8_t status = hfp_trigger_release_audio_connection(hfp_connection);
1649     if (status == ERROR_CODE_SUCCESS){
1650         hfp_hf_run_for_context(hfp_connection);
1651     }
1652     return ERROR_CODE_SUCCESS;
1653 }
1654 
1655 uint8_t hfp_hf_answer_incoming_call(hci_con_handle_t acl_handle){
1656     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1657     if (!hfp_connection) {
1658         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1659     }
1660 
1661     if (hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
1662         hfp_connection->hf_answer_incoming_call = 1;
1663         hfp_hf_run_for_context(hfp_connection);
1664     } else {
1665         log_error("HFP HF: answering incoming call with wrong callsetup status %u", hfp_hf_callsetup_status);
1666         return ERROR_CODE_COMMAND_DISALLOWED;
1667     }
1668     return ERROR_CODE_SUCCESS;
1669 }
1670 
1671 uint8_t hfp_hf_terminate_call(hci_con_handle_t acl_handle){
1672     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1673     if (!hfp_connection) {
1674         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1675     }
1676     hfp_connection->hf_send_chup = 1;
1677     hfp_hf_run_for_context(hfp_connection);
1678     return ERROR_CODE_SUCCESS;
1679 }
1680 
1681 uint8_t hfp_hf_reject_incoming_call(hci_con_handle_t acl_handle){
1682     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1683     if (!hfp_connection) {
1684         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1685     }
1686 
1687     if (hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
1688         hfp_connection->hf_send_chup = 1;
1689         hfp_hf_run_for_context(hfp_connection);
1690     }
1691     return ERROR_CODE_SUCCESS;
1692 }
1693 
1694 uint8_t hfp_hf_user_busy(hci_con_handle_t acl_handle){
1695     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1696     if (!hfp_connection) {
1697         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1698     }
1699 
1700     if (hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
1701         hfp_connection->hf_send_chld_0 = 1;
1702         hfp_hf_run_for_context(hfp_connection);
1703     }
1704     return ERROR_CODE_SUCCESS;
1705 }
1706 
1707 uint8_t hfp_hf_end_active_and_accept_other(hci_con_handle_t acl_handle){
1708     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1709     if (!hfp_connection) {
1710         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1711     }
1712 
1713     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1714         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1715         hfp_connection->hf_send_chld_1 = 1;
1716         hfp_hf_run_for_context(hfp_connection);
1717     }
1718     return ERROR_CODE_SUCCESS;
1719 }
1720 
1721 uint8_t hfp_hf_swap_calls(hci_con_handle_t acl_handle){
1722     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1723     if (!hfp_connection) {
1724         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1725     }
1726 
1727     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1728         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1729         hfp_connection->hf_send_chld_2 = 1;
1730         hfp_hf_run_for_context(hfp_connection);
1731     }
1732     return ERROR_CODE_SUCCESS;
1733 }
1734 
1735 uint8_t hfp_hf_join_held_call(hci_con_handle_t acl_handle){
1736     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1737     if (!hfp_connection) {
1738         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1739     }
1740 
1741     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1742         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1743         hfp_connection->hf_send_chld_3 = 1;
1744         hfp_hf_run_for_context(hfp_connection);
1745     }
1746     return ERROR_CODE_SUCCESS;
1747 }
1748 
1749 uint8_t hfp_hf_connect_calls(hci_con_handle_t acl_handle){
1750     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1751     if (!hfp_connection) {
1752         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1753     }
1754 
1755     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1756         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1757         hfp_connection->hf_send_chld_4 = 1;
1758         hfp_hf_run_for_context(hfp_connection);
1759     }
1760     return ERROR_CODE_SUCCESS;
1761 }
1762 
1763 uint8_t hfp_hf_release_call_with_index(hci_con_handle_t acl_handle, int index){
1764     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1765     if (!hfp_connection) {
1766         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1767     }
1768 
1769     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1770         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1771         hfp_connection->hf_send_chld_x = 1;
1772         hfp_connection->hf_send_chld_x_index = 10 + index;
1773         hfp_hf_run_for_context(hfp_connection);
1774     }
1775     return ERROR_CODE_SUCCESS;
1776 }
1777 
1778 uint8_t hfp_hf_private_consultation_with_call(hci_con_handle_t acl_handle, int index){
1779     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1780     if (!hfp_connection) {
1781         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1782     }
1783 
1784     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1785         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1786         hfp_connection->hf_send_chld_x = 1;
1787         hfp_connection->hf_send_chld_x_index = 20 + index;
1788         hfp_hf_run_for_context(hfp_connection);
1789     }
1790     return ERROR_CODE_SUCCESS;
1791 }
1792 
1793 uint8_t hfp_hf_dial_number(hci_con_handle_t acl_handle, char * number){
1794     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1795     if (!hfp_connection) {
1796         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1797     }
1798 
1799     hfp_connection->hf_initiate_outgoing_call = 1;
1800     snprintf(hfp_hf_phone_number, sizeof(hfp_hf_phone_number), "%s", number);
1801     hfp_hf_run_for_context(hfp_connection);
1802     return ERROR_CODE_SUCCESS;
1803 }
1804 
1805 uint8_t hfp_hf_dial_memory(hci_con_handle_t acl_handle, int memory_id){
1806     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1807     if (!hfp_connection) {
1808         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1809     }
1810 
1811     hfp_connection->hf_initiate_memory_dialing = 1;
1812     hfp_connection->memory_id = memory_id;
1813 
1814     hfp_hf_run_for_context(hfp_connection);
1815     return ERROR_CODE_SUCCESS;
1816 }
1817 
1818 uint8_t hfp_hf_redial_last_number(hci_con_handle_t acl_handle){
1819     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1820     if (!hfp_connection) {
1821         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1822     }
1823 
1824     hfp_connection->hf_initiate_redial_last_number = 1;
1825     hfp_hf_run_for_context(hfp_connection);
1826     return ERROR_CODE_SUCCESS;
1827 }
1828 
1829 uint8_t hfp_hf_activate_call_waiting_notification(hci_con_handle_t acl_handle){
1830     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1831     if (!hfp_connection) {
1832         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1833     }
1834 
1835     hfp_connection->hf_activate_call_waiting_notification = 1;
1836     hfp_hf_run_for_context(hfp_connection);
1837     return ERROR_CODE_SUCCESS;
1838 }
1839 
1840 
1841 uint8_t hfp_hf_deactivate_call_waiting_notification(hci_con_handle_t acl_handle){
1842     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1843     if (!hfp_connection) {
1844         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1845     }
1846 
1847     hfp_connection->hf_deactivate_call_waiting_notification = 1;
1848     hfp_hf_run_for_context(hfp_connection);
1849     return ERROR_CODE_SUCCESS;
1850 }
1851 
1852 
1853 uint8_t hfp_hf_activate_calling_line_notification(hci_con_handle_t acl_handle){
1854     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1855     if (!hfp_connection) {
1856         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1857     }
1858 
1859     hfp_connection->hf_activate_calling_line_notification = 1;
1860     hfp_hf_run_for_context(hfp_connection);
1861     return ERROR_CODE_SUCCESS;
1862 }
1863 
1864 uint8_t hfp_hf_deactivate_calling_line_notification(hci_con_handle_t acl_handle){
1865     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1866     if (!hfp_connection) {
1867         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1868     }
1869 
1870     hfp_connection->hf_deactivate_calling_line_notification = 1;
1871     hfp_hf_run_for_context(hfp_connection);
1872     return ERROR_CODE_SUCCESS;
1873 }
1874 
1875 static bool hfp_hf_echo_canceling_and_noise_reduction_supported(hfp_connection_t * hfp_connection){
1876     int ag = get_bit(hfp_connection->remote_supported_features, HFP_AGSF_EC_NR_FUNCTION);
1877     int hf = get_bit(hfp_hf_supported_features, HFP_HFSF_EC_NR_FUNCTION);
1878     return hf && ag;
1879 }
1880 
1881 uint8_t hfp_hf_deactivate_echo_canceling_and_noise_reduction(hci_con_handle_t acl_handle){
1882     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1883     if (!hfp_connection) {
1884         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1885     }
1886     if (!hfp_hf_echo_canceling_and_noise_reduction_supported(hfp_connection)){
1887         return ERROR_CODE_COMMAND_DISALLOWED;
1888     }
1889 
1890     hfp_connection->hf_deactivate_echo_canceling_and_noise_reduction = 1;
1891     hfp_hf_run_for_context(hfp_connection);
1892     return ERROR_CODE_SUCCESS;
1893 }
1894 
1895 uint8_t hfp_hf_activate_voice_recognition(hci_con_handle_t acl_handle){
1896      hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1897     if (!hfp_connection) {
1898         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1899     }
1900     if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED || hfp_connection->state > HFP_AUDIO_CONNECTION_ESTABLISHED){
1901         return ERROR_CODE_COMMAND_DISALLOWED;
1902     }
1903 
1904     bool enhanced_vra_supported = hfp_hf_enhanced_vra_flag_supported(hfp_connection);
1905     bool legacy_vra_supported   = hfp_hf_vra_flag_supported(hfp_connection);
1906     if (!enhanced_vra_supported && !legacy_vra_supported){
1907         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1908     }
1909 
1910     switch (hfp_connection->vra_state){
1911         case HFP_VRA_VOICE_RECOGNITION_OFF:
1912         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF:
1913             hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED;
1914             hfp_connection->enhanced_voice_recognition_enabled = enhanced_vra_supported;
1915             break;
1916         case HFP_VRA_W4_VOICE_RECOGNITION_OFF:
1917             hfp_connection->activate_voice_recognition = true;
1918             break;
1919         default:
1920             return ERROR_CODE_COMMAND_DISALLOWED;
1921     }
1922 
1923     hfp_hf_run_for_context(hfp_connection);
1924     return ERROR_CODE_SUCCESS;
1925 }
1926 
1927 uint8_t hfp_hf_enhanced_voice_recognition_report_ready_for_audio(hci_con_handle_t acl_handle){
1928     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1929     if (!hfp_connection) {
1930         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1931     }
1932 
1933     if (hfp_connection->emit_vra_enabled_after_audio_established){
1934         return ERROR_CODE_COMMAND_DISALLOWED;
1935     }
1936 
1937     if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED){
1938         return ERROR_CODE_COMMAND_DISALLOWED;
1939     }
1940 
1941     bool enhanced_vra_supported = hfp_hf_enhanced_vra_flag_supported(hfp_connection);
1942     if (!enhanced_vra_supported){
1943         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1944     }
1945 
1946     switch (hfp_connection->vra_state){
1947         case HFP_VRA_VOICE_RECOGNITION_ACTIVATED:
1948         case HFP_VRA_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1949             hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO;
1950             break;
1951         default:
1952             return ERROR_CODE_COMMAND_DISALLOWED;
1953     }
1954 
1955     hfp_hf_run_for_context(hfp_connection);
1956     return ERROR_CODE_SUCCESS;
1957 }
1958 
1959 
1960 uint8_t hfp_hf_deactivate_voice_recognition(hci_con_handle_t acl_handle){
1961     // return deactivate_voice_recognition(acl_handle, false);
1962     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1963     if (!hfp_connection) {
1964         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1965     }
1966 
1967     if (hfp_connection->emit_vra_enabled_after_audio_established){
1968         return ERROR_CODE_COMMAND_DISALLOWED;
1969     }
1970 
1971     if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED ||
1972         hfp_connection->state > HFP_AUDIO_CONNECTION_ESTABLISHED){
1973         return ERROR_CODE_COMMAND_DISALLOWED;
1974     }
1975 
1976     bool enhanced_vra_supported = hfp_hf_enhanced_vra_flag_supported(hfp_connection);
1977     bool legacy_vra_supported   = hfp_hf_vra_flag_supported(hfp_connection);
1978     if (!enhanced_vra_supported && !legacy_vra_supported){
1979         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1980     }
1981 
1982     switch (hfp_connection->vra_state){
1983         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED:
1984         case HFP_VRA_VOICE_RECOGNITION_ACTIVATED:
1985         case HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1986         case HFP_VRA_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1987             hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF;
1988             break;
1989 
1990         case HFP_VRA_W4_VOICE_RECOGNITION_ACTIVATED:
1991         case HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1992             hfp_connection->deactivate_voice_recognition = true;
1993             break;
1994 
1995         case HFP_VRA_VOICE_RECOGNITION_OFF:
1996         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF:
1997         case HFP_VRA_W4_VOICE_RECOGNITION_OFF:
1998         default:
1999             return ERROR_CODE_COMMAND_DISALLOWED;
2000     }
2001 
2002     hfp_hf_run_for_context(hfp_connection);
2003     return ERROR_CODE_SUCCESS;
2004 }
2005 
2006 uint8_t hfp_hf_set_microphone_gain(hci_con_handle_t acl_handle, int gain){
2007     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2008     if (!hfp_connection) {
2009         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2010     }
2011 
2012     if (hfp_connection->microphone_gain == gain) {
2013         return ERROR_CODE_SUCCESS;
2014     }
2015 
2016     if ((gain < 0) || (gain > 15)){
2017         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
2018         return ERROR_CODE_COMMAND_DISALLOWED;
2019     }
2020 
2021     hfp_connection->microphone_gain = gain;
2022     hfp_connection->send_microphone_gain = 1;
2023     hfp_hf_run_for_context(hfp_connection);
2024     return ERROR_CODE_SUCCESS;
2025 }
2026 
2027 uint8_t hfp_hf_set_speaker_gain(hci_con_handle_t acl_handle, int gain){
2028     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2029     if (!hfp_connection) {
2030         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2031     }
2032 
2033     if (hfp_connection->speaker_gain == gain){
2034         return ERROR_CODE_SUCCESS;
2035     }
2036 
2037     if ((gain < 0) || (gain > 15)){
2038         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
2039         return ERROR_CODE_COMMAND_DISALLOWED;
2040     }
2041 
2042     hfp_connection->speaker_gain = gain;
2043     hfp_connection->send_speaker_gain = 1;
2044     hfp_hf_run_for_context(hfp_connection);
2045     return ERROR_CODE_SUCCESS;
2046 }
2047 
2048 uint8_t hfp_hf_send_dtmf_code(hci_con_handle_t acl_handle, char code){
2049     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2050     if (!hfp_connection) {
2051         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2052     }
2053     hfp_connection->hf_send_dtmf_code = code;
2054     hfp_hf_run_for_context(hfp_connection);
2055     return ERROR_CODE_SUCCESS;
2056 }
2057 
2058 uint8_t hfp_hf_request_phone_number_for_voice_tag(hci_con_handle_t acl_handle){
2059     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2060     if (!hfp_connection) {
2061         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2062     }
2063     hfp_connection->hf_send_binp = 1;
2064     hfp_hf_run_for_context(hfp_connection);
2065     return ERROR_CODE_SUCCESS;
2066 }
2067 
2068 uint8_t hfp_hf_query_current_call_status(hci_con_handle_t acl_handle){
2069     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2070     if (!hfp_connection) {
2071         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2072     }
2073     hfp_connection->hf_send_clcc = 1;
2074     hfp_hf_run_for_context(hfp_connection);
2075     return ERROR_CODE_SUCCESS;
2076 }
2077 
2078 
2079 uint8_t hfp_hf_rrh_query_status(hci_con_handle_t acl_handle){
2080     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2081     if (!hfp_connection) {
2082         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2083     }
2084     hfp_connection->hf_send_rrh = 1;
2085     hfp_connection->hf_send_rrh_command = '?';
2086     hfp_hf_run_for_context(hfp_connection);
2087     return ERROR_CODE_SUCCESS;
2088 }
2089 
2090 uint8_t hfp_hf_rrh_hold_call(hci_con_handle_t acl_handle){
2091     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2092     if (!hfp_connection) {
2093         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2094     }
2095     hfp_connection->hf_send_rrh = 1;
2096     hfp_connection->hf_send_rrh_command = '0';
2097     hfp_hf_run_for_context(hfp_connection);
2098     return ERROR_CODE_SUCCESS;
2099 }
2100 
2101 uint8_t hfp_hf_rrh_accept_held_call(hci_con_handle_t acl_handle){
2102     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2103     if (!hfp_connection) {
2104         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2105     }
2106     hfp_connection->hf_send_rrh = 1;
2107     hfp_connection->hf_send_rrh_command = '1';
2108     hfp_hf_run_for_context(hfp_connection);
2109     return ERROR_CODE_SUCCESS;
2110 }
2111 
2112 uint8_t hfp_hf_rrh_reject_held_call(hci_con_handle_t acl_handle){
2113     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2114     if (!hfp_connection) {
2115         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2116     }
2117     hfp_connection->hf_send_rrh = 1;
2118     hfp_connection->hf_send_rrh_command = '2';
2119     hfp_hf_run_for_context(hfp_connection);
2120     return ERROR_CODE_SUCCESS;
2121 }
2122 
2123 uint8_t hfp_hf_query_subscriber_number(hci_con_handle_t acl_handle){
2124     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2125     if (!hfp_connection) {
2126         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2127     }
2128     hfp_connection->hf_send_cnum = 1;
2129     hfp_hf_run_for_context(hfp_connection);
2130     return ERROR_CODE_SUCCESS;
2131 }
2132 
2133 uint8_t hfp_hf_set_hf_indicator(hci_con_handle_t acl_handle, int assigned_number, int value){
2134     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2135     if (!hfp_connection) {
2136         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2137     }
2138     // find index for assigned number
2139     int i;
2140     for (i = 0; i < hfp_hf_indicators_nr ; i++){
2141         if (hfp_hf_indicators[i] == assigned_number){
2142             // set value
2143             hfp_hf_indicators_value[i] = value;
2144             // mark for update
2145             if (hfp_connection->state > HFP_LIST_GENERIC_STATUS_INDICATORS){
2146                 hfp_connection->generic_status_update_bitmap |= (1<<i);
2147                 // send update
2148                 hfp_hf_run_for_context(hfp_connection);
2149             }
2150             return ERROR_CODE_SUCCESS;
2151         }
2152     }
2153     return ERROR_CODE_SUCCESS;
2154 }
2155 
2156 int hfp_hf_in_band_ringtone_active(hci_con_handle_t acl_handle){
2157     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2158     if (!hfp_connection) {
2159         return 0;
2160     }
2161     return get_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE);
2162 }
2163 
2164 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){
2165 	if (!name){
2166 		name = hfp_hf_default_service_name;
2167 	}
2168 	hfp_create_sdp_record(service, service_record_handle, BLUETOOTH_SERVICE_CLASS_HANDSFREE, rfcomm_channel_nr, name);
2169 
2170 	// Construct SupportedFeatures for SDP bitmap:
2171 	//
2172 	// "The values of the “SupportedFeatures” bitmap given in Table 5.4 shall be the same as the values
2173 	//  of the Bits 0 to 4 of the unsolicited result code +BRSF"
2174 	//
2175 	// Wide band speech (bit 5) requires Codec negotiation
2176 	//
2177 	uint16_t sdp_features = supported_features & 0x1f;
2178 	if ( (wide_band_speech != 0) && (supported_features & (1 << HFP_HFSF_CODEC_NEGOTIATION))){
2179 		sdp_features |= 1 << 5;
2180 	}
2181 
2182     if (supported_features & (1 << HFP_HFSF_ENHANCED_VOICE_RECOGNITION_STATUS)){
2183         sdp_features |= 1 << 6;
2184     }
2185 
2186     if (supported_features & (1 << HFP_HFSF_VOICE_RECOGNITION_TEXT)){
2187         sdp_features |= 1 << 7;
2188     }
2189 
2190 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);    // Hands-Free Profile - SupportedFeatures
2191 	de_add_number(service, DE_UINT, DE_SIZE_16, sdp_features);
2192 }
2193 
2194 void hfp_hf_register_packet_handler(btstack_packet_handler_t callback){
2195 	btstack_assert(callback != NULL);
2196 
2197 	hfp_hf_callback = callback;
2198 	hfp_set_hf_callback(callback);
2199 }
2200