xref: /btstack/src/classic/hfp_hf.c (revision 2d66e7972be8c6b055813288eb9cd5ae46fa219e)
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 MATTHIAS
24  * RINGWALD 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 <string.h>
50 
51 #include "bluetooth_sdp.h"
52 #include "btstack_debug.h"
53 #include "btstack_event.h"
54 #include "btstack_memory.h"
55 #include "btstack_run_loop.h"
56 #include "classic/core.h"
57 #include "classic/hfp.h"
58 #include "classic/hfp_hf.h"
59 #include "classic/sdp_client_rfcomm.h"
60 #include "classic/sdp_server.h"
61 #include "classic/sdp_util.h"
62 #include "hci.h"
63 #include "hci_cmd.h"
64 #include "hci_dump.h"
65 #include "l2cap.h"
66 
67 // const
68 static const char default_hfp_hf_service_name[] = "Hands-Free unit";
69 
70 // globals
71 static btstack_packet_callback_registration_t hfp_hf_hci_event_callback_registration;
72 
73 static uint16_t hfp_supported_features = HFP_DEFAULT_HF_SUPPORTED_FEATURES;
74 static uint8_t hfp_codecs_nr;
75 static uint8_t hfp_codecs[HFP_MAX_NUM_CODECS];
76 
77 static uint8_t hfp_indicators_nr;
78 static uint8_t hfp_indicators[HFP_MAX_NUM_INDICATORS];
79 static uint32_t hfp_indicators_value[HFP_MAX_NUM_INDICATORS];
80 
81 static uint8_t hfp_hf_speaker_gain;
82 static uint8_t hfp_hf_microphone_gain;
83 
84 static btstack_packet_handler_t hfp_hf_callback;
85 
86 static hfp_call_status_t hfp_call_status;
87 static hfp_callsetup_status_t hfp_callsetup_status;
88 static hfp_callheld_status_t hfp_callheld_status;
89 
90 static char phone_number[25];
91 
92 static int has_codec_negotiation_feature(hfp_connection_t * hfp_connection){
93 	int hf = get_bit(hfp_supported_features, HFP_HFSF_CODEC_NEGOTIATION);
94 	int ag = get_bit(hfp_connection->remote_supported_features, HFP_AGSF_CODEC_NEGOTIATION);
95 	return hf && ag;
96 }
97 
98 static int has_call_waiting_and_3way_calling_feature(hfp_connection_t * hfp_connection){
99 	int hf = get_bit(hfp_supported_features, HFP_HFSF_THREE_WAY_CALLING);
100 	int ag = get_bit(hfp_connection->remote_supported_features, HFP_AGSF_THREE_WAY_CALLING);
101 	return hf && ag;
102 }
103 
104 
105 static int has_hf_indicators_feature(hfp_connection_t * hfp_connection){
106 	int hf = get_bit(hfp_supported_features, HFP_HFSF_HF_INDICATORS);
107 	int ag = get_bit(hfp_connection->remote_supported_features, HFP_AGSF_HF_INDICATORS);
108 	return hf && ag;
109 }
110 
111 
112 static hfp_connection_t * get_hfp_hf_connection_context_for_acl_handle(uint16_t handle){
113     btstack_linked_list_iterator_t it;
114     btstack_linked_list_iterator_init(&it, hfp_get_connections());
115     while (btstack_linked_list_iterator_has_next(&it)){
116         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
117         if (hfp_connection->acl_handle != handle)      continue;
118         if (hfp_connection->local_role != HFP_ROLE_HF) continue;
119         return hfp_connection;
120     }
121     return NULL;
122 }
123 
124 /* emit functinos */
125 
126 static void hfp_hf_emit_subscriber_information(btstack_packet_handler_t callback, uint8_t event_subtype, uint8_t status, uint8_t bnip_type, const char * bnip_number){
127     if (!callback) return;
128     uint8_t event[31];
129     event[0] = HCI_EVENT_HFP_META;
130     event[1] = sizeof(event) - 2;
131     event[2] = event_subtype;
132     event[3] = status;
133     event[4] = bnip_type;
134     uint16_t size = btstack_min(strlen(bnip_number), sizeof(event) - 6);
135     strncpy((char*)&event[5], bnip_number, size);
136     event[5 + size] = 0;
137     (*callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
138 }
139 
140 static void hfp_hf_emit_type_and_number(btstack_packet_handler_t callback, uint8_t event_subtype, uint8_t bnip_type, const char * bnip_number){
141     if (!callback) return;
142     uint8_t event[30];
143     event[0] = HCI_EVENT_HFP_META;
144     event[1] = sizeof(event) - 2;
145     event[2] = event_subtype;
146     event[3] = bnip_type;
147     uint16_t size = btstack_min(strlen(bnip_number), sizeof(event) - 5);
148     strncpy((char*)&event[4], bnip_number, size);
149     event[4 + size] = 0;
150     (*callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
151 }
152 
153 static void hfp_hf_emit_enhanced_call_status(btstack_packet_handler_t callback, hfp_connection_t * connection){
154     if (!callback) return;
155     uint8_t event[36];
156     int pos = 0;
157     event[pos++] = HCI_EVENT_HFP_META;
158     event[pos++] = sizeof(event) - 2;
159     event[pos++] = HFP_SUBEVENT_ENHANCED_CALL_STATUS;
160     event[pos++] = connection->clcc_idx;
161     event[pos++] = connection->clcc_dir;
162     event[pos++] = connection->clcc_status;
163     event[pos++] = connection->clcc_mode;
164     event[pos++] = connection->clcc_mpty;
165     event[pos++] = connection->bnip_type;
166     uint16_t size = btstack_min(strlen(connection->bnip_number), sizeof(event) - pos);
167     strncpy((char*)&event[pos], connection->bnip_number, size);
168     pos += size;
169     event[pos++] = 0;
170     (*callback)(HCI_EVENT_PACKET, 0, event, pos);
171 }
172 
173 
174 static void hfp_emit_ag_indicator_event(btstack_packet_handler_t callback, hfp_ag_indicator_t indicator){
175 	if (!callback) return;
176 	uint8_t event[10+HFP_MAX_INDICATOR_DESC_SIZE+1];
177 	int pos = 0;
178 	event[pos++] = HCI_EVENT_HFP_META;
179 	event[pos++] = sizeof(event) - 2;
180 	event[pos++] = HFP_SUBEVENT_AG_INDICATOR_STATUS_CHANGED;
181 	event[pos++] = indicator.index;
182 	event[pos++] = indicator.status;
183 	event[pos++] = indicator.min_range;
184 	event[pos++] = indicator.max_range;
185 	event[pos++] = indicator.mandatory;
186 	event[pos++] = indicator.enabled;
187 	event[pos++] = indicator.status_changed;
188 	strncpy((char*)&event[pos], indicator.name, HFP_MAX_INDICATOR_DESC_SIZE);
189 	pos += HFP_MAX_INDICATOR_DESC_SIZE;
190 	event[pos] = 0;
191 	(*callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
192 }
193 
194 static void hfp_emit_network_operator_event(btstack_packet_handler_t callback, hfp_network_opearator_t network_operator){
195 	if (!callback) return;
196 	uint8_t event[5+HFP_MAX_NETWORK_OPERATOR_NAME_SIZE+1];
197 	event[0] = HCI_EVENT_HFP_META;
198 	event[1] = sizeof(event) - 2;
199 	event[2] = HFP_SUBEVENT_NETWORK_OPERATOR_CHANGED;
200 	event[3] = network_operator.mode;
201 	event[4] = network_operator.format;
202 	strncpy((char*)&event[5], network_operator.name, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE);
203 	event[5+HFP_MAX_NETWORK_OPERATOR_NAME_SIZE] = 0;
204 	(*callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
205 }
206 
207 /* send commands */
208 
209 static inline int hfp_hf_send_cmd(uint16_t cid, const char * cmd){
210     char buffer[20];
211     snprintf(buffer, sizeof(buffer), "AT%s\r\n", cmd);
212     return send_str_over_rfcomm(cid, buffer);
213 }
214 
215 static inline int hfp_hf_send_cmd_with_mark(uint16_t cid, const char * cmd, const char * mark){
216     char buffer[20];
217     snprintf(buffer, sizeof(buffer), "AT%s%s\r\n", cmd, mark);
218     return send_str_over_rfcomm(cid, buffer);
219 }
220 
221 static inline int hfp_hf_send_cmd_with_int(uint16_t cid, const char * cmd, uint16_t value){
222     char buffer[40];
223     snprintf(buffer, sizeof(buffer), "AT%s=%d\r\n", cmd, value);
224     return send_str_over_rfcomm(cid, buffer);
225 }
226 
227 static int hfp_hf_cmd_notify_on_codecs(uint16_t cid){
228     char buffer[30];
229     const int size = sizeof(buffer);
230     int offset = snprintf(buffer, size, "AT%s=", HFP_AVAILABLE_CODECS);
231     offset += join(buffer+offset, size-offset, hfp_codecs, hfp_codecs_nr);
232     offset += snprintf(buffer+offset, size-offset, "\r\n");
233     return send_str_over_rfcomm(cid, buffer);
234 }
235 
236 static int hfp_hf_cmd_activate_status_update_for_ag_indicator(uint16_t cid, uint32_t indicators_status, int indicators_nr){
237     char buffer[50];
238     const int size = sizeof(buffer);
239     int offset = snprintf(buffer, size, "AT%s=", HFP_UPDATE_ENABLE_STATUS_FOR_INDIVIDUAL_AG_INDICATORS);
240     offset += join_bitmap(buffer+offset, size-offset, indicators_status, indicators_nr);
241     offset += snprintf(buffer+offset, size-offset, "\r\n");
242     return send_str_over_rfcomm(cid, buffer);
243 }
244 
245 static int hfp_hf_cmd_list_supported_generic_status_indicators(uint16_t cid){
246     char buffer[30];
247     const int size = sizeof(buffer);
248     int offset = snprintf(buffer, size, "AT%s=", HFP_GENERIC_STATUS_INDICATOR);
249     offset += join(buffer+offset, size-offset, hfp_indicators, hfp_indicators_nr);
250     offset += snprintf(buffer+offset, size-offset, "\r\n");
251     return send_str_over_rfcomm(cid, buffer);
252 }
253 
254 static int hfp_hf_cmd_activate_status_update_for_all_ag_indicators(uint16_t cid, uint8_t activate){
255     char buffer[20];
256     snprintf(buffer, sizeof(buffer), "AT%s=3,0,0,%d\r\n", HFP_ENABLE_STATUS_UPDATE_FOR_AG_INDICATORS, activate);
257     return send_str_over_rfcomm(cid, buffer);
258 }
259 
260 static int hfp_hf_initiate_outgoing_call_cmd(uint16_t cid){
261     char buffer[40];
262     snprintf(buffer, sizeof(buffer), "%s%s;\r\n", HFP_CALL_PHONE_NUMBER, phone_number);
263     return send_str_over_rfcomm(cid, buffer);
264 }
265 
266 static int hfp_hf_send_memory_dial_cmd(uint16_t cid, int memory_id){
267     char buffer[40];
268     snprintf(buffer, sizeof(buffer), "%s>%d;\r\n", HFP_CALL_PHONE_NUMBER, memory_id);
269     return send_str_over_rfcomm(cid, buffer);
270 }
271 
272 static int hfp_hf_send_chld(uint16_t cid, unsigned int number){
273     char buffer[40];
274     snprintf(buffer, sizeof(buffer), "AT%s=%u\r\n", HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES, number);
275     return send_str_over_rfcomm(cid, buffer);
276 }
277 
278 static int hfp_hf_send_dtmf(uint16_t cid, char code){
279     char buffer[20];
280     snprintf(buffer, sizeof(buffer), "AT%s=%c\r\n", HFP_TRANSMIT_DTMF_CODES, code);
281     return send_str_over_rfcomm(cid, buffer);
282 }
283 
284 static int hfp_hf_cmd_ata(uint16_t cid){
285     return send_str_over_rfcomm(cid, (char *) "ATA\r\n");
286 }
287 
288 static int hfp_hf_cmd_exchange_supported_features(uint16_t cid){
289     return hfp_hf_send_cmd_with_int(cid, HFP_SUPPORTED_FEATURES, hfp_supported_features);
290 }
291 
292 static int hfp_hf_cmd_retrieve_indicators(uint16_t cid){
293     return hfp_hf_send_cmd_with_mark(cid, HFP_INDICATOR, "=?");
294 }
295 
296 static int hfp_hf_cmd_retrieve_indicators_status(uint16_t cid){
297     return hfp_hf_send_cmd_with_mark(cid, HFP_INDICATOR, "?");
298 }
299 
300 static int hfp_hf_cmd_retrieve_can_hold_call(uint16_t cid){
301     return hfp_hf_send_cmd_with_mark(cid, HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES, "=?");
302 }
303 
304 static int hfp_hf_cmd_retrieve_supported_generic_status_indicators(uint16_t cid){
305     return hfp_hf_send_cmd_with_mark(cid, HFP_GENERIC_STATUS_INDICATOR, "=?");
306 }
307 
308 static int hfp_hf_cmd_list_initital_supported_generic_status_indicators(uint16_t cid){
309     return hfp_hf_send_cmd_with_mark(cid, HFP_GENERIC_STATUS_INDICATOR, "?");
310 }
311 
312 static int hfp_hf_cmd_query_operator_name_format(uint16_t cid){
313     return hfp_hf_send_cmd_with_mark(cid, HFP_QUERY_OPERATOR_SELECTION, "=3,0");
314 }
315 
316 static int hfp_hf_cmd_query_operator_name(uint16_t cid){
317     return hfp_hf_send_cmd_with_mark(cid, HFP_QUERY_OPERATOR_SELECTION, "?");
318 }
319 
320 static int hfp_hf_cmd_trigger_codec_connection_setup(uint16_t cid){
321     return hfp_hf_send_cmd(cid, HFP_TRIGGER_CODEC_CONNECTION_SETUP);
322 }
323 
324 static int hfp_hf_set_microphone_gain_cmd(uint16_t cid, int gain){
325     return hfp_hf_send_cmd_with_int(cid, HFP_SET_MICROPHONE_GAIN, gain);
326 }
327 
328 static int hfp_hf_set_speaker_gain_cmd(uint16_t cid, int gain){
329     return hfp_hf_send_cmd_with_int(cid, HFP_SET_SPEAKER_GAIN, gain);
330 }
331 
332 static int hfp_hf_set_calling_line_notification_cmd(uint16_t cid, uint8_t activate){
333     return hfp_hf_send_cmd_with_int(cid, HFP_ENABLE_CLIP, activate);
334 }
335 
336 static int hfp_hf_set_echo_canceling_and_noise_reduction_cmd(uint16_t cid, uint8_t activate){
337     return hfp_hf_send_cmd_with_int(cid, HFP_TURN_OFF_EC_AND_NR, activate);
338 }
339 
340 static int hfp_hf_set_voice_recognition_notification_cmd(uint16_t cid, uint8_t activate){
341     return hfp_hf_send_cmd_with_int(cid, HFP_ACTIVATE_VOICE_RECOGNITION, activate);
342 }
343 
344 static int hfp_hf_set_call_waiting_notification_cmd(uint16_t cid, uint8_t activate){
345     return hfp_hf_send_cmd_with_int(cid, HFP_ENABLE_CALL_WAITING_NOTIFICATION, activate);
346 }
347 
348 static int hfp_hf_cmd_confirm_codec(uint16_t cid, uint8_t codec){
349     return hfp_hf_send_cmd_with_int(cid, HFP_CONFIRM_COMMON_CODEC, codec);
350 }
351 
352 static int hfp_hf_cmd_enable_extended_audio_gateway_error_report(uint16_t cid, uint8_t enable){
353     return hfp_hf_send_cmd_with_int(cid, HFP_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR, enable);
354 }
355 
356 static int hfp_hf_send_redial_last_number_cmd(uint16_t cid){
357     return hfp_hf_send_cmd(cid, HFP_REDIAL_LAST_NUMBER);
358 }
359 
360 static int hfp_hf_send_chup(uint16_t cid){
361     return hfp_hf_send_cmd(cid, HFP_HANG_UP_CALL);
362 }
363 
364 static int hfp_hf_send_binp(uint16_t cid){
365     return hfp_hf_send_cmd_with_mark(cid, HFP_PHONE_NUMBER_FOR_VOICE_TAG, "=1");
366 }
367 
368 static int hfp_hf_send_clcc(uint16_t cid){
369     return hfp_hf_send_cmd(cid, HFP_LIST_CURRENT_CALLS);
370 }
371 
372 /* state machines */
373 
374 static int hfp_hf_run_for_context_service_level_connection(hfp_connection_t * hfp_connection){
375     if (hfp_connection->state >= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) return 0;
376     if (hfp_connection->ok_pending) return 0;
377     int done = 1;
378 
379     switch (hfp_connection->state){
380         case HFP_EXCHANGE_SUPPORTED_FEATURES:
381             hfp_hf_drop_mSBC_if_eSCO_not_supported(hfp_codecs, &hfp_codecs_nr);
382             hfp_connection->state = HFP_W4_EXCHANGE_SUPPORTED_FEATURES;
383             hfp_hf_cmd_exchange_supported_features(hfp_connection->rfcomm_cid);
384             break;
385         case HFP_NOTIFY_ON_CODECS:
386             hfp_connection->state = HFP_W4_NOTIFY_ON_CODECS;
387             hfp_hf_cmd_notify_on_codecs(hfp_connection->rfcomm_cid);
388             break;
389         case HFP_RETRIEVE_INDICATORS:
390             hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS;
391             hfp_hf_cmd_retrieve_indicators(hfp_connection->rfcomm_cid);
392             break;
393         case HFP_RETRIEVE_INDICATORS_STATUS:
394             hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS_STATUS;
395             hfp_hf_cmd_retrieve_indicators_status(hfp_connection->rfcomm_cid);
396             break;
397         case HFP_ENABLE_INDICATORS_STATUS_UPDATE:
398             hfp_connection->state = HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE;
399             hfp_hf_cmd_activate_status_update_for_all_ag_indicators(hfp_connection->rfcomm_cid, 1);
400             break;
401         case HFP_RETRIEVE_CAN_HOLD_CALL:
402             hfp_connection->state = HFP_W4_RETRIEVE_CAN_HOLD_CALL;
403             hfp_hf_cmd_retrieve_can_hold_call(hfp_connection->rfcomm_cid);
404             break;
405         case HFP_LIST_GENERIC_STATUS_INDICATORS:
406             hfp_connection->state = HFP_W4_LIST_GENERIC_STATUS_INDICATORS;
407             hfp_hf_cmd_list_supported_generic_status_indicators(hfp_connection->rfcomm_cid);
408             break;
409         case HFP_RETRIEVE_GENERIC_STATUS_INDICATORS:
410             hfp_connection->state = HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS;
411             hfp_hf_cmd_retrieve_supported_generic_status_indicators(hfp_connection->rfcomm_cid);
412             break;
413         case HFP_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS:
414             hfp_connection->state = HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS;
415             hfp_hf_cmd_list_initital_supported_generic_status_indicators(hfp_connection->rfcomm_cid);
416             break;
417         default:
418             done = 0;
419             break;
420     }
421     return done;
422 }
423 
424 
425 static int hfp_hf_run_for_context_service_level_connection_queries(hfp_connection_t * hfp_connection){
426     if (hfp_connection->state != HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) return 0;
427     if (hfp_connection->ok_pending) return 0;
428 
429     int done = 0;
430     if (hfp_connection->enable_status_update_for_ag_indicators != 0xFF){
431         hfp_connection->ok_pending = 1;
432         done = 1;
433         hfp_hf_cmd_activate_status_update_for_all_ag_indicators(hfp_connection->rfcomm_cid, hfp_connection->enable_status_update_for_ag_indicators);
434         return done;
435     };
436     if (hfp_connection->change_status_update_for_individual_ag_indicators){
437         hfp_connection->ok_pending = 1;
438         done = 1;
439         hfp_hf_cmd_activate_status_update_for_ag_indicator(hfp_connection->rfcomm_cid,
440                 hfp_connection->ag_indicators_status_update_bitmap,
441                 hfp_connection->ag_indicators_nr);
442         return done;
443     }
444 
445     switch (hfp_connection->hf_query_operator_state){
446         case HFP_HF_QUERY_OPERATOR_SET_FORMAT:
447             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_W4_SET_FORMAT_OK;
448             hfp_connection->ok_pending = 1;
449             hfp_hf_cmd_query_operator_name_format(hfp_connection->rfcomm_cid);
450             return 1;
451         case HFP_HF_QUERY_OPERATOR_SEND_QUERY:
452             hfp_connection->hf_query_operator_state = HPF_HF_QUERY_OPERATOR_W4_RESULT;
453             hfp_connection->ok_pending = 1;
454             hfp_hf_cmd_query_operator_name(hfp_connection->rfcomm_cid);
455             return 1;
456         default:
457             break;
458     }
459 
460     if (hfp_connection->enable_extended_audio_gateway_error_report){
461         hfp_connection->ok_pending = 1;
462         done = 1;
463         hfp_hf_cmd_enable_extended_audio_gateway_error_report(hfp_connection->rfcomm_cid, hfp_connection->enable_extended_audio_gateway_error_report);
464         return done;
465     }
466 
467     return done;
468 }
469 
470 static int codecs_exchange_state_machine(hfp_connection_t * hfp_connection){
471 
472     if (hfp_connection->ok_pending) return 0;
473 
474     if (hfp_connection->trigger_codec_exchange){
475 		hfp_connection->trigger_codec_exchange = 0;
476 
477 		hfp_connection->ok_pending = 1;
478 		hfp_hf_cmd_trigger_codec_connection_setup(hfp_connection->rfcomm_cid);
479 		return 1;
480     }
481 
482     if (hfp_connection->hf_send_codec_confirm){
483 		hfp_connection->hf_send_codec_confirm = false;
484 
485 		hfp_connection->ok_pending = 1;
486 		hfp_hf_cmd_confirm_codec(hfp_connection->rfcomm_cid, hfp_connection->codec_confirmed);
487 		return 1;
488     }
489 
490     if (hfp_connection->hf_send_supported_codecs){
491 		hfp_connection->hf_send_supported_codecs = false;
492 
493 		hfp_connection->ok_pending = 1;
494 		hfp_hf_cmd_notify_on_codecs(hfp_connection->rfcomm_cid);
495 		return 1;
496     }
497 
498     return 0;
499 }
500 
501 static int hfp_hf_run_for_audio_connection(hfp_connection_t * hfp_connection){
502     if ((hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) ||
503         (hfp_connection->state > HFP_W2_DISCONNECT_SCO)) return 0;
504 
505     if (hfp_connection->release_audio_connection){
506         hfp_connection->state = HFP_W4_SCO_DISCONNECTED;
507         hfp_connection->release_audio_connection = 0;
508         gap_disconnect(hfp_connection->sco_handle);
509         return 1;
510     }
511 
512     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
513 
514     // run codecs exchange
515     int done = codecs_exchange_state_machine(hfp_connection);
516     if (done) return 1;
517 
518     if (hfp_connection->codecs_state != HFP_CODECS_EXCHANGED) return 0;
519     if (hfp_connection->establish_audio_connection){
520         hfp_connection->state = HFP_W4_SCO_CONNECTED;
521         hfp_connection->establish_audio_connection = 0;
522         hfp_setup_synchronous_connection(hfp_connection);
523         return 1;
524     }
525 
526     return 0;
527 }
528 
529 
530 static int call_setup_state_machine(hfp_connection_t * hfp_connection){
531 
532 	if (hfp_connection->ok_pending) return 0;
533 
534     if (hfp_connection->hf_answer_incoming_call){
535         hfp_hf_cmd_ata(hfp_connection->rfcomm_cid);
536         hfp_connection->hf_answer_incoming_call = 0;
537         return 1;
538     }
539     return 0;
540 }
541 
542 static void hfp_hf_run_for_context(hfp_connection_t * hfp_connection){
543 
544 	btstack_assert(hfp_connection != NULL);
545 	btstack_assert(hfp_connection->local_role == HFP_ROLE_HF);
546 
547 	// during SDP query, RFCOMM CID is not set
548 	if (hfp_connection->rfcomm_cid == 0) return;
549 
550 	// assert command could be sent
551 	if (hci_can_send_command_packet_now() == 0) return;
552 
553 #ifdef ENABLE_CC256X_ASSISTED_HFP
554     // WBS Disassociate
555     if (hfp_connection->cc256x_send_wbs_disassociate){
556         hfp_connection->cc256x_send_wbs_disassociate = false;
557         hci_send_cmd(&hci_ti_wbs_disassociate);
558         return;
559     }
560     // Write Codec Config
561     if (hfp_connection->cc256x_send_write_codec_config){
562         hfp_connection->cc256x_send_write_codec_config = false;
563         hfp_cc256x_write_codec_config(hfp_connection);
564         return;
565     }
566     // WBS Associate
567     if (hfp_connection->cc256x_send_wbs_associate){
568         hfp_connection->cc256x_send_wbs_associate = false;
569         hci_send_cmd(&hci_ti_wbs_associate, hfp_connection->acl_handle);
570         return;
571     }
572 #endif
573 #ifdef ENABLE_BCM_PCM_WBS
574     // Enable WBS
575     if (hfp_connection->bcm_send_enable_wbs){
576         hfp_connection->bcm_send_enable_wbs = false;
577         hci_send_cmd(&hci_bcm_enable_wbs, 1, 2);
578         return;
579     }
580     // Write I2S/PCM params
581     if (hfp_connection->bcm_send_write_i2spcm_interface_param){
582         hfp_connection->bcm_send_write_i2spcm_interface_param = false;
583         hfp_bcm_write_i2spcm_interface_param(hfp_connection);
584         return;
585     }
586     // Disable WBS
587     if (hfp_connection->bcm_send_disable_wbs){
588         hfp_connection->bcm_send_disable_wbs = false;
589         hci_send_cmd(&hci_bcm_enable_wbs, 0, 2);
590         return;
591     }
592 #endif
593 #if defined (ENABLE_CC256X_ASSISTED_HFP) || defined (ENABLE_BCM_PCM_WBS)
594     if (hfp_connection->state == HFP_W4_WBS_SHUTDOWN){
595         hfp_finalize_connection_context(hfp_connection);
596         return;
597     }
598 #endif
599 
600     if (hfp_connection->hf_accept_sco){
601 
602         bool eSCO = hfp_connection->hf_accept_sco == 2;
603         hfp_connection->hf_accept_sco = 0;
604 
605         // notify about codec selection if not done already
606         if (hfp_connection->negotiated_codec == 0){
607             hfp_connection->negotiated_codec = HFP_CODEC_CVSD;
608         }
609 
610         // remote supported feature eSCO is set if link type is eSCO
611         // eSCO: S4 - max latency == transmission interval = 0x000c == 12 ms,
612         uint16_t max_latency;
613         uint8_t  retransmission_effort;
614         uint16_t packet_types;
615 
616         if (eSCO && hci_extended_sco_link_supported() && hci_remote_esco_supported(hfp_connection->acl_handle)){
617             max_latency = 0x000c;
618             retransmission_effort = 0x02;
619             // eSCO: EV3 and 2-EV3
620             packet_types = 0x0048;
621         } else {
622             max_latency = 0xffff;
623             retransmission_effort = 0xff;
624             // sco: HV1 and HV3
625             packet_types = 0x005;
626         }
627 
628         // mSBC only allows for transparent data
629         uint16_t sco_voice_setting = hci_get_sco_voice_setting();
630         if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
631 #ifdef ENABLE_BCM_PCM_WBS
632             sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
633 #else
634             sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
635 #endif
636         }
637 
638         // filter packet types
639         packet_types &= hfp_get_sco_packet_types();
640 
641         // bits 6-9 are 'don't allow'
642         packet_types ^= 0x3c0;
643 
644         log_info("HFP: sending hci_accept_connection_request, packet types 0x%04x, sco_voice_setting 0x%02x", packet_types, sco_voice_setting);
645         hci_send_cmd(&hci_accept_synchronous_connection, hfp_connection->remote_addr, 8000, 8000, max_latency,
646                         sco_voice_setting, retransmission_effort, packet_types);
647         return;
648     }
649 
650     if (!rfcomm_can_send_packet_now(hfp_connection->rfcomm_cid)) {
651         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
652         return;
653     }
654     int done = hfp_hf_run_for_context_service_level_connection(hfp_connection);
655     if (!done){
656         done = hfp_hf_run_for_context_service_level_connection_queries(hfp_connection);
657     }
658     if (!done){
659         done = hfp_hf_run_for_audio_connection(hfp_connection);
660     }
661     if (!done){
662         done = call_setup_state_machine(hfp_connection);
663     }
664 
665     // don't send a new command while ok still pending
666     if (hfp_connection->ok_pending) return;
667 
668     if (hfp_connection->send_microphone_gain){
669         hfp_connection->send_microphone_gain = 0;
670         hfp_connection->ok_pending = 1;
671         hfp_hf_set_microphone_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->microphone_gain);
672         return;
673     }
674 
675     if (hfp_connection->send_speaker_gain){
676         hfp_connection->send_speaker_gain = 0;
677         hfp_connection->ok_pending = 1;
678         hfp_hf_set_speaker_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->speaker_gain);
679         return;
680     }
681 
682     if (hfp_connection->hf_deactivate_calling_line_notification){
683         hfp_connection->hf_deactivate_calling_line_notification = 0;
684         hfp_connection->ok_pending = 1;
685         hfp_hf_set_calling_line_notification_cmd(hfp_connection->rfcomm_cid, 0);
686         return;
687     }
688 
689     if (hfp_connection->hf_activate_calling_line_notification){
690         hfp_connection->hf_activate_calling_line_notification = 0;
691         hfp_connection->ok_pending = 1;
692         hfp_hf_set_calling_line_notification_cmd(hfp_connection->rfcomm_cid, 1);
693         return;
694     }
695 
696     if (hfp_connection->hf_deactivate_echo_canceling_and_noise_reduction){
697         hfp_connection->hf_deactivate_echo_canceling_and_noise_reduction = 0;
698         hfp_connection->ok_pending = 1;
699         hfp_hf_set_echo_canceling_and_noise_reduction_cmd(hfp_connection->rfcomm_cid, 0);
700         return;
701     }
702 
703     if (hfp_connection->hf_activate_echo_canceling_and_noise_reduction){
704         hfp_connection->hf_activate_echo_canceling_and_noise_reduction = 0;
705         hfp_connection->ok_pending = 1;
706         hfp_hf_set_echo_canceling_and_noise_reduction_cmd(hfp_connection->rfcomm_cid, 1);
707         return;
708     }
709 
710     if (hfp_connection->hf_deactivate_voice_recognition_notification){
711         hfp_connection->hf_deactivate_voice_recognition_notification = 0;
712         hfp_connection->ok_pending = 1;
713         hfp_hf_set_voice_recognition_notification_cmd(hfp_connection->rfcomm_cid, 0);
714         return;
715     }
716 
717     if (hfp_connection->hf_activate_voice_recognition_notification){
718         hfp_connection->hf_activate_voice_recognition_notification = 0;
719         hfp_connection->ok_pending = 1;
720         hfp_hf_set_voice_recognition_notification_cmd(hfp_connection->rfcomm_cid, 1);
721         return;
722     }
723 
724 
725     if (hfp_connection->hf_deactivate_call_waiting_notification){
726         hfp_connection->hf_deactivate_call_waiting_notification = 0;
727         hfp_connection->ok_pending = 1;
728         hfp_hf_set_call_waiting_notification_cmd(hfp_connection->rfcomm_cid, 0);
729         return;
730     }
731 
732     if (hfp_connection->hf_activate_call_waiting_notification){
733         hfp_connection->hf_activate_call_waiting_notification = 0;
734         hfp_connection->ok_pending = 1;
735         hfp_hf_set_call_waiting_notification_cmd(hfp_connection->rfcomm_cid, 1);
736         return;
737     }
738 
739     if (hfp_connection->hf_initiate_outgoing_call){
740         hfp_connection->hf_initiate_outgoing_call = 0;
741         hfp_connection->ok_pending = 1;
742         hfp_hf_initiate_outgoing_call_cmd(hfp_connection->rfcomm_cid);
743         return;
744     }
745 
746     if (hfp_connection->hf_initiate_memory_dialing){
747         hfp_connection->hf_initiate_memory_dialing = 0;
748         hfp_connection->ok_pending = 1;
749         hfp_hf_send_memory_dial_cmd(hfp_connection->rfcomm_cid, hfp_connection->memory_id);
750         return;
751     }
752 
753     if (hfp_connection->hf_initiate_redial_last_number){
754         hfp_connection->hf_initiate_redial_last_number = 0;
755         hfp_connection->ok_pending = 1;
756         hfp_hf_send_redial_last_number_cmd(hfp_connection->rfcomm_cid);
757         return;
758     }
759 
760     if (hfp_connection->hf_send_chup){
761         hfp_connection->hf_send_chup = 0;
762         hfp_connection->ok_pending = 1;
763         hfp_hf_send_chup(hfp_connection->rfcomm_cid);
764         return;
765     }
766 
767     if (hfp_connection->hf_send_chld_0){
768         hfp_connection->hf_send_chld_0 = 0;
769         hfp_connection->ok_pending = 1;
770         hfp_hf_send_chld(hfp_connection->rfcomm_cid, 0);
771         return;
772     }
773 
774     if (hfp_connection->hf_send_chld_1){
775         hfp_connection->hf_send_chld_1 = 0;
776         hfp_connection->ok_pending = 1;
777         hfp_hf_send_chld(hfp_connection->rfcomm_cid, 1);
778         return;
779     }
780 
781     if (hfp_connection->hf_send_chld_2){
782         hfp_connection->hf_send_chld_2 = 0;
783         hfp_connection->ok_pending = 1;
784         hfp_hf_send_chld(hfp_connection->rfcomm_cid, 2);
785         return;
786     }
787 
788     if (hfp_connection->hf_send_chld_3){
789         hfp_connection->hf_send_chld_3 = 0;
790         hfp_connection->ok_pending = 1;
791         hfp_hf_send_chld(hfp_connection->rfcomm_cid, 3);
792         return;
793     }
794 
795     if (hfp_connection->hf_send_chld_4){
796         hfp_connection->hf_send_chld_4 = 0;
797         hfp_connection->ok_pending = 1;
798         hfp_hf_send_chld(hfp_connection->rfcomm_cid, 4);
799         return;
800     }
801 
802     if (hfp_connection->hf_send_chld_x){
803         hfp_connection->hf_send_chld_x = 0;
804         hfp_connection->ok_pending = 1;
805         hfp_hf_send_chld(hfp_connection->rfcomm_cid, hfp_connection->hf_send_chld_x_index);
806         return;
807     }
808 
809     if (hfp_connection->hf_send_dtmf_code){
810         char code = hfp_connection->hf_send_dtmf_code;
811         hfp_connection->hf_send_dtmf_code = 0;
812         hfp_connection->ok_pending = 1;
813         hfp_hf_send_dtmf(hfp_connection->rfcomm_cid, code);
814         return;
815     }
816 
817     if (hfp_connection->hf_send_binp){
818         hfp_connection->hf_send_binp = 0;
819         hfp_connection->ok_pending = 1;
820         hfp_hf_send_binp(hfp_connection->rfcomm_cid);
821         return;
822     }
823 
824     if (hfp_connection->hf_send_clcc){
825         hfp_connection->hf_send_clcc = 0;
826         hfp_connection->ok_pending = 1;
827         hfp_hf_send_clcc(hfp_connection->rfcomm_cid);
828         return;
829     }
830 
831     if (hfp_connection->hf_send_rrh){
832         hfp_connection->hf_send_rrh = 0;
833         char buffer[20];
834         switch (hfp_connection->hf_send_rrh_command){
835             case '?':
836                 snprintf(buffer, sizeof(buffer), "AT%s?\r\n",
837                          HFP_RESPONSE_AND_HOLD);
838                 buffer[sizeof(buffer) - 1] = 0;
839                 send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
840                 return;
841             case '0':
842             case '1':
843             case '2':
844                 snprintf(buffer, sizeof(buffer), "AT%s=%c\r\n",
845                          HFP_RESPONSE_AND_HOLD,
846                          hfp_connection->hf_send_rrh_command);
847                 buffer[sizeof(buffer) - 1] = 0;
848                 send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
849                 return;
850             default:
851                 break;
852         }
853         return;
854     }
855 
856     if (hfp_connection->hf_send_cnum){
857         hfp_connection->hf_send_cnum = 0;
858         char buffer[20];
859         snprintf(buffer, sizeof(buffer), "AT%s\r\n",
860                  HFP_SUBSCRIBER_NUMBER_INFORMATION);
861         buffer[sizeof(buffer) - 1] = 0;
862         send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
863         return;
864     }
865 
866     // update HF indicators
867     if (hfp_connection->generic_status_update_bitmap){
868         int i;
869         for (i=0;i<hfp_indicators_nr;i++){
870             if (get_bit(hfp_connection->generic_status_update_bitmap, i)){
871                 if (hfp_connection->generic_status_indicators[i].state){
872                     hfp_connection->ok_pending = 1;
873                     hfp_connection->generic_status_update_bitmap = store_bit(hfp_connection->generic_status_update_bitmap, i, 0);
874                     char buffer[30];
875                     snprintf(buffer, sizeof(buffer), "AT%s=%u,%u\r\n",
876                              HFP_TRANSFER_HF_INDICATOR_STATUS,
877                              hfp_indicators[i],
878                              (unsigned int)hfp_indicators_value[i]);
879                     buffer[sizeof(buffer) - 1] = 0;
880                     send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
881                 } else {
882                     log_info("Not sending HF indicator %u as it is disabled", hfp_indicators[i]);
883                 }
884                 return;
885             }
886         }
887     }
888 
889     if (done) return;
890     // deal with disconnect
891     switch (hfp_connection->state){
892         case HFP_W2_DISCONNECT_RFCOMM:
893             hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED;
894             rfcomm_disconnect(hfp_connection->rfcomm_cid);
895             break;
896 
897         default:
898             break;
899     }
900 }
901 
902 static void hfp_ag_slc_established(hfp_connection_t * hfp_connection){
903     hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
904 
905     hfp_emit_slc_connection_event(hfp_connection, 0, hfp_connection->acl_handle, hfp_connection->remote_addr);
906 
907     // restore volume settings
908     hfp_connection->speaker_gain = hfp_hf_speaker_gain;
909     hfp_connection->send_speaker_gain = 1;
910     hfp_emit_event(hfp_connection, HFP_SUBEVENT_SPEAKER_VOLUME, hfp_hf_speaker_gain);
911     hfp_connection->microphone_gain = hfp_hf_microphone_gain;
912     hfp_connection->send_microphone_gain = 1;
913     hfp_emit_event(hfp_connection, HFP_SUBEVENT_MICROPHONE_VOLUME, hfp_hf_microphone_gain);
914     // enable all indicators
915     int i;
916     for (i=0;i<hfp_indicators_nr;i++){
917         hfp_connection->generic_status_indicators[i].uuid = hfp_indicators[i];
918         hfp_connection->generic_status_indicators[i].state = 1;
919     }
920 }
921 
922 static void hfp_hf_handle_suggested_codec(hfp_connection_t * hfp_connection){
923 	if (hfp_supports_codec(hfp_connection->suggested_codec, hfp_codecs_nr, hfp_codecs)){
924 		// Codec supported, confirm
925 		hfp_connection->negotiated_codec = hfp_connection->suggested_codec;
926 		hfp_connection->codec_confirmed = hfp_connection->suggested_codec;
927 		log_info("hfp: codec confirmed: %s", (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? "mSBC" : "CVSD");
928 		hfp_connection->codecs_state = HFP_CODECS_HF_CONFIRMED_CODEC;
929 
930 		hfp_connection->hf_send_codec_confirm = true;
931 	} else {
932 		// Codec not supported, send supported codecs
933 		hfp_connection->codec_confirmed = 0;
934 		hfp_connection->suggested_codec = 0;
935 		hfp_connection->negotiated_codec = 0;
936 		hfp_connection->codecs_state = HFP_CODECS_W4_AG_COMMON_CODEC;
937 
938 		hfp_connection->hf_send_supported_codecs = true;
939 	}
940 }
941 
942 static void hfp_hf_switch_on_ok(hfp_connection_t *hfp_connection){
943     hfp_connection->ok_pending = 0;
944     switch (hfp_connection->state){
945         case HFP_W4_EXCHANGE_SUPPORTED_FEATURES:
946             if (has_codec_negotiation_feature(hfp_connection)){
947                 hfp_connection->state = HFP_NOTIFY_ON_CODECS;
948                 break;
949             }
950             hfp_connection->state = HFP_RETRIEVE_INDICATORS;
951             break;
952 
953         case HFP_W4_NOTIFY_ON_CODECS:
954             hfp_connection->state = HFP_RETRIEVE_INDICATORS;
955             break;
956 
957         case HFP_W4_RETRIEVE_INDICATORS:
958             hfp_connection->state = HFP_RETRIEVE_INDICATORS_STATUS;
959             break;
960 
961         case HFP_W4_RETRIEVE_INDICATORS_STATUS:
962             hfp_connection->state = HFP_ENABLE_INDICATORS_STATUS_UPDATE;
963             break;
964 
965         case HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE:
966             if (has_call_waiting_and_3way_calling_feature(hfp_connection)){
967                 hfp_connection->state = HFP_RETRIEVE_CAN_HOLD_CALL;
968                 break;
969             }
970             if (has_hf_indicators_feature(hfp_connection)){
971                 hfp_connection->state = HFP_LIST_GENERIC_STATUS_INDICATORS;
972                 break;
973             }
974             hfp_ag_slc_established(hfp_connection);
975             break;
976 
977         case HFP_W4_RETRIEVE_CAN_HOLD_CALL:
978             if (has_hf_indicators_feature(hfp_connection)){
979                 hfp_connection->state = HFP_LIST_GENERIC_STATUS_INDICATORS;
980                 break;
981             }
982             hfp_ag_slc_established(hfp_connection);
983             break;
984 
985         case HFP_W4_LIST_GENERIC_STATUS_INDICATORS:
986             hfp_connection->state = HFP_RETRIEVE_GENERIC_STATUS_INDICATORS;
987             break;
988 
989         case HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS:
990             hfp_connection->state = HFP_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS;
991             break;
992 
993         case HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS:
994             hfp_ag_slc_established(hfp_connection);
995             break;
996         case HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED:
997             if (hfp_connection->enable_status_update_for_ag_indicators != 0xFF){
998                 hfp_connection->enable_status_update_for_ag_indicators = 0xFF;
999                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_COMPLETE, 0);
1000                 break;
1001             }
1002 
1003             if (hfp_connection->change_status_update_for_individual_ag_indicators == 1){
1004                 hfp_connection->change_status_update_for_individual_ag_indicators = 0;
1005                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_COMPLETE, 0);
1006                 break;
1007             }
1008 
1009             switch (hfp_connection->hf_query_operator_state){
1010                 case HFP_HF_QUERY_OPERATOR_W4_SET_FORMAT_OK:
1011                     hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_SEND_QUERY;
1012                     break;
1013                 case HPF_HF_QUERY_OPERATOR_W4_RESULT:
1014                     hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_FORMAT_SET;
1015                     hfp_emit_network_operator_event(hfp_hf_callback, hfp_connection->network_operator);
1016                     break;
1017                 default:
1018                     break;
1019             }
1020 
1021             if (hfp_connection->enable_extended_audio_gateway_error_report){
1022                 hfp_connection->enable_extended_audio_gateway_error_report = 0;
1023                 break;
1024             }
1025 
1026             switch (hfp_connection->codecs_state){
1027                 case HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE:
1028                     hfp_connection->codecs_state = HFP_CODECS_W4_AG_COMMON_CODEC;
1029                     break;
1030                 case HFP_CODECS_HF_CONFIRMED_CODEC:
1031                     hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
1032                     break;
1033                 default:
1034                     break;
1035             }
1036             break;
1037         default:
1038             break;
1039     }
1040 
1041     // done
1042     hfp_connection->command = HFP_CMD_NONE;
1043 }
1044 
1045 static void hfp_hf_handle_transfer_ag_indicator_status(hfp_connection_t * hfp_connection) {
1046     uint16_t i;
1047     for (i = 0; i < hfp_connection->ag_indicators_nr; i++){
1048         if (hfp_connection->ag_indicators[i].status_changed) {
1049             if (strcmp(hfp_connection->ag_indicators[i].name, "callsetup") == 0){
1050                 hfp_callsetup_status = (hfp_callsetup_status_t) hfp_connection->ag_indicators[i].status;
1051             } else if (strcmp(hfp_connection->ag_indicators[i].name, "callheld") == 0){
1052                 hfp_callheld_status = (hfp_callheld_status_t) hfp_connection->ag_indicators[i].status;
1053                 // avoid set but not used warning
1054                 (void) hfp_callheld_status;
1055             } else if (strcmp(hfp_connection->ag_indicators[i].name, "call") == 0){
1056                 hfp_call_status = (hfp_call_status_t) hfp_connection->ag_indicators[i].status;
1057             }
1058             hfp_connection->ag_indicators[i].status_changed = 0;
1059             hfp_emit_ag_indicator_event(hfp_hf_callback, hfp_connection->ag_indicators[i]);
1060             break;
1061         }
1062     }
1063 }
1064 
1065 static void hfp_hf_handle_rfcomm_command(hfp_connection_t * hfp_connection){
1066     int value;
1067     int i;
1068     switch (hfp_connection->command){
1069         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1070             hfp_connection->command = HFP_CMD_NONE;
1071             hfp_hf_emit_subscriber_information(hfp_hf_callback, HFP_SUBEVENT_SUBSCRIBER_NUMBER_INFORMATION, 0, hfp_connection->bnip_type, hfp_connection->bnip_number);
1072             break;
1073         case HFP_CMD_RESPONSE_AND_HOLD_STATUS:
1074             hfp_connection->command = HFP_CMD_NONE;
1075             hfp_emit_event(hfp_connection, HFP_SUBEVENT_RESPONSE_AND_HOLD_STATUS, btstack_atoi((char *)&hfp_connection->line_buffer[0]));
1076             break;
1077         case HFP_CMD_LIST_CURRENT_CALLS:
1078             hfp_connection->command = HFP_CMD_NONE;
1079             hfp_hf_emit_enhanced_call_status(hfp_hf_callback, hfp_connection);
1080             break;
1081         case HFP_CMD_SET_SPEAKER_GAIN:
1082             hfp_connection->command = HFP_CMD_NONE;
1083             value = btstack_atoi((char*)hfp_connection->line_buffer);
1084             hfp_hf_speaker_gain = value;
1085             hfp_emit_event(hfp_connection, HFP_SUBEVENT_SPEAKER_VOLUME, value);
1086             break;
1087         case HFP_CMD_SET_MICROPHONE_GAIN:
1088             hfp_connection->command = HFP_CMD_NONE;
1089             value = btstack_atoi((char*)hfp_connection->line_buffer);
1090             hfp_hf_microphone_gain = value;
1091             hfp_emit_event(hfp_connection, HFP_SUBEVENT_MICROPHONE_VOLUME, value);
1092             break;
1093         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1094             hfp_connection->command = HFP_CMD_NONE;
1095             hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_NUMBER_FOR_VOICE_TAG, hfp_connection->bnip_number);
1096             break;
1097         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1098             hfp_connection->command = HFP_CMD_NONE;
1099             hfp_hf_emit_type_and_number(hfp_hf_callback, HFP_SUBEVENT_CALL_WAITING_NOTIFICATION, hfp_connection->bnip_type, hfp_connection->bnip_number);
1100             break;
1101         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1102             hfp_connection->command = HFP_CMD_NONE;
1103             hfp_hf_emit_type_and_number(hfp_hf_callback, HFP_SUBEVENT_CALLING_LINE_IDENTIFICATION_NOTIFICATION, hfp_connection->bnip_type, hfp_connection->bnip_number);
1104             break;
1105         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1106             hfp_connection->command = HFP_CMD_NONE;
1107             hfp_connection->ok_pending = 0;
1108             hfp_connection->extended_audio_gateway_error = 0;
1109             hfp_emit_event(hfp_connection, HFP_SUBEVENT_EXTENDED_AUDIO_GATEWAY_ERROR, hfp_connection->extended_audio_gateway_error_value);
1110             break;
1111         case HFP_CMD_ERROR:
1112             hfp_connection->command = HFP_CMD_NONE;
1113             hfp_connection->ok_pending = 0;
1114             hfp_reset_context_flags(hfp_connection);
1115             switch (hfp_connection->state){
1116                 case HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED:
1117                     switch (hfp_connection->codecs_state){
1118                         case HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE:
1119                             hfp_emit_sco_event(hfp_connection, HFP_REMOTE_REJECTS_AUDIO_CONNECTION, 0, hfp_connection->remote_addr, hfp_connection->negotiated_codec);
1120                             return;
1121                         default:
1122                             break;
1123                     }
1124                 default:
1125                     break;
1126             }
1127             hfp_emit_event(hfp_connection, HFP_SUBEVENT_COMPLETE, 1);
1128             break;
1129         case HFP_CMD_OK:
1130             hfp_hf_switch_on_ok(hfp_connection);
1131             break;
1132         case HFP_CMD_RING:
1133             hfp_connection->command = HFP_CMD_NONE;
1134             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_RING);
1135             break;
1136         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1137             hfp_connection->command = HFP_CMD_NONE;
1138             hfp_hf_handle_transfer_ag_indicator_status(hfp_connection);
1139             break;
1140         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1141             hfp_connection->command = HFP_CMD_NONE;
1142             for (i = 0; i < hfp_connection->ag_indicators_nr; i++){
1143                 hfp_emit_ag_indicator_event(hfp_hf_callback, hfp_connection->ag_indicators[i]);
1144             }
1145             break;
1146     	case HFP_CMD_AG_SUGGESTED_CODEC:
1147             hfp_connection->command = HFP_CMD_NONE;
1148     		hfp_hf_handle_suggested_codec(hfp_connection);
1149 			break;
1150         default:
1151             break;
1152     }
1153 }
1154 
1155 static int hfp_parser_is_end_of_line(uint8_t byte){
1156 	return (byte == '\n') || (byte == '\r');
1157 }
1158 
1159 static void hfp_hf_handle_rfcomm_data(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1160     UNUSED(packet_type);    // ok: only called with RFCOMM_DATA_PACKET
1161     // assertion: size >= 1 as rfcomm.c does not deliver empty packets
1162     if (size < 1) return;
1163 
1164     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_rfcomm_cid(channel);
1165     if (!hfp_connection) return;
1166 
1167     hfp_log_rfcomm_message("HFP_HF_RX", packet, size);
1168 #ifdef ENABLE_HFP_AT_MESSAGES
1169     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_RECEIVED, (char *) packet);
1170 #endif
1171 
1172     // process messages byte-wise
1173     int pos;
1174     for (pos = 0; pos < size; pos++){
1175         hfp_parse(hfp_connection, packet[pos], 1);
1176 
1177         // parse until end of line "\r\n"
1178         if (!hfp_parser_is_end_of_line(packet[pos])) continue;
1179 
1180         hfp_hf_handle_rfcomm_command(hfp_connection);
1181     }
1182     hfp_hf_run_for_context(hfp_connection);
1183 }
1184 
1185 static void hfp_hf_run(void){
1186     btstack_linked_list_iterator_t it;
1187     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1188     while (btstack_linked_list_iterator_has_next(&it)){
1189         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1190         if (hfp_connection->local_role != HFP_ROLE_HF) continue;
1191         hfp_hf_run_for_context(hfp_connection);
1192     }
1193 }
1194 
1195 static void hfp_hf_rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1196     switch (packet_type){
1197         case RFCOMM_DATA_PACKET:
1198             hfp_hf_handle_rfcomm_data(packet_type, channel, packet, size);
1199             break;
1200         case HCI_EVENT_PACKET:
1201             if (packet[0] == RFCOMM_EVENT_CAN_SEND_NOW){
1202                 uint16_t rfcomm_cid = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
1203                 hfp_hf_run_for_context(get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid));
1204                 return;
1205             }
1206             hfp_handle_rfcomm_event(packet_type, channel, packet, size, HFP_ROLE_HF);
1207             break;
1208         default:
1209             break;
1210     }
1211     hfp_hf_run();
1212 }
1213 
1214 static void hfp_hf_hci_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1215     hfp_handle_hci_event(packet_type, channel, packet, size, HFP_ROLE_HF);
1216     hfp_hf_run();
1217 }
1218 
1219 void hfp_hf_init(uint16_t rfcomm_channel_nr){
1220     hfp_init();
1221     hfp_supported_features = HFP_DEFAULT_HF_SUPPORTED_FEATURES;
1222     hfp_call_status = HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS;
1223     hfp_callsetup_status = HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1224     hfp_callheld_status= HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1225     hfp_codecs_nr = 0;
1226     hfp_hf_speaker_gain = 9;
1227     hfp_hf_microphone_gain = 9;
1228     hfp_indicators_nr = 0;
1229     hfp_supported_features = HFP_DEFAULT_HF_SUPPORTED_FEATURES;
1230 
1231     hfp_hf_hci_event_callback_registration.callback = &hfp_hf_hci_event_packet_handler;
1232     hci_add_event_handler(&hfp_hf_hci_event_callback_registration);
1233 
1234     rfcomm_register_service(hfp_hf_rfcomm_packet_handler, rfcomm_channel_nr, 0xffff);
1235 
1236     // used to set packet handler for outgoing rfcomm connections - could be handled by emitting an event to us
1237     hfp_set_hf_rfcomm_packet_handler(&hfp_hf_rfcomm_packet_handler);
1238 }
1239 
1240 void hfp_hf_deinit(void){
1241     hfp_deinit();
1242     (void) memset(&hfp_hf_hci_event_callback_registration, 0, sizeof(btstack_packet_callback_registration_t));
1243     (void) memset(&hfp_hf_callback, 0, sizeof(btstack_packet_handler_t));
1244     (void) memset(phone_number, 0, sizeof(phone_number));
1245 }
1246 
1247 void hfp_hf_init_codecs(int codecs_nr, const uint8_t * codecs){
1248     if (codecs_nr > HFP_MAX_NUM_CODECS){
1249         log_error("hfp_hf_init_codecs: codecs_nr (%d) > HFP_MAX_NUM_CODECS (%d)", codecs_nr, HFP_MAX_NUM_CODECS);
1250         return;
1251     }
1252 
1253     hfp_codecs_nr = codecs_nr;
1254     int i;
1255     for (i=0; i<codecs_nr; i++){
1256         hfp_codecs[i] = codecs[i];
1257     }
1258 }
1259 
1260 void hfp_hf_init_supported_features(uint32_t supported_features){
1261     hfp_supported_features = supported_features;
1262 }
1263 
1264 void hfp_hf_init_hf_indicators(int indicators_nr, const uint16_t * indicators){
1265     hfp_indicators_nr = indicators_nr;
1266     int i;
1267     for (i = 0; i < hfp_indicators_nr ; i++){
1268         hfp_indicators[i] = indicators[i];
1269     }
1270 }
1271 
1272 void hfp_hf_establish_service_level_connection(bd_addr_t bd_addr){
1273     hfp_establish_service_level_connection(bd_addr, BLUETOOTH_SERVICE_CLASS_HANDSFREE_AUDIO_GATEWAY, HFP_ROLE_HF);
1274 }
1275 
1276 void hfp_hf_release_service_level_connection(hci_con_handle_t acl_handle){
1277     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1278     if (!hfp_connection) {
1279         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1280         return;
1281     }
1282     hfp_release_service_level_connection(hfp_connection);
1283     hfp_hf_run_for_context(hfp_connection);
1284 }
1285 
1286 static void hfp_hf_set_status_update_for_all_ag_indicators(hci_con_handle_t acl_handle, uint8_t enable){
1287     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1288     if (!hfp_connection) {
1289         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1290         return;
1291     }
1292     hfp_connection->enable_status_update_for_ag_indicators = enable;
1293     hfp_hf_run_for_context(hfp_connection);
1294 }
1295 
1296 void hfp_hf_enable_status_update_for_all_ag_indicators(hci_con_handle_t acl_handle){
1297     hfp_hf_set_status_update_for_all_ag_indicators(acl_handle, 1);
1298 }
1299 
1300 void hfp_hf_disable_status_update_for_all_ag_indicators(hci_con_handle_t acl_handle){
1301     hfp_hf_set_status_update_for_all_ag_indicators(acl_handle, 0);
1302 }
1303 
1304 // TODO: returned ERROR - wrong format
1305 void hfp_hf_set_status_update_for_individual_ag_indicators(hci_con_handle_t acl_handle, uint32_t indicators_status_bitmap){
1306     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1307     if (!hfp_connection) {
1308         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1309         return;
1310     }
1311     hfp_connection->change_status_update_for_individual_ag_indicators = 1;
1312     hfp_connection->ag_indicators_status_update_bitmap = indicators_status_bitmap;
1313     hfp_hf_run_for_context(hfp_connection);
1314 }
1315 
1316 void hfp_hf_query_operator_selection(hci_con_handle_t acl_handle){
1317     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1318     if (!hfp_connection) {
1319         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1320         return;
1321     }
1322     switch (hfp_connection->hf_query_operator_state){
1323         case HFP_HF_QUERY_OPERATOR_FORMAT_NOT_SET:
1324             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_SET_FORMAT;
1325             break;
1326         case HFP_HF_QUERY_OPERATOR_FORMAT_SET:
1327             hfp_connection->hf_query_operator_state = HFP_HF_QUERY_OPERATOR_SEND_QUERY;
1328             break;
1329         default:
1330             break;
1331     }
1332     hfp_hf_run_for_context(hfp_connection);
1333 }
1334 
1335 static void hfp_hf_set_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle, uint8_t enable){
1336     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1337     if (!hfp_connection) {
1338         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1339         return;
1340     }
1341     hfp_connection->enable_extended_audio_gateway_error_report = enable;
1342     hfp_hf_run_for_context(hfp_connection);
1343 }
1344 
1345 
1346 void hfp_hf_enable_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle){
1347     hfp_hf_set_report_extended_audio_gateway_error_result_code(acl_handle, 1);
1348 }
1349 
1350 void hfp_hf_disable_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle){
1351     hfp_hf_set_report_extended_audio_gateway_error_result_code(acl_handle, 0);
1352 }
1353 
1354 static uint8_t hfp_hf_esco_s4_supported(hfp_connection_t * hfp_connection){
1355     return (hfp_connection->remote_supported_features & (1<<HFP_AGSF_ESCO_S4)) &&  (hfp_supported_features  & (1<<HFP_HFSF_ESCO_S4));
1356 }
1357 
1358 void hfp_hf_establish_audio_connection(hci_con_handle_t acl_handle){
1359     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1360     if (!hfp_connection) {
1361         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1362         return;
1363     }
1364     hfp_connection->establish_audio_connection = 0;
1365 
1366     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return;
1367     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
1368 
1369     hfp_connection->trigger_codec_exchange = 0;
1370     hfp_connection->establish_audio_connection = 1;
1371     if (!has_codec_negotiation_feature(hfp_connection)){
1372         log_info("no codec negotiation feature, using NBS");
1373         hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
1374         hfp_connection->suggested_codec = HFP_CODEC_CVSD;
1375         hfp_connection->codec_confirmed = hfp_connection->suggested_codec;
1376         hfp_connection->negotiated_codec = hfp_connection->suggested_codec;
1377         hfp_init_link_settings(hfp_connection, hfp_hf_esco_s4_supported(hfp_connection));
1378         hfp_connection->state = HFP_W4_SCO_CONNECTED;
1379     } else {
1380         switch (hfp_connection->codecs_state){
1381             case HFP_CODECS_W4_AG_COMMON_CODEC:
1382                 break;
1383             default:
1384 				hfp_connection->codec_confirmed = 0;
1385 				hfp_connection->suggested_codec = 0;
1386 				hfp_connection->negotiated_codec = 0;
1387 				hfp_connection->codecs_state = HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE;
1388                 hfp_connection->trigger_codec_exchange = 1;
1389                 break;
1390         }
1391     }
1392 
1393     hfp_hf_run_for_context(hfp_connection);
1394 }
1395 
1396 void hfp_hf_release_audio_connection(hci_con_handle_t acl_handle){
1397     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1398     if (!hfp_connection) {
1399         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1400         return;
1401     }
1402     hfp_release_audio_connection(hfp_connection);
1403     hfp_hf_run_for_context(hfp_connection);
1404 }
1405 
1406 void hfp_hf_answer_incoming_call(hci_con_handle_t acl_handle){
1407     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1408     if (!hfp_connection) {
1409         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1410         return;
1411     }
1412 
1413     if (hfp_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
1414         hfp_connection->hf_answer_incoming_call = 1;
1415         hfp_hf_run_for_context(hfp_connection);
1416     } else {
1417         log_error("HFP HF: answering incoming call with wrong callsetup status %u", hfp_callsetup_status);
1418     }
1419 }
1420 
1421 void hfp_hf_terminate_call(hci_con_handle_t acl_handle){
1422     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1423     if (!hfp_connection) {
1424         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1425         return;
1426     }
1427     hfp_connection->hf_send_chup = 1;
1428     hfp_hf_run_for_context(hfp_connection);
1429 }
1430 
1431 void hfp_hf_reject_incoming_call(hci_con_handle_t acl_handle){
1432     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1433     if (!hfp_connection) {
1434         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1435         return;
1436     }
1437 
1438     if (hfp_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
1439         hfp_connection->hf_send_chup = 1;
1440         hfp_hf_run_for_context(hfp_connection);
1441     }
1442 }
1443 
1444 void hfp_hf_user_busy(hci_con_handle_t acl_handle){
1445     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1446     if (!hfp_connection) {
1447         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1448         return;
1449     }
1450 
1451     if (hfp_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
1452         hfp_connection->hf_send_chld_0 = 1;
1453         hfp_hf_run_for_context(hfp_connection);
1454     }
1455 }
1456 
1457 void hfp_hf_end_active_and_accept_other(hci_con_handle_t acl_handle){
1458     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1459     if (!hfp_connection) {
1460         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1461         return;
1462     }
1463 
1464     if ((hfp_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1465         (hfp_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1466         hfp_connection->hf_send_chld_1 = 1;
1467         hfp_hf_run_for_context(hfp_connection);
1468     }
1469 }
1470 
1471 void hfp_hf_swap_calls(hci_con_handle_t acl_handle){
1472     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1473     if (!hfp_connection) {
1474         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1475         return;
1476     }
1477 
1478     if ((hfp_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1479         (hfp_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1480         hfp_connection->hf_send_chld_2 = 1;
1481         hfp_hf_run_for_context(hfp_connection);
1482     }
1483 }
1484 
1485 void hfp_hf_join_held_call(hci_con_handle_t acl_handle){
1486     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1487     if (!hfp_connection) {
1488         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1489         return;
1490     }
1491 
1492     if ((hfp_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1493         (hfp_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1494         hfp_connection->hf_send_chld_3 = 1;
1495         hfp_hf_run_for_context(hfp_connection);
1496     }
1497 }
1498 
1499 void hfp_hf_connect_calls(hci_con_handle_t acl_handle){
1500     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1501     if (!hfp_connection) {
1502         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1503         return;
1504     }
1505 
1506     if ((hfp_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1507         (hfp_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1508         hfp_connection->hf_send_chld_4 = 1;
1509         hfp_hf_run_for_context(hfp_connection);
1510     }
1511 }
1512 
1513 void hfp_hf_release_call_with_index(hci_con_handle_t acl_handle, int index){
1514     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1515     if (!hfp_connection) {
1516         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1517         return;
1518     }
1519 
1520     if ((hfp_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1521         (hfp_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1522         hfp_connection->hf_send_chld_x = 1;
1523         hfp_connection->hf_send_chld_x_index = 10 + index;
1524         hfp_hf_run_for_context(hfp_connection);
1525     }
1526 }
1527 
1528 void hfp_hf_private_consultation_with_call(hci_con_handle_t acl_handle, int index){
1529     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1530     if (!hfp_connection) {
1531         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1532         return;
1533     }
1534 
1535     if ((hfp_callsetup_status == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS) ||
1536         (hfp_call_status == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
1537         hfp_connection->hf_send_chld_x = 1;
1538         hfp_connection->hf_send_chld_x_index = 20 + index;
1539         hfp_hf_run_for_context(hfp_connection);
1540     }
1541 }
1542 
1543 void hfp_hf_dial_number(hci_con_handle_t acl_handle, char * number){
1544     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1545     if (!hfp_connection) {
1546         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1547         return;
1548     }
1549 
1550     hfp_connection->hf_initiate_outgoing_call = 1;
1551     snprintf(phone_number, sizeof(phone_number), "%s", number);
1552     hfp_hf_run_for_context(hfp_connection);
1553 }
1554 
1555 void hfp_hf_dial_memory(hci_con_handle_t acl_handle, int memory_id){
1556     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1557     if (!hfp_connection) {
1558         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1559         return;
1560     }
1561 
1562     hfp_connection->hf_initiate_memory_dialing = 1;
1563     hfp_connection->memory_id = memory_id;
1564 
1565     hfp_hf_run_for_context(hfp_connection);
1566 }
1567 
1568 void hfp_hf_redial_last_number(hci_con_handle_t acl_handle){
1569     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1570     if (!hfp_connection) {
1571         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1572         return;
1573     }
1574 
1575     hfp_connection->hf_initiate_redial_last_number = 1;
1576     hfp_hf_run_for_context(hfp_connection);
1577 }
1578 
1579 void hfp_hf_activate_call_waiting_notification(hci_con_handle_t acl_handle){
1580     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1581     if (!hfp_connection) {
1582         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1583         return;
1584     }
1585 
1586     hfp_connection->hf_activate_call_waiting_notification = 1;
1587     hfp_hf_run_for_context(hfp_connection);
1588 }
1589 
1590 
1591 void hfp_hf_deactivate_call_waiting_notification(hci_con_handle_t acl_handle){
1592     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1593     if (!hfp_connection) {
1594         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1595         return;
1596     }
1597 
1598     hfp_connection->hf_deactivate_call_waiting_notification = 1;
1599     hfp_hf_run_for_context(hfp_connection);
1600 }
1601 
1602 
1603 void hfp_hf_activate_calling_line_notification(hci_con_handle_t acl_handle){
1604     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1605     if (!hfp_connection) {
1606         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1607         return;
1608     }
1609 
1610     hfp_connection->hf_activate_calling_line_notification = 1;
1611     hfp_hf_run_for_context(hfp_connection);
1612 }
1613 
1614 void hfp_hf_deactivate_calling_line_notification(hci_con_handle_t acl_handle){
1615     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1616     if (!hfp_connection) {
1617         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1618         return;
1619     }
1620 
1621     hfp_connection->hf_deactivate_calling_line_notification = 1;
1622     hfp_hf_run_for_context(hfp_connection);
1623 }
1624 
1625 
1626 void hfp_hf_activate_echo_canceling_and_noise_reduction(hci_con_handle_t acl_handle){
1627     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1628     if (!hfp_connection) {
1629         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1630         return;
1631     }
1632 
1633     hfp_connection->hf_activate_echo_canceling_and_noise_reduction = 1;
1634     hfp_hf_run_for_context(hfp_connection);
1635 }
1636 
1637 void hfp_hf_deactivate_echo_canceling_and_noise_reduction(hci_con_handle_t acl_handle){
1638     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1639     if (!hfp_connection) {
1640         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1641         return;
1642     }
1643 
1644     hfp_connection->hf_deactivate_echo_canceling_and_noise_reduction = 1;
1645     hfp_hf_run_for_context(hfp_connection);
1646 }
1647 
1648 void hfp_hf_activate_voice_recognition_notification(hci_con_handle_t acl_handle){
1649     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1650     if (!hfp_connection) {
1651         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1652         return;
1653     }
1654 
1655     hfp_connection->hf_activate_voice_recognition_notification = 1;
1656     hfp_hf_run_for_context(hfp_connection);
1657 }
1658 
1659 void hfp_hf_deactivate_voice_recognition_notification(hci_con_handle_t acl_handle){
1660     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1661     if (!hfp_connection) {
1662         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1663         return;
1664     }
1665 
1666     hfp_connection->hf_deactivate_voice_recognition_notification = 1;
1667     hfp_hf_run_for_context(hfp_connection);
1668 }
1669 
1670 void hfp_hf_set_microphone_gain(hci_con_handle_t acl_handle, int gain){
1671     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1672     if (!hfp_connection) {
1673         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1674         return;
1675     }
1676 
1677     if (hfp_connection->microphone_gain == gain) return;
1678     if ((gain < 0) || (gain > 15)){
1679         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
1680         return;
1681     }
1682     hfp_connection->microphone_gain = gain;
1683     hfp_connection->send_microphone_gain = 1;
1684     hfp_hf_run_for_context(hfp_connection);
1685 }
1686 
1687 void hfp_hf_set_speaker_gain(hci_con_handle_t acl_handle, int gain){
1688     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1689     if (!hfp_connection) {
1690         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1691         return;
1692     }
1693 
1694     if (hfp_connection->speaker_gain == gain) return;
1695     if ((gain < 0) || (gain > 15)){
1696         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
1697         return;
1698     }
1699     hfp_connection->speaker_gain = gain;
1700     hfp_connection->send_speaker_gain = 1;
1701     hfp_hf_run_for_context(hfp_connection);
1702 }
1703 
1704 void hfp_hf_send_dtmf_code(hci_con_handle_t acl_handle, char code){
1705     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1706     if (!hfp_connection) {
1707         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1708         return;
1709     }
1710 
1711     hfp_connection->hf_send_dtmf_code = code;
1712     hfp_hf_run_for_context(hfp_connection);
1713 }
1714 
1715 void hfp_hf_request_phone_number_for_voice_tag(hci_con_handle_t acl_handle){
1716     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1717     if (!hfp_connection) {
1718         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1719         return;
1720     }
1721     hfp_connection->hf_send_binp = 1;
1722     hfp_hf_run_for_context(hfp_connection);
1723 }
1724 
1725 void hfp_hf_query_current_call_status(hci_con_handle_t acl_handle){
1726     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1727     if (!hfp_connection) {
1728         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1729         return;
1730     }
1731     hfp_connection->hf_send_clcc = 1;
1732     hfp_hf_run_for_context(hfp_connection);
1733 }
1734 
1735 
1736 void hfp_hf_rrh_query_status(hci_con_handle_t acl_handle){
1737     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1738     if (!hfp_connection) {
1739         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1740         return;
1741     }
1742     hfp_connection->hf_send_rrh = 1;
1743     hfp_connection->hf_send_rrh_command = '?';
1744     hfp_hf_run_for_context(hfp_connection);
1745 }
1746 
1747 void hfp_hf_rrh_hold_call(hci_con_handle_t acl_handle){
1748     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1749     if (!hfp_connection) {
1750         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1751         return;
1752     }
1753     hfp_connection->hf_send_rrh = 1;
1754     hfp_connection->hf_send_rrh_command = '0';
1755     hfp_hf_run_for_context(hfp_connection);
1756 }
1757 
1758 void hfp_hf_rrh_accept_held_call(hci_con_handle_t acl_handle){
1759     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1760     if (!hfp_connection) {
1761         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1762         return;
1763     }
1764     hfp_connection->hf_send_rrh = 1;
1765     hfp_connection->hf_send_rrh_command = '1';
1766     hfp_hf_run_for_context(hfp_connection);
1767 }
1768 
1769 void hfp_hf_rrh_reject_held_call(hci_con_handle_t acl_handle){
1770     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1771     if (!hfp_connection) {
1772         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1773         return;
1774     }
1775     hfp_connection->hf_send_rrh = 1;
1776     hfp_connection->hf_send_rrh_command = '2';
1777     hfp_hf_run_for_context(hfp_connection);
1778 }
1779 
1780 void hfp_hf_query_subscriber_number(hci_con_handle_t acl_handle){
1781     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1782     if (!hfp_connection) {
1783         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1784         return;
1785     }
1786     hfp_connection->hf_send_cnum = 1;
1787     hfp_hf_run_for_context(hfp_connection);
1788 }
1789 
1790 void hfp_hf_set_hf_indicator(hci_con_handle_t acl_handle, int assigned_number, int value){
1791     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1792     if (!hfp_connection) {
1793         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1794         return;
1795     }
1796     // find index for assigned number
1797     int i;
1798     for (i = 0; i < hfp_indicators_nr ; i++){
1799         if (hfp_indicators[i] == assigned_number){
1800             // set value
1801             hfp_indicators_value[i] = value;
1802             // mark for update
1803             if (hfp_connection->state > HFP_LIST_GENERIC_STATUS_INDICATORS){
1804                 hfp_connection->generic_status_update_bitmap |= (1<<i);
1805                 // send update
1806                 hfp_hf_run_for_context(hfp_connection);
1807             }
1808             return;
1809         }
1810     }
1811 }
1812 
1813 int hfp_hf_in_band_ringtone_active(hci_con_handle_t acl_handle){
1814     hfp_connection_t * hfp_connection = get_hfp_hf_connection_context_for_acl_handle(acl_handle);
1815     if (!hfp_connection) {
1816         log_error("HFP HF: ACL handle 0x%2x is not found.", acl_handle);
1817         return 0;
1818     }
1819     return get_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE);
1820 }
1821 
1822 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){
1823 	if (!name){
1824 		name = default_hfp_hf_service_name;
1825 	}
1826 	hfp_create_sdp_record(service, service_record_handle, BLUETOOTH_SERVICE_CLASS_HANDSFREE, rfcomm_channel_nr, name);
1827 
1828 	// Construct SupportedFeatures for SDP bitmap:
1829 	//
1830 	// "The values of the “SupportedFeatures” bitmap given in Table 5.4 shall be the same as the values
1831 	//  of the Bits 0 to 4 of the unsolicited result code +BRSF"
1832 	//
1833 	// Wide band speech (bit 5) requires Codec negotiation
1834 	//
1835 	uint16_t sdp_features = supported_features & 0x1f;
1836 	if (wide_band_speech && (supported_features & (1 << HFP_HFSF_CODEC_NEGOTIATION))){
1837 		sdp_features |= 1 << 5;
1838 	}
1839 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);    // Hands-Free Profile - SupportedFeatures
1840 	de_add_number(service, DE_UINT, DE_SIZE_16, sdp_features);
1841 }
1842 
1843 void hfp_hf_register_packet_handler(btstack_packet_handler_t callback){
1844 	if (callback == NULL){
1845 		log_error("hfp_hf_register_packet_handler called with NULL callback");
1846 		return;
1847 	}
1848 	hfp_hf_callback = callback;
1849 	hfp_set_hf_callback(callback);
1850 }
1851