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