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