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