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