xref: /btstack/src/classic/hfp_hf.c (revision 0c10ebdb23c8398211e3309dce23119483d552d5)
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         return;
972     }
973 
974     if (hfp_connection->hf_send_binp){
975         hfp_connection->hf_send_binp = 0;
976         hfp_connection->ok_pending = 1;
977         hfp_hf_send_binp(hfp_connection->rfcomm_cid);
978         return;
979     }
980 
981     if (hfp_connection->hf_send_clcc){
982         hfp_connection->hf_send_clcc = 0;
983         hfp_connection->ok_pending = 1;
984         hfp_hf_send_clcc(hfp_connection->rfcomm_cid);
985         return;
986     }
987 
988     if (hfp_connection->hf_send_rrh){
989         hfp_connection->hf_send_rrh = 0;
990         char buffer[20];
991         switch (hfp_connection->hf_send_rrh_command){
992             case '?':
993                 snprintf(buffer, sizeof(buffer), "AT%s?\r",
994                          HFP_RESPONSE_AND_HOLD);
995                 buffer[sizeof(buffer) - 1] = 0;
996                 send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
997                 return;
998             case '0':
999             case '1':
1000             case '2':
1001                 snprintf(buffer, sizeof(buffer), "AT%s=%c\r",
1002                          HFP_RESPONSE_AND_HOLD,
1003                          hfp_connection->hf_send_rrh_command);
1004                 buffer[sizeof(buffer) - 1] = 0;
1005                 send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1006                 return;
1007             default:
1008                 break;
1009         }
1010         return;
1011     }
1012 
1013     if (hfp_connection->hf_send_cnum){
1014         hfp_connection->hf_send_cnum = 0;
1015         char buffer[20];
1016         snprintf(buffer, sizeof(buffer), "AT%s\r",
1017                  HFP_SUBSCRIBER_NUMBER_INFORMATION);
1018         buffer[sizeof(buffer) - 1] = 0;
1019         send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1020         return;
1021     }
1022 
1023     // update HF indicators
1024     if (hfp_connection->generic_status_update_bitmap){
1025         int i;
1026         for (i=0; i < hfp_hf_indicators_nr; i++){
1027             if (get_bit(hfp_connection->generic_status_update_bitmap, i)){
1028                 if (hfp_connection->generic_status_indicators[i].state){
1029                     hfp_connection->ok_pending = 1;
1030                     hfp_connection->generic_status_update_bitmap = store_bit(hfp_connection->generic_status_update_bitmap, i, 0);
1031                     char buffer[30];
1032                     snprintf(buffer, sizeof(buffer), "AT%s=%u,%u\r",
1033                              HFP_TRANSFER_HF_INDICATOR_STATUS,
1034                              hfp_hf_indicators[i],
1035                              (unsigned int)hfp_hf_indicators_value[i]);
1036                     buffer[sizeof(buffer) - 1] = 0;
1037                     send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1038                 } else {
1039                     log_info("Not sending HF indicator %u as it is disabled", hfp_hf_indicators[i]);
1040                 }
1041                 return;
1042             }
1043         }
1044     }
1045 
1046     if (done) return;
1047     // deal with disconnect
1048     switch (hfp_connection->state){
1049         case HFP_W2_DISCONNECT_RFCOMM:
1050             hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED;
1051             rfcomm_disconnect(hfp_connection->rfcomm_cid);
1052             break;
1053 
1054         default:
1055             break;
1056     }
1057 }
1058 
1059 static void hfp_ag_slc_established(hfp_connection_t * hfp_connection){
1060     hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1061 
1062     hfp_emit_slc_connection_event(hfp_connection->local_role, 0, hfp_connection->acl_handle, hfp_connection->remote_addr);
1063 
1064     uint8_t i;
1065     for (i = 0; i < hfp_connection->ag_indicators_nr; i++){
1066         hfp_emit_ag_indicator_mapping_event(hfp_connection, &hfp_connection->ag_indicators[i]);
1067     }
1068 
1069     for (i = 0; i < hfp_connection->ag_indicators_nr; i++){
1070         hfp_connection->ag_indicators[i].status_changed = 0;
1071         hfp_emit_ag_indicator_status_event(hfp_connection, &hfp_connection->ag_indicators[i]);
1072     }
1073 
1074     // restore volume settings
1075     hfp_connection->speaker_gain = hfp_hf_speaker_gain;
1076     hfp_connection->send_speaker_gain = 1;
1077     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SPEAKER_VOLUME, hfp_hf_speaker_gain);
1078     hfp_connection->microphone_gain = hfp_hf_microphone_gain;
1079     hfp_connection->send_microphone_gain = 1;
1080     hfp_emit_event(hfp_connection, HFP_SUBEVENT_MICROPHONE_VOLUME, hfp_hf_microphone_gain);
1081     // enable all indicators
1082     for (i=0; i < hfp_hf_indicators_nr; i++){
1083         hfp_connection->generic_status_indicators[i].uuid = hfp_hf_indicators[i];
1084         hfp_connection->generic_status_indicators[i].state = 1;
1085     }
1086 }
1087 
1088 static void hfp_hf_handle_suggested_codec(hfp_connection_t * hfp_connection){
1089 	if (hfp_supports_codec(hfp_connection->suggested_codec, hfp_hf_codecs_nr, hfp_hf_codecs)){
1090 		// Codec supported, confirm
1091 		hfp_connection->negotiated_codec = hfp_connection->suggested_codec;
1092 		hfp_connection->codec_confirmed = hfp_connection->suggested_codec;
1093 		log_info("hfp: codec confirmed: %s", (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? "mSBC" : "CVSD");
1094 		hfp_connection->codecs_state = HFP_CODECS_HF_CONFIRMED_CODEC;
1095 
1096 		hfp_connection->hf_send_codec_confirm = true;
1097 	} else {
1098 		// Codec not supported, send supported codecs
1099 		hfp_connection->codec_confirmed = 0;
1100 		hfp_connection->suggested_codec = 0;
1101 		hfp_connection->negotiated_codec = 0;
1102 		hfp_connection->codecs_state = HFP_CODECS_W4_AG_COMMON_CODEC;
1103 
1104 		hfp_connection->hf_send_supported_codecs = true;
1105 	}
1106 }
1107 
1108 static bool hfp_hf_switch_on_ok_pending(hfp_connection_t *hfp_connection, uint8_t status){
1109     bool event_emited = true;
1110 
1111     switch (hfp_connection->response_pending_for_command){
1112         case HFP_CMD_TURN_OFF_EC_AND_NR:
1113             hfp_emit_event(hfp_connection, HFP_SUBEVENT_ECHO_CANCELING_AND_NOISE_REDUCTION_DEACTIVATE, status);
1114             break;
1115         default:
1116             event_emited = false;
1117 
1118             switch (hfp_connection->state){
1119                 case HFP_W4_EXCHANGE_SUPPORTED_FEATURES:
1120                     if (has_codec_negotiation_feature(hfp_connection)){
1121                         hfp_connection->state = HFP_NOTIFY_ON_CODECS;
1122                         break;
1123                     }
1124                     hfp_connection->state = HFP_RETRIEVE_INDICATORS;
1125                     break;
1126 
1127                 case HFP_W4_NOTIFY_ON_CODECS:
1128                     hfp_connection->state = HFP_RETRIEVE_INDICATORS;
1129                     break;
1130 
1131                 case HFP_W4_RETRIEVE_INDICATORS:
1132                     hfp_connection->state = HFP_RETRIEVE_INDICATORS_STATUS;
1133                     break;
1134 
1135                 case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1136                     hfp_connection->state = HFP_ENABLE_INDICATORS_STATUS_UPDATE;
1137                     break;
1138 
1139                 case HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE:
1140                     if (has_call_waiting_and_3way_calling_feature(hfp_connection)){
1141                         hfp_connection->state = HFP_RETRIEVE_CAN_HOLD_CALL;
1142                         break;
1143                     }
1144                     if (has_hf_indicators_feature(hfp_connection)){
1145                         hfp_connection->state = HFP_LIST_GENERIC_STATUS_INDICATORS;
1146                         break;
1147                     }
1148                     hfp_ag_slc_established(hfp_connection);
1149                     break;
1150 
1151                 case HFP_W4_RETRIEVE_CAN_HOLD_CALL:
1152                     if (has_hf_indicators_feature(hfp_connection)){
1153                         hfp_connection->state = HFP_LIST_GENERIC_STATUS_INDICATORS;
1154                         break;
1155                     }
1156                     hfp_ag_slc_established(hfp_connection);
1157                     break;
1158 
1159                 case HFP_W4_LIST_GENERIC_STATUS_INDICATORS:
1160                     hfp_connection->state = HFP_RETRIEVE_GENERIC_STATUS_INDICATORS;
1161                     break;
1162 
1163                 case HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS:
1164                     hfp_connection->state = HFP_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS;
1165                     break;
1166 
1167                 case HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS:
1168                     hfp_ag_slc_established(hfp_connection);
1169                     break;
1170                 case HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED:
1171                     if (hfp_connection->enable_status_update_for_ag_indicators != 0xFF){
1172                         hfp_connection->enable_status_update_for_ag_indicators = 0xFF;
1173                         hfp_emit_event(hfp_connection, HFP_SUBEVENT_COMPLETE, 0);
1174                         break;
1175                     }
1176 
1177                     if (hfp_connection->change_status_update_for_individual_ag_indicators == 1){
1178                         hfp_connection->change_status_update_for_individual_ag_indicators = 0;
1179                         hfp_emit_event(hfp_connection, HFP_SUBEVENT_COMPLETE, 0);
1180                         break;
1181                     }
1182 
1183                     switch (hfp_connection->hf_query_operator_state){
1184                         case HFP_HF_QUERY_OPERATOR_W4_SET_FORMAT_OK:
1185                             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_SEND_QUERY;
1186                             break;
1187                         case HPF_HF_QUERY_OPERATOR_W4_RESULT:
1188                             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_FORMAT_SET;
1189                             hfp_emit_network_operator_event(hfp_connection);
1190                             break;
1191                         default:
1192                             break;
1193                     }
1194 
1195                     if (hfp_connection->enable_extended_audio_gateway_error_report){
1196                         hfp_connection->enable_extended_audio_gateway_error_report = 0;
1197                         break;
1198                     }
1199 
1200                     switch (hfp_connection->codecs_state){
1201                         case HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE:
1202                             hfp_connection->codecs_state = HFP_CODECS_W4_AG_COMMON_CODEC;
1203                             break;
1204                         case HFP_CODECS_HF_CONFIRMED_CODEC:
1205                             hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
1206                             break;
1207                         default:
1208                             break;
1209                     }
1210                     hfp_hf_voice_recognition_state_machine(hfp_connection);
1211                     break;
1212                 case HFP_AUDIO_CONNECTION_ESTABLISHED:
1213                     hfp_hf_voice_recognition_state_machine(hfp_connection);
1214                     break;
1215                 default:
1216                     break;
1217             }
1218             break;
1219     }
1220 
1221     // done
1222     hfp_connection->response_pending_for_command = HFP_CMD_NONE;
1223     hfp_connection->ok_pending = 0;
1224     hfp_connection->command = HFP_CMD_NONE;
1225     return event_emited;
1226 }
1227 
1228 static bool hfp_is_ringing(hfp_callsetup_status_t callsetup_status){
1229     switch (callsetup_status){
1230         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1231         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1232             return true;
1233         default:
1234             return false;
1235    }
1236 }
1237 
1238 static void hfp_hf_handle_transfer_ag_indicator_status(hfp_connection_t * hfp_connection) {
1239     uint16_t i;
1240 
1241     for (i = 0; i < hfp_connection->ag_indicators_nr; i++){
1242         if (hfp_connection->ag_indicators[i].status_changed) {
1243             if (strcmp(hfp_connection->ag_indicators[i].name, "callsetup") == 0){
1244                 hfp_callsetup_status_t new_hf_callsetup_status = (hfp_callsetup_status_t) hfp_connection->ag_indicators[i].status;
1245                 bool ringing_old = hfp_is_ringing(hfp_hf_callsetup_status);
1246                 bool ringing_new = hfp_is_ringing(new_hf_callsetup_status);
1247                 if (ringing_old != ringing_new){
1248                     if (ringing_new){
1249                         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_START_RINGING);
1250                     } else {
1251                         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_STOP_RINGING);
1252                     }
1253                 }
1254                 hfp_hf_callsetup_status = new_hf_callsetup_status;
1255             } else if (strcmp(hfp_connection->ag_indicators[i].name, "callheld") == 0){
1256                 hfp_hf_callheld_status = (hfp_callheld_status_t) hfp_connection->ag_indicators[i].status;
1257                 // avoid set but not used warning
1258                 (void) hfp_hf_callheld_status;
1259             } else if (strcmp(hfp_connection->ag_indicators[i].name, "call") == 0){
1260                 hfp_call_status_t new_hf_call_status = (hfp_call_status_t) hfp_connection->ag_indicators[i].status;
1261                 if (hfp_hf_call_status != new_hf_call_status){
1262                     if (new_hf_call_status == HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS){
1263                         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_TERMINATED);
1264                     } else {
1265                         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_ANSWERED);
1266                     }
1267                 }
1268                 hfp_hf_call_status = new_hf_call_status;
1269             }
1270             hfp_connection->ag_indicators[i].status_changed = 0;
1271             hfp_emit_ag_indicator_status_event(hfp_connection, &hfp_connection->ag_indicators[i]);
1272             break;
1273         }
1274     }
1275 }
1276 
1277 static void hfp_hf_handle_rfcomm_command(hfp_connection_t * hfp_connection){
1278     int value;
1279     int i;
1280     bool event_emited;
1281 
1282     // last argument is still in line_buffer
1283 
1284     switch (hfp_connection->command){
1285         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1286             hfp_connection->command = HFP_CMD_NONE;
1287             hfp_hf_emit_subscriber_information(hfp_connection, 0);
1288             break;
1289         case HFP_CMD_RESPONSE_AND_HOLD_STATUS:
1290             hfp_connection->command = HFP_CMD_NONE;
1291             hfp_emit_event(hfp_connection, HFP_SUBEVENT_RESPONSE_AND_HOLD_STATUS, btstack_atoi((char *)&hfp_connection->line_buffer[0]));
1292             break;
1293         case HFP_CMD_LIST_CURRENT_CALLS:
1294             hfp_connection->command = HFP_CMD_NONE;
1295             hfp_hf_emit_enhanced_call_status(hfp_connection);
1296             break;
1297         case HFP_CMD_SET_SPEAKER_GAIN:
1298             hfp_connection->command = HFP_CMD_NONE;
1299             value = btstack_atoi((char*)hfp_connection->line_buffer);
1300             hfp_hf_speaker_gain = value;
1301             hfp_emit_event(hfp_connection, HFP_SUBEVENT_SPEAKER_VOLUME, value);
1302             break;
1303         case HFP_CMD_SET_MICROPHONE_GAIN:
1304             hfp_connection->command = HFP_CMD_NONE;
1305             value = btstack_atoi((char*)hfp_connection->line_buffer);
1306             hfp_hf_microphone_gain = value;
1307             hfp_emit_event(hfp_connection, HFP_SUBEVENT_MICROPHONE_VOLUME, value);
1308             break;
1309         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1310             hfp_connection->command = HFP_CMD_NONE;
1311             hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_NUMBER_FOR_VOICE_TAG, hfp_connection->bnip_number);
1312             break;
1313         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1314             hfp_connection->command = HFP_CMD_NONE;
1315             hfp_hf_emit_type_number_alpha(hfp_connection, HFP_SUBEVENT_CALL_WAITING_NOTIFICATION);
1316             break;
1317         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1318             hfp_connection->command = HFP_CMD_NONE;
1319             hfp_hf_emit_type_number_alpha(hfp_connection, HFP_SUBEVENT_CALLING_LINE_IDENTIFICATION_NOTIFICATION);
1320             break;
1321         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1322             hfp_connection->command = HFP_CMD_NONE;
1323             hfp_connection->ok_pending = 0;
1324             hfp_connection->extended_audio_gateway_error = 0;
1325             hfp_emit_event(hfp_connection, HFP_SUBEVENT_EXTENDED_AUDIO_GATEWAY_ERROR, hfp_connection->extended_audio_gateway_error_value);
1326             break;
1327         case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
1328             break;
1329         case HFP_CMD_ERROR:
1330             switch (hfp_connection->state){
1331                 case HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED:
1332                     switch (hfp_connection->codecs_state){
1333                         case HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE:
1334                             hfp_reset_context_flags(hfp_connection);
1335                             hfp_emit_sco_event(hfp_connection, HFP_REMOTE_REJECTS_AUDIO_CONNECTION, 0, hfp_connection->remote_addr, hfp_connection->negotiated_codec);
1336                             return;
1337                         default:
1338                             break;
1339                     }
1340                     break;
1341                 default:
1342                     break;
1343             }
1344 
1345             // handle error response for voice activation (HF initiated)
1346             switch(hfp_connection->vra_state_requested){
1347                 case HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1348                     hfp_emit_enhanced_voice_recognition_hf_ready_for_audio_event(hfp_connection, ERROR_CODE_UNSPECIFIED_ERROR);
1349                     break;
1350                 default:
1351                     if (hfp_connection->vra_state_requested == hfp_connection->vra_state){
1352                         break;
1353                     }
1354                     hfp_connection->vra_state_requested = hfp_connection->vra_state;
1355                     hfp_emit_voice_recognition_enabled(hfp_connection, ERROR_CODE_UNSPECIFIED_ERROR);
1356                     hfp_reset_context_flags(hfp_connection);
1357                     return;
1358             }
1359             event_emited = hfp_hf_switch_on_ok_pending(hfp_connection, ERROR_CODE_UNSPECIFIED_ERROR);
1360             if (!event_emited){
1361                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_COMPLETE, 1);
1362             }
1363             hfp_reset_context_flags(hfp_connection);
1364             break;
1365 
1366         case HFP_CMD_OK:
1367             hfp_hf_switch_on_ok_pending(hfp_connection, ERROR_CODE_SUCCESS);
1368             break;
1369         case HFP_CMD_RING:
1370             hfp_connection->command = HFP_CMD_NONE;
1371             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_RING);
1372             break;
1373         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1374             hfp_connection->command = HFP_CMD_NONE;
1375             hfp_hf_handle_transfer_ag_indicator_status(hfp_connection);
1376             break;
1377         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1378             hfp_connection->command = HFP_CMD_NONE;
1379             // report status after SLC established
1380             if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
1381                 break;
1382             }
1383             for (i = 0; i < hfp_connection->ag_indicators_nr; i++){
1384                 hfp_emit_ag_indicator_mapping_event(hfp_connection, &hfp_connection->ag_indicators[i]);
1385             }
1386             break;
1387     	case HFP_CMD_AG_SUGGESTED_CODEC:
1388             hfp_connection->command = HFP_CMD_NONE;
1389     		hfp_hf_handle_suggested_codec(hfp_connection);
1390 			break;
1391         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1392             hfp_emit_event(hfp_connection, HFP_SUBEVENT_IN_BAND_RING_TONE, get_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE));
1393         default:
1394             break;
1395     }
1396 }
1397 
1398 static int hfp_parser_is_end_of_line(uint8_t byte){
1399 	return (byte == '\n') || (byte == '\r');
1400 }
1401 
1402 static void hfp_hf_handle_rfcomm_data(hfp_connection_t * hfp_connection, uint8_t *packet, uint16_t size){
1403     // assertion: size >= 1 as rfcomm.c does not deliver empty packets
1404     if (size < 1) return;
1405 
1406     hfp_log_rfcomm_message("HFP_HF_RX", packet, size);
1407 #ifdef ENABLE_HFP_AT_MESSAGES
1408     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_RECEIVED, (char *) packet);
1409 #endif
1410 
1411     // process messages byte-wise
1412     uint8_t pos;
1413     for (pos = 0; pos < size; pos++){
1414         hfp_parse(hfp_connection, packet[pos], 1);
1415         // parse until end of line "\r" or "\n"
1416         if (!hfp_parser_is_end_of_line(packet[pos])) continue;
1417         hfp_hf_handle_rfcomm_command(hfp_connection);
1418     }
1419 }
1420 
1421 static void hfp_hf_run(void){
1422     btstack_linked_list_iterator_t it;
1423     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1424     while (btstack_linked_list_iterator_has_next(&it)){
1425         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1426         if (hfp_connection->local_role != HFP_ROLE_HF) continue;
1427         hfp_hf_run_for_context(hfp_connection);
1428     }
1429 }
1430 
1431 static void hfp_hf_rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1432     hfp_connection_t * hfp_connection;
1433     switch (packet_type){
1434         case RFCOMM_DATA_PACKET:
1435             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(channel);
1436             if (!hfp_connection) return;
1437             hfp_hf_handle_rfcomm_data(hfp_connection, packet, size);
1438             hfp_hf_run_for_context(hfp_connection);
1439             return;
1440         case HCI_EVENT_PACKET:
1441             if (packet[0] == RFCOMM_EVENT_CAN_SEND_NOW){
1442                 uint16_t rfcomm_cid = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
1443                 hfp_hf_run_for_context(get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid));
1444                 return;
1445             }
1446             hfp_handle_rfcomm_event(packet_type, channel, packet, size, HFP_ROLE_HF);
1447             break;
1448         default:
1449             break;
1450     }
1451     hfp_hf_run();
1452 }
1453 
1454 static void hfp_hf_hci_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1455     hfp_handle_hci_event(packet_type, channel, packet, size, HFP_ROLE_HF);
1456     hfp_hf_run();
1457 }
1458 
1459 static void hfp_hf_set_defaults(void){
1460     hfp_hf_supported_features = HFP_DEFAULT_HF_SUPPORTED_FEATURES;
1461     hfp_hf_call_status = HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS;
1462     hfp_hf_callsetup_status = HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1463     hfp_hf_callheld_status= HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1464     hfp_hf_codecs_nr = 0;
1465     hfp_hf_speaker_gain = 9;
1466     hfp_hf_microphone_gain = 9;
1467     hfp_hf_indicators_nr = 0;
1468 }
1469 
1470 uint8_t hfp_hf_init(uint16_t rfcomm_channel_nr){
1471     uint8_t status = rfcomm_register_service(hfp_hf_rfcomm_packet_handler, rfcomm_channel_nr, 0xffff);
1472     if (status != ERROR_CODE_SUCCESS){
1473         return status;
1474     }
1475 
1476     hfp_init();
1477     hfp_hf_set_defaults();
1478 
1479     hfp_hf_hci_event_callback_registration.callback = &hfp_hf_hci_event_packet_handler;
1480     hci_add_event_handler(&hfp_hf_hci_event_callback_registration);
1481 
1482     // used to set packet handler for outgoing rfcomm connections - could be handled by emitting an event to us
1483     hfp_set_hf_rfcomm_packet_handler(&hfp_hf_rfcomm_packet_handler);
1484     return ERROR_CODE_SUCCESS;
1485 }
1486 
1487 void hfp_hf_deinit(void){
1488     hfp_deinit();
1489     hfp_hf_set_defaults();
1490 
1491     hfp_hf_callback = NULL;
1492     (void) memset(&hfp_hf_hci_event_callback_registration, 0, sizeof(btstack_packet_callback_registration_t));
1493     (void) memset(hfp_hf_phone_number, 0, sizeof(hfp_hf_phone_number));
1494 }
1495 
1496 void hfp_hf_init_codecs(int codecs_nr, const uint8_t * codecs){
1497     btstack_assert(codecs_nr < HFP_MAX_NUM_CODECS);
1498 
1499     hfp_hf_codecs_nr = codecs_nr;
1500     int i;
1501     for (i=0; i<codecs_nr; i++){
1502         hfp_hf_codecs[i] = codecs[i];
1503     }
1504 }
1505 
1506 void hfp_hf_init_supported_features(uint32_t supported_features){
1507     hfp_hf_supported_features = supported_features;
1508 }
1509 
1510 void hfp_hf_init_hf_indicators(int indicators_nr, const uint16_t * indicators){
1511     btstack_assert(hfp_hf_indicators_nr < HFP_MAX_NUM_INDICATORS);
1512 
1513     hfp_hf_indicators_nr = indicators_nr;
1514     int i;
1515     for (i = 0; i < hfp_hf_indicators_nr ; i++){
1516         hfp_hf_indicators[i] = indicators[i];
1517     }
1518 }
1519 
1520 uint8_t hfp_hf_establish_service_level_connection(bd_addr_t bd_addr){
1521     return hfp_establish_service_level_connection(bd_addr, BLUETOOTH_SERVICE_CLASS_HANDSFREE_AUDIO_GATEWAY, HFP_ROLE_HF);
1522 }
1523 
1524 uint8_t hfp_hf_release_service_level_connection(hci_con_handle_t acl_handle){
1525     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1526     if (!hfp_connection){
1527         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1528     }
1529     hfp_trigger_release_service_level_connection(hfp_connection);
1530     hfp_hf_run_for_context(hfp_connection);
1531     return ERROR_CODE_SUCCESS;
1532 }
1533 
1534 static uint8_t hfp_hf_set_status_update_for_all_ag_indicators(hci_con_handle_t acl_handle, uint8_t enable){
1535     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1536     if (!hfp_connection) {
1537         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1538     }
1539     hfp_connection->enable_status_update_for_ag_indicators = enable;
1540     hfp_hf_run_for_context(hfp_connection);
1541     return ERROR_CODE_SUCCESS;
1542 }
1543 
1544 uint8_t hfp_hf_enable_status_update_for_all_ag_indicators(hci_con_handle_t acl_handle){
1545     return hfp_hf_set_status_update_for_all_ag_indicators(acl_handle, 1);
1546 }
1547 
1548 uint8_t hfp_hf_disable_status_update_for_all_ag_indicators(hci_con_handle_t acl_handle){
1549     return hfp_hf_set_status_update_for_all_ag_indicators(acl_handle, 0);
1550 }
1551 
1552 // TODO: returned ERROR - wrong format
1553 uint8_t hfp_hf_set_status_update_for_individual_ag_indicators(hci_con_handle_t acl_handle, uint32_t indicators_status_bitmap){
1554     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1555     if (!hfp_connection) {
1556         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1557     }
1558     hfp_connection->change_status_update_for_individual_ag_indicators = 1;
1559     hfp_connection->ag_indicators_status_update_bitmap = indicators_status_bitmap;
1560     hfp_hf_run_for_context(hfp_connection);
1561     return ERROR_CODE_SUCCESS;
1562 }
1563 
1564 uint8_t hfp_hf_query_operator_selection(hci_con_handle_t acl_handle){
1565     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1566     if (!hfp_connection) {
1567         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1568     }
1569 
1570     switch (hfp_connection->hf_query_operator_state){
1571         case HFP_HF_QUERY_OPERATOR_FORMAT_NOT_SET:
1572             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_SET_FORMAT;
1573             break;
1574         case HFP_HF_QUERY_OPERATOR_FORMAT_SET:
1575             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_SEND_QUERY;
1576             break;
1577         default:
1578             return ERROR_CODE_COMMAND_DISALLOWED;
1579     }
1580     hfp_hf_run_for_context(hfp_connection);
1581     return ERROR_CODE_SUCCESS;
1582 }
1583 
1584 static uint8_t hfp_hf_set_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle, uint8_t enable){
1585     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1586     if (!hfp_connection) {
1587         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1588     }
1589     hfp_connection->enable_extended_audio_gateway_error_report = enable;
1590     hfp_hf_run_for_context(hfp_connection);
1591     return ERROR_CODE_SUCCESS;
1592 }
1593 
1594 
1595 uint8_t hfp_hf_enable_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle){
1596     return hfp_hf_set_report_extended_audio_gateway_error_result_code(acl_handle, 1);
1597 }
1598 
1599 uint8_t hfp_hf_disable_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle){
1600     return hfp_hf_set_report_extended_audio_gateway_error_result_code(acl_handle, 0);
1601 }
1602 
1603 static uint8_t hfp_hf_esco_s4_supported(hfp_connection_t * hfp_connection){
1604     return (hfp_connection->remote_supported_features & (1<<HFP_AGSF_ESCO_S4)) &&  (hfp_hf_supported_features & (1 << HFP_HFSF_ESCO_S4));
1605 }
1606 
1607 uint8_t hfp_hf_establish_audio_connection(hci_con_handle_t acl_handle){
1608     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1609     if (!hfp_connection) {
1610         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1611     }
1612 
1613     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
1614         return ERROR_CODE_COMMAND_DISALLOWED;
1615     }
1616 
1617     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO){
1618         return ERROR_CODE_COMMAND_DISALLOWED;
1619     }
1620     if (has_codec_negotiation_feature(hfp_connection)) {
1621         switch (hfp_connection->codecs_state) {
1622             case HFP_CODECS_W4_AG_COMMON_CODEC:
1623                 break;
1624             case HFP_CODECS_EXCHANGED:
1625                 hfp_connection->trigger_codec_exchange = 1;
1626                 break;
1627             default:
1628                 hfp_connection->codec_confirmed = 0;
1629                 hfp_connection->suggested_codec = 0;
1630                 hfp_connection->negotiated_codec = 0;
1631                 hfp_connection->codecs_state = HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE;
1632                 hfp_connection->trigger_codec_exchange = 1;
1633                 break;
1634         }
1635     } else {
1636         log_info("no codec negotiation feature, use CVSD");
1637         hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
1638         hfp_connection->suggested_codec = HFP_CODEC_CVSD;
1639         hfp_connection->codec_confirmed = hfp_connection->suggested_codec;
1640         hfp_connection->negotiated_codec = hfp_connection->suggested_codec;
1641         hfp_init_link_settings(hfp_connection, hfp_hf_esco_s4_supported(hfp_connection));
1642         hfp_connection->establish_audio_connection = 1;
1643         hfp_connection->state = HFP_W4_SCO_CONNECTED;
1644     }
1645 
1646     hfp_hf_run_for_context(hfp_connection);
1647     return ERROR_CODE_SUCCESS;
1648 }
1649 
1650 uint8_t hfp_hf_release_audio_connection(hci_con_handle_t acl_handle){
1651     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1652     if (!hfp_connection) {
1653         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1654     }
1655     if (hfp_connection->vra_state == HFP_VRA_VOICE_RECOGNITION_ACTIVATED){
1656         return ERROR_CODE_COMMAND_DISALLOWED;
1657     }
1658     uint8_t status = hfp_trigger_release_audio_connection(hfp_connection);
1659     if (status == ERROR_CODE_SUCCESS){
1660         hfp_hf_run_for_context(hfp_connection);
1661     }
1662     return ERROR_CODE_SUCCESS;
1663 }
1664 
1665 uint8_t hfp_hf_answer_incoming_call(hci_con_handle_t acl_handle){
1666     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1667     if (!hfp_connection) {
1668         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1669     }
1670 
1671     if (hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
1672         hfp_connection->hf_answer_incoming_call = 1;
1673         hfp_hf_run_for_context(hfp_connection);
1674     } else {
1675         log_error("HFP HF: answering incoming call with wrong callsetup status %u", hfp_hf_callsetup_status);
1676         return ERROR_CODE_COMMAND_DISALLOWED;
1677     }
1678     return ERROR_CODE_SUCCESS;
1679 }
1680 
1681 uint8_t hfp_hf_terminate_call(hci_con_handle_t acl_handle){
1682     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1683     if (!hfp_connection) {
1684         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1685     }
1686     hfp_connection->hf_send_chup = 1;
1687     hfp_hf_run_for_context(hfp_connection);
1688     return ERROR_CODE_SUCCESS;
1689 }
1690 
1691 uint8_t hfp_hf_reject_incoming_call(hci_con_handle_t acl_handle){
1692     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1693     if (!hfp_connection) {
1694         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1695     }
1696 
1697     if (hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
1698         hfp_connection->hf_send_chup = 1;
1699         hfp_hf_run_for_context(hfp_connection);
1700     }
1701     return ERROR_CODE_SUCCESS;
1702 }
1703 
1704 uint8_t hfp_hf_user_busy(hci_con_handle_t acl_handle){
1705     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1706     if (!hfp_connection) {
1707         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1708     }
1709 
1710     if (hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
1711         hfp_connection->hf_send_chld_0 = 1;
1712         hfp_hf_run_for_context(hfp_connection);
1713     }
1714     return ERROR_CODE_SUCCESS;
1715 }
1716 
1717 uint8_t hfp_hf_end_active_and_accept_other(hci_con_handle_t acl_handle){
1718     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1719     if (!hfp_connection) {
1720         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1721     }
1722 
1723     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1724         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1725         hfp_connection->hf_send_chld_1 = 1;
1726         hfp_hf_run_for_context(hfp_connection);
1727     }
1728     return ERROR_CODE_SUCCESS;
1729 }
1730 
1731 uint8_t hfp_hf_swap_calls(hci_con_handle_t acl_handle){
1732     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1733     if (!hfp_connection) {
1734         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1735     }
1736 
1737     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1738         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1739         hfp_connection->hf_send_chld_2 = 1;
1740         hfp_hf_run_for_context(hfp_connection);
1741     }
1742     return ERROR_CODE_SUCCESS;
1743 }
1744 
1745 uint8_t hfp_hf_join_held_call(hci_con_handle_t acl_handle){
1746     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1747     if (!hfp_connection) {
1748         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1749     }
1750 
1751     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1752         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1753         hfp_connection->hf_send_chld_3 = 1;
1754         hfp_hf_run_for_context(hfp_connection);
1755     }
1756     return ERROR_CODE_SUCCESS;
1757 }
1758 
1759 uint8_t hfp_hf_connect_calls(hci_con_handle_t acl_handle){
1760     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1761     if (!hfp_connection) {
1762         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1763     }
1764 
1765     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1766         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1767         hfp_connection->hf_send_chld_4 = 1;
1768         hfp_hf_run_for_context(hfp_connection);
1769     }
1770     return ERROR_CODE_SUCCESS;
1771 }
1772 
1773 uint8_t hfp_hf_release_call_with_index(hci_con_handle_t acl_handle, int index){
1774     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1775     if (!hfp_connection) {
1776         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1777     }
1778 
1779     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1780         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1781         hfp_connection->hf_send_chld_x = 1;
1782         hfp_connection->hf_send_chld_x_index = 10 + index;
1783         hfp_hf_run_for_context(hfp_connection);
1784     }
1785     return ERROR_CODE_SUCCESS;
1786 }
1787 
1788 uint8_t hfp_hf_private_consultation_with_call(hci_con_handle_t acl_handle, int index){
1789     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1790     if (!hfp_connection) {
1791         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1792     }
1793 
1794     if ((hfp_hf_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1795         (hfp_hf_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1796         hfp_connection->hf_send_chld_x = 1;
1797         hfp_connection->hf_send_chld_x_index = 20 + index;
1798         hfp_hf_run_for_context(hfp_connection);
1799     }
1800     return ERROR_CODE_SUCCESS;
1801 }
1802 
1803 uint8_t hfp_hf_dial_number(hci_con_handle_t acl_handle, char * number){
1804     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1805     if (!hfp_connection) {
1806         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1807     }
1808 
1809     hfp_connection->hf_initiate_outgoing_call = 1;
1810     snprintf(hfp_hf_phone_number, sizeof(hfp_hf_phone_number), "%s", number);
1811     hfp_hf_run_for_context(hfp_connection);
1812     return ERROR_CODE_SUCCESS;
1813 }
1814 
1815 uint8_t hfp_hf_dial_memory(hci_con_handle_t acl_handle, int memory_id){
1816     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1817     if (!hfp_connection) {
1818         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1819     }
1820 
1821     hfp_connection->hf_initiate_memory_dialing = 1;
1822     hfp_connection->memory_id = memory_id;
1823 
1824     hfp_hf_run_for_context(hfp_connection);
1825     return ERROR_CODE_SUCCESS;
1826 }
1827 
1828 uint8_t hfp_hf_redial_last_number(hci_con_handle_t acl_handle){
1829     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1830     if (!hfp_connection) {
1831         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1832     }
1833 
1834     hfp_connection->hf_initiate_redial_last_number = 1;
1835     hfp_hf_run_for_context(hfp_connection);
1836     return ERROR_CODE_SUCCESS;
1837 }
1838 
1839 uint8_t hfp_hf_activate_call_waiting_notification(hci_con_handle_t acl_handle){
1840     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1841     if (!hfp_connection) {
1842         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1843     }
1844 
1845     hfp_connection->hf_activate_call_waiting_notification = 1;
1846     hfp_hf_run_for_context(hfp_connection);
1847     return ERROR_CODE_SUCCESS;
1848 }
1849 
1850 
1851 uint8_t hfp_hf_deactivate_call_waiting_notification(hci_con_handle_t acl_handle){
1852     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1853     if (!hfp_connection) {
1854         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1855     }
1856 
1857     hfp_connection->hf_deactivate_call_waiting_notification = 1;
1858     hfp_hf_run_for_context(hfp_connection);
1859     return ERROR_CODE_SUCCESS;
1860 }
1861 
1862 
1863 uint8_t hfp_hf_activate_calling_line_notification(hci_con_handle_t acl_handle){
1864     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1865     if (!hfp_connection) {
1866         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1867     }
1868 
1869     hfp_connection->hf_activate_calling_line_notification = 1;
1870     hfp_hf_run_for_context(hfp_connection);
1871     return ERROR_CODE_SUCCESS;
1872 }
1873 
1874 uint8_t hfp_hf_deactivate_calling_line_notification(hci_con_handle_t acl_handle){
1875     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1876     if (!hfp_connection) {
1877         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1878     }
1879 
1880     hfp_connection->hf_deactivate_calling_line_notification = 1;
1881     hfp_hf_run_for_context(hfp_connection);
1882     return ERROR_CODE_SUCCESS;
1883 }
1884 
1885 static bool hfp_hf_echo_canceling_and_noise_reduction_supported(hfp_connection_t * hfp_connection){
1886     int ag = get_bit(hfp_connection->remote_supported_features, HFP_AGSF_EC_NR_FUNCTION);
1887     int hf = get_bit(hfp_hf_supported_features, HFP_HFSF_EC_NR_FUNCTION);
1888     return hf && ag;
1889 }
1890 
1891 uint8_t hfp_hf_deactivate_echo_canceling_and_noise_reduction(hci_con_handle_t acl_handle){
1892     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1893     if (!hfp_connection) {
1894         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1895     }
1896     if (!hfp_hf_echo_canceling_and_noise_reduction_supported(hfp_connection)){
1897         return ERROR_CODE_COMMAND_DISALLOWED;
1898     }
1899 
1900     hfp_connection->hf_deactivate_echo_canceling_and_noise_reduction = 1;
1901     hfp_hf_run_for_context(hfp_connection);
1902     return ERROR_CODE_SUCCESS;
1903 }
1904 
1905 uint8_t hfp_hf_activate_voice_recognition(hci_con_handle_t acl_handle){
1906      hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1907     if (!hfp_connection) {
1908         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1909     }
1910     if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED || hfp_connection->state > HFP_AUDIO_CONNECTION_ESTABLISHED){
1911         return ERROR_CODE_COMMAND_DISALLOWED;
1912     }
1913 
1914     bool enhanced_vra_supported = hfp_hf_enhanced_vra_flag_supported(hfp_connection);
1915     bool legacy_vra_supported   = hfp_hf_vra_flag_supported(hfp_connection);
1916     if (!enhanced_vra_supported && !legacy_vra_supported){
1917         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1918     }
1919 
1920     switch (hfp_connection->vra_state){
1921         case HFP_VRA_VOICE_RECOGNITION_OFF:
1922         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF:
1923             hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED;
1924             hfp_connection->enhanced_voice_recognition_enabled = enhanced_vra_supported;
1925             break;
1926         case HFP_VRA_W4_VOICE_RECOGNITION_OFF:
1927             hfp_connection->activate_voice_recognition = true;
1928             break;
1929         default:
1930             return ERROR_CODE_COMMAND_DISALLOWED;
1931     }
1932 
1933     hfp_hf_run_for_context(hfp_connection);
1934     return ERROR_CODE_SUCCESS;
1935 }
1936 
1937 uint8_t hfp_hf_enhanced_voice_recognition_report_ready_for_audio(hci_con_handle_t acl_handle){
1938     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1939     if (!hfp_connection) {
1940         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1941     }
1942 
1943     if (hfp_connection->emit_vra_enabled_after_audio_established){
1944         return ERROR_CODE_COMMAND_DISALLOWED;
1945     }
1946 
1947     if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED){
1948         return ERROR_CODE_COMMAND_DISALLOWED;
1949     }
1950 
1951     bool enhanced_vra_supported = hfp_hf_enhanced_vra_flag_supported(hfp_connection);
1952     if (!enhanced_vra_supported){
1953         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1954     }
1955 
1956     switch (hfp_connection->vra_state){
1957         case HFP_VRA_VOICE_RECOGNITION_ACTIVATED:
1958         case HFP_VRA_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1959             hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO;
1960             break;
1961         default:
1962             return ERROR_CODE_COMMAND_DISALLOWED;
1963     }
1964 
1965     hfp_hf_run_for_context(hfp_connection);
1966     return ERROR_CODE_SUCCESS;
1967 }
1968 
1969 
1970 uint8_t hfp_hf_deactivate_voice_recognition(hci_con_handle_t acl_handle){
1971     // return deactivate_voice_recognition(acl_handle, false);
1972     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1973     if (!hfp_connection) {
1974         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1975     }
1976 
1977     if (hfp_connection->emit_vra_enabled_after_audio_established){
1978         return ERROR_CODE_COMMAND_DISALLOWED;
1979     }
1980 
1981     if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED ||
1982         hfp_connection->state > HFP_AUDIO_CONNECTION_ESTABLISHED){
1983         return ERROR_CODE_COMMAND_DISALLOWED;
1984     }
1985 
1986     bool enhanced_vra_supported = hfp_hf_enhanced_vra_flag_supported(hfp_connection);
1987     bool legacy_vra_supported   = hfp_hf_vra_flag_supported(hfp_connection);
1988     if (!enhanced_vra_supported && !legacy_vra_supported){
1989         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
1990     }
1991 
1992     switch (hfp_connection->vra_state){
1993         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED:
1994         case HFP_VRA_VOICE_RECOGNITION_ACTIVATED:
1995         case HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1996         case HFP_VRA_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
1997             hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF;
1998             break;
1999 
2000         case HFP_VRA_W4_VOICE_RECOGNITION_ACTIVATED:
2001         case HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
2002             hfp_connection->deactivate_voice_recognition = true;
2003             break;
2004 
2005         case HFP_VRA_VOICE_RECOGNITION_OFF:
2006         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF:
2007         case HFP_VRA_W4_VOICE_RECOGNITION_OFF:
2008         default:
2009             return ERROR_CODE_COMMAND_DISALLOWED;
2010     }
2011 
2012     hfp_hf_run_for_context(hfp_connection);
2013     return ERROR_CODE_SUCCESS;
2014 }
2015 
2016 uint8_t hfp_hf_set_microphone_gain(hci_con_handle_t acl_handle, int gain){
2017     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2018     if (!hfp_connection) {
2019         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2020     }
2021 
2022     if (hfp_connection->microphone_gain == gain) {
2023         return ERROR_CODE_SUCCESS;
2024     }
2025 
2026     if ((gain < 0) || (gain > 15)){
2027         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
2028         return ERROR_CODE_COMMAND_DISALLOWED;
2029     }
2030 
2031     hfp_connection->microphone_gain = gain;
2032     hfp_connection->send_microphone_gain = 1;
2033     hfp_hf_run_for_context(hfp_connection);
2034     return ERROR_CODE_SUCCESS;
2035 }
2036 
2037 uint8_t hfp_hf_set_speaker_gain(hci_con_handle_t acl_handle, int gain){
2038     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2039     if (!hfp_connection) {
2040         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2041     }
2042 
2043     if (hfp_connection->speaker_gain == gain){
2044         return ERROR_CODE_SUCCESS;
2045     }
2046 
2047     if ((gain < 0) || (gain > 15)){
2048         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
2049         return ERROR_CODE_COMMAND_DISALLOWED;
2050     }
2051 
2052     hfp_connection->speaker_gain = gain;
2053     hfp_connection->send_speaker_gain = 1;
2054     hfp_hf_run_for_context(hfp_connection);
2055     return ERROR_CODE_SUCCESS;
2056 }
2057 
2058 uint8_t hfp_hf_send_dtmf_code(hci_con_handle_t acl_handle, char code){
2059     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2060     if (!hfp_connection) {
2061         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2062     }
2063     hfp_connection->hf_send_dtmf_code = code;
2064     hfp_hf_run_for_context(hfp_connection);
2065     return ERROR_CODE_SUCCESS;
2066 }
2067 
2068 uint8_t hfp_hf_request_phone_number_for_voice_tag(hci_con_handle_t acl_handle){
2069     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2070     if (!hfp_connection) {
2071         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2072     }
2073     hfp_connection->hf_send_binp = 1;
2074     hfp_hf_run_for_context(hfp_connection);
2075     return ERROR_CODE_SUCCESS;
2076 }
2077 
2078 uint8_t hfp_hf_query_current_call_status(hci_con_handle_t acl_handle){
2079     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2080     if (!hfp_connection) {
2081         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2082     }
2083     hfp_connection->hf_send_clcc = 1;
2084     hfp_hf_run_for_context(hfp_connection);
2085     return ERROR_CODE_SUCCESS;
2086 }
2087 
2088 
2089 uint8_t hfp_hf_rrh_query_status(hci_con_handle_t acl_handle){
2090     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2091     if (!hfp_connection) {
2092         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2093     }
2094     hfp_connection->hf_send_rrh = 1;
2095     hfp_connection->hf_send_rrh_command = '?';
2096     hfp_hf_run_for_context(hfp_connection);
2097     return ERROR_CODE_SUCCESS;
2098 }
2099 
2100 uint8_t hfp_hf_rrh_hold_call(hci_con_handle_t acl_handle){
2101     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2102     if (!hfp_connection) {
2103         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2104     }
2105     hfp_connection->hf_send_rrh = 1;
2106     hfp_connection->hf_send_rrh_command = '0';
2107     hfp_hf_run_for_context(hfp_connection);
2108     return ERROR_CODE_SUCCESS;
2109 }
2110 
2111 uint8_t hfp_hf_rrh_accept_held_call(hci_con_handle_t acl_handle){
2112     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2113     if (!hfp_connection) {
2114         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2115     }
2116     hfp_connection->hf_send_rrh = 1;
2117     hfp_connection->hf_send_rrh_command = '1';
2118     hfp_hf_run_for_context(hfp_connection);
2119     return ERROR_CODE_SUCCESS;
2120 }
2121 
2122 uint8_t hfp_hf_rrh_reject_held_call(hci_con_handle_t acl_handle){
2123     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2124     if (!hfp_connection) {
2125         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2126     }
2127     hfp_connection->hf_send_rrh = 1;
2128     hfp_connection->hf_send_rrh_command = '2';
2129     hfp_hf_run_for_context(hfp_connection);
2130     return ERROR_CODE_SUCCESS;
2131 }
2132 
2133 uint8_t hfp_hf_query_subscriber_number(hci_con_handle_t acl_handle){
2134     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2135     if (!hfp_connection) {
2136         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2137     }
2138     hfp_connection->hf_send_cnum = 1;
2139     hfp_hf_run_for_context(hfp_connection);
2140     return ERROR_CODE_SUCCESS;
2141 }
2142 
2143 uint8_t hfp_hf_set_hf_indicator(hci_con_handle_t acl_handle, int assigned_number, int value){
2144     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2145     if (!hfp_connection) {
2146         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2147     }
2148     // find index for assigned number
2149     int i;
2150     for (i = 0; i < hfp_hf_indicators_nr ; i++){
2151         if (hfp_hf_indicators[i] == assigned_number){
2152             // set value
2153             hfp_hf_indicators_value[i] = value;
2154             // mark for update
2155             if (hfp_connection->state > HFP_LIST_GENERIC_STATUS_INDICATORS){
2156                 hfp_connection->generic_status_update_bitmap |= (1<<i);
2157                 // send update
2158                 hfp_hf_run_for_context(hfp_connection);
2159             }
2160             return ERROR_CODE_SUCCESS;
2161         }
2162     }
2163     return ERROR_CODE_SUCCESS;
2164 }
2165 
2166 int hfp_hf_in_band_ringtone_active(hci_con_handle_t acl_handle){
2167     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
2168     if (!hfp_connection) {
2169         return 0;
2170     }
2171     return get_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE);
2172 }
2173 
2174 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){
2175 	if (!name){
2176 		name = hfp_hf_default_service_name;
2177 	}
2178 	hfp_create_sdp_record(service, service_record_handle, BLUETOOTH_SERVICE_CLASS_HANDSFREE, rfcomm_channel_nr, name);
2179 
2180 	// Construct SupportedFeatures for SDP bitmap:
2181 	//
2182 	// "The values of the “SupportedFeatures” bitmap given in Table 5.4 shall be the same as the values
2183 	//  of the Bits 0 to 4 of the unsolicited result code +BRSF"
2184 	//
2185 	// Wide band speech (bit 5) requires Codec negotiation
2186 	//
2187 	uint16_t sdp_features = supported_features & 0x1f;
2188 	if ( (wide_band_speech != 0) && (supported_features & (1 << HFP_HFSF_CODEC_NEGOTIATION))){
2189 		sdp_features |= 1 << 5;
2190 	}
2191 
2192     if (supported_features & (1 << HFP_HFSF_ENHANCED_VOICE_RECOGNITION_STATUS)){
2193         sdp_features |= 1 << 6;
2194     }
2195 
2196     if (supported_features & (1 << HFP_HFSF_VOICE_RECOGNITION_TEXT)){
2197         sdp_features |= 1 << 7;
2198     }
2199 
2200 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);    // Hands-Free Profile - SupportedFeatures
2201 	de_add_number(service, DE_UINT, DE_SIZE_16, sdp_features);
2202 }
2203 
2204 void hfp_hf_register_packet_handler(btstack_packet_handler_t callback){
2205 	btstack_assert(callback != NULL);
2206 
2207 	hfp_hf_callback = callback;
2208 	hfp_set_hf_callback(callback);
2209 }
2210