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