xref: /btstack/src/classic/hfp_ag.c (revision cd5f23a3250874824c01a2b3326a9522fea3f99f)
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_ag.c"
39 
40 // *****************************************************************************
41 //
42 // HFP Audio Gateway (AG) unit
43 //
44 // *****************************************************************************
45 
46 #include "btstack_config.h"
47 
48 #include <stdint.h>
49 #include <string.h>
50 
51 #include "hci_cmd.h"
52 #include "btstack_run_loop.h"
53 
54 #include "bluetooth_sdp.h"
55 #include "hci.h"
56 #include "btstack_memory.h"
57 #include "hci_dump.h"
58 #include "l2cap.h"
59 #include "btstack_debug.h"
60 #include "btstack_event.h"
61 #include "classic/core.h"
62 #include "classic/hfp.h"
63 #include "classic/hfp_ag.h"
64 #include "classic/hfp_gsm_model.h"
65 #include "classic/sdp_client_rfcomm.h"
66 #include "classic/sdp_server.h"
67 #include "classic/sdp_util.h"
68 
69 // private prototypes
70 static void hfp_ag_run_for_context(hfp_connection_t *hfp_connection);
71 static void hfp_ag_hf_start_ringing(hfp_connection_t * hfp_connection);
72 static void hfp_ag_setup_audio_connection(hfp_connection_t * hfp_connection);
73 
74 // public prototypes
75 hfp_generic_status_indicator_t * get_hfp_generic_status_indicators(void);
76 int get_hfp_generic_status_indicators_nr(void);
77 void set_hfp_generic_status_indicators(hfp_generic_status_indicator_t * indicators, int indicator_nr);
78 void set_hfp_ag_indicators(hfp_ag_indicator_t * indicators, int indicator_nr);
79 int get_hfp_ag_indicators_nr(hfp_connection_t * context);
80 hfp_ag_indicator_t * get_hfp_ag_indicators(hfp_connection_t * context);
81 
82 
83 // const
84 static const char default_hfp_ag_service_name[] = "Voice gateway";
85 
86 // globals
87 static btstack_packet_callback_registration_t hfp_ag_hci_event_callback_registration;
88 
89 static uint16_t hfp_supported_features;
90 
91 static uint8_t hfp_codecs_nr;
92 static uint8_t hfp_codecs[HFP_MAX_NUM_CODECS];
93 
94 static int  hfp_ag_indicators_nr;
95 static hfp_ag_indicator_t hfp_ag_indicators[HFP_MAX_NUM_INDICATORS];
96 
97 static int hfp_generic_status_indicators_nr;
98 static hfp_generic_status_indicator_t hfp_generic_status_indicators[HFP_MAX_NUM_INDICATORS];
99 
100 static int  hfp_ag_call_hold_services_nr;
101 static char *hfp_ag_call_hold_services[6];
102 static btstack_packet_handler_t hfp_ag_callback;
103 
104 static hfp_response_and_hold_state_t hfp_ag_response_and_hold_state;
105 static int hfp_ag_response_and_hold_active;
106 
107 // Subscriber information entries
108 static hfp_phone_number_t * subscriber_numbers;
109 static int subscriber_numbers_count;
110 
111 // code
112 static void hfp_ag_emit_simple_event(uint8_t event_subtype){
113 	uint8_t event[3];
114 	event[0] = HCI_EVENT_HFP_META;
115 	event[1] = sizeof(event) - 2;
116 	event[2] = event_subtype;
117 	if (!hfp_ag_callback) return;
118 	(*hfp_ag_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
119 }
120 
121 static int hfp_ag_get_ag_indicators_nr(hfp_connection_t * hfp_connection){
122     if (hfp_connection->ag_indicators_nr != hfp_ag_indicators_nr){
123         hfp_connection->ag_indicators_nr = hfp_ag_indicators_nr;
124         (void)memcpy(hfp_connection->ag_indicators, hfp_ag_indicators,
125                      hfp_ag_indicators_nr * sizeof(hfp_ag_indicator_t));
126     }
127     return hfp_connection->ag_indicators_nr;
128 }
129 
130 hfp_ag_indicator_t * hfp_ag_get_ag_indicators(hfp_connection_t * hfp_connection){
131     // TODO: save only value, and value changed in the hfp_connection?
132     if (hfp_connection->ag_indicators_nr != hfp_ag_indicators_nr){
133         hfp_connection->ag_indicators_nr = hfp_ag_indicators_nr;
134         (void)memcpy(hfp_connection->ag_indicators, hfp_ag_indicators,
135                      hfp_ag_indicators_nr * sizeof(hfp_ag_indicator_t));
136     }
137     return (hfp_ag_indicator_t *)&(hfp_connection->ag_indicators);
138 }
139 
140 static hfp_ag_indicator_t * get_ag_indicator_for_name(const char * name){
141     int i;
142     for (i = 0; i < hfp_ag_indicators_nr; i++){
143         if (strcmp(hfp_ag_indicators[i].name, name) == 0){
144             return &hfp_ag_indicators[i];
145         }
146     }
147     return NULL;
148 }
149 
150 static int get_ag_indicator_index_for_name(const char * name){
151     int i;
152     for (i = 0; i < hfp_ag_indicators_nr; i++){
153         if (strcmp(hfp_ag_indicators[i].name, name) == 0){
154             return i;
155         }
156     }
157     return -1;
158 }
159 
160 static hfp_connection_t * get_hfp_ag_connection_context_for_acl_handle(uint16_t handle){
161     btstack_linked_list_iterator_t it;
162     btstack_linked_list_iterator_init(&it, hfp_get_connections());
163     while (btstack_linked_list_iterator_has_next(&it)){
164         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
165         if (hfp_connection->acl_handle != handle)      continue;
166         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
167         return hfp_connection;
168     }
169     return NULL;
170 }
171 
172 static int use_in_band_tone(void){
173     return get_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE);
174 }
175 
176 static int has_codec_negotiation_feature(hfp_connection_t * hfp_connection){
177     int hf = get_bit(hfp_connection->remote_supported_features, HFP_HFSF_CODEC_NEGOTIATION);
178     int ag = get_bit(hfp_supported_features, HFP_AGSF_CODEC_NEGOTIATION);
179     return hf && ag;
180 }
181 
182 static int has_call_waiting_and_3way_calling_feature(hfp_connection_t * hfp_connection){
183     int hf = get_bit(hfp_connection->remote_supported_features, HFP_HFSF_THREE_WAY_CALLING);
184     int ag = get_bit(hfp_supported_features, HFP_AGSF_THREE_WAY_CALLING);
185     return hf && ag;
186 }
187 
188 static int has_hf_indicators_feature(hfp_connection_t * hfp_connection){
189     int hf = get_bit(hfp_connection->remote_supported_features, HFP_HFSF_HF_INDICATORS);
190     int ag = get_bit(hfp_supported_features, HFP_AGSF_HF_INDICATORS);
191     return hf && ag;
192 }
193 
194 /* unsolicited responses */
195 
196 static int hfp_ag_send_change_in_band_ring_tone_setting_cmd(uint16_t cid){
197     char buffer[20];
198     sprintf(buffer, "\r\n%s:%d\r\n", HFP_CHANGE_IN_BAND_RING_TONE_SETTING, use_in_band_tone());
199     return send_str_over_rfcomm(cid, buffer);
200 }
201 
202 static int hfp_ag_exchange_supported_features_cmd(uint16_t cid){
203     char buffer[40];
204     sprintf(buffer, "\r\n%s:%d\r\n\r\nOK\r\n", HFP_SUPPORTED_FEATURES, hfp_supported_features);
205     return send_str_over_rfcomm(cid, buffer);
206 }
207 
208 static int hfp_ag_send_ok(uint16_t cid){
209     char buffer[10];
210     sprintf(buffer, "\r\nOK\r\n");
211     return send_str_over_rfcomm(cid, buffer);
212 }
213 
214 static int hfp_ag_send_ring(uint16_t cid){
215     return send_str_over_rfcomm(cid, (char *) "\r\nRING\r\n");
216 }
217 
218 static int hfp_ag_send_clip(uint16_t cid){
219     char buffer[50];
220     sprintf(buffer, "\r\n%s: \"%s\",%u\r\n", HFP_ENABLE_CLIP, hfp_gsm_clip_number(), hfp_gsm_clip_type());
221     return send_str_over_rfcomm(cid, buffer);
222 }
223 
224 static int hfp_send_subscriber_number_cmd(uint16_t cid, uint8_t type, const char * number){
225     char buffer[50];
226     sprintf(buffer, "\r\n%s: ,\"%s\",%u, , \r\n", HFP_SUBSCRIBER_NUMBER_INFORMATION, number, type);
227     return send_str_over_rfcomm(cid, buffer);
228 }
229 
230 static int hfp_ag_send_phone_number_for_voice_tag_cmd(uint16_t cid){
231     char buffer[50];
232     sprintf(buffer, "\r\n%s: %s\r\n", HFP_PHONE_NUMBER_FOR_VOICE_TAG, hfp_gsm_clip_number());
233     return send_str_over_rfcomm(cid, buffer);
234 }
235 
236 static int hfp_ag_send_call_waiting_notification(uint16_t cid){
237     char buffer[50];
238     sprintf(buffer, "\r\n%s: \"%s\",%u\r\n", HFP_ENABLE_CALL_WAITING_NOTIFICATION, hfp_gsm_clip_number(), hfp_gsm_clip_type());
239     return send_str_over_rfcomm(cid, buffer);
240 }
241 
242 static int hfp_ag_send_error(uint16_t cid){
243     char buffer[10];
244     sprintf(buffer, "\r\nERROR\r\n");
245     return send_str_over_rfcomm(cid, buffer);
246 }
247 
248 static int hfp_ag_send_report_extended_audio_gateway_error(uint16_t cid, uint8_t error){
249     char buffer[20];
250     sprintf(buffer, "\r\n%s=%d\r\n", HFP_EXTENDED_AUDIO_GATEWAY_ERROR, error);
251     return send_str_over_rfcomm(cid, buffer);
252 }
253 
254 // get size for indicator string
255 static int hfp_ag_indicators_string_size(hfp_connection_t * hfp_connection, int i){
256     // template: ("$NAME",($MIN,$MAX))
257     return 8 + (int) strlen(hfp_ag_get_ag_indicators(hfp_connection)[i].name)
258          + string_len_for_uint32(hfp_ag_get_ag_indicators(hfp_connection)[i].min_range)
259          + string_len_for_uint32(hfp_ag_get_ag_indicators(hfp_connection)[i].min_range);
260 }
261 
262 // store indicator
263 static void hfp_ag_indicators_string_store(hfp_connection_t * hfp_connection, int i, uint8_t * buffer){
264     sprintf((char *) buffer, "(\"%s\",(%d,%d)),",
265             hfp_ag_get_ag_indicators(hfp_connection)[i].name,
266             hfp_ag_get_ag_indicators(hfp_connection)[i].min_range,
267             hfp_ag_get_ag_indicators(hfp_connection)[i].max_range);
268 }
269 
270 // structure: header [indicator [comma indicator]] footer
271 static int hfp_ag_indicators_cmd_generator_num_segments(hfp_connection_t * hfp_connection){
272     int num_indicators = hfp_ag_get_ag_indicators_nr(hfp_connection);
273     if (!num_indicators) return 2;
274     return 3 + ((num_indicators-1) * 2);
275 }
276 
277 // get size of individual segment for hfp_ag_retrieve_indicators_cmd
278 static int hfp_ag_indicators_cmd_generator_get_segment_len(hfp_connection_t * hfp_connection, int index){
279     if (index == 0) {
280         return strlen(HFP_INDICATOR) + 3;   // "\n\r%s:""
281     }
282     index--;
283     int num_indicators = hfp_ag_get_ag_indicators_nr(hfp_connection);
284     int indicator_index = index >> 1;
285     if ((index & 1) == 0){
286         return hfp_ag_indicators_string_size(hfp_connection, indicator_index);
287     }
288     if (indicator_index == (num_indicators - 1)){
289         return 8; // "\r\n\r\nOK\r\n"
290     }
291     return 1; // comma
292 }
293 
294 static void hgp_ag_indicators_cmd_generator_store_segment(hfp_connection_t * hfp_connection, int index, uint8_t * buffer){
295     if (index == 0){
296         *buffer++ = '\r';
297         *buffer++ = '\n';
298         int len = strlen(HFP_INDICATOR);
299         (void)memcpy(buffer, HFP_INDICATOR, len);
300         buffer += len;
301         *buffer++ = ':';
302         return;
303     }
304     index--;
305     int num_indicators = hfp_ag_get_ag_indicators_nr(hfp_connection);
306     int indicator_index = index >> 1;
307     if ((index & 1) == 0){
308         hfp_ag_indicators_string_store(hfp_connection, indicator_index, buffer);
309         return;
310     }
311     if (indicator_index == (num_indicators-1)){
312         (void)memcpy(buffer, "\r\n\r\nOK\r\n", 8);
313         return;
314     }
315     *buffer = ',';
316 }
317 
318 static int hfp_hf_indicators_join(char * buffer, int buffer_size){
319     if (buffer_size < (hfp_ag_indicators_nr * 3)) return 0;
320     int i;
321     int offset = 0;
322     for (i = 0; i < (hfp_generic_status_indicators_nr-1); i++) {
323         offset += snprintf(buffer+offset, buffer_size-offset, "%d,", hfp_generic_status_indicators[i].uuid);
324     }
325     if (i < hfp_generic_status_indicators_nr){
326         offset += snprintf(buffer+offset, buffer_size-offset, "%d,", hfp_generic_status_indicators[i].uuid);
327     }
328     return offset;
329 }
330 
331 static int hfp_hf_indicators_initial_status_join(char * buffer, int buffer_size){
332     if (buffer_size < (hfp_generic_status_indicators_nr * 3)) return 0;
333     int i;
334     int offset = 0;
335     for (i = 0; i < hfp_generic_status_indicators_nr; i++) {
336         offset += snprintf(buffer+offset, buffer_size-offset, "\r\n%s:%d,%d\r\n", HFP_GENERIC_STATUS_INDICATOR, hfp_generic_status_indicators[i].uuid, hfp_generic_status_indicators[i].state);
337     }
338     return offset;
339 }
340 
341 static int hfp_ag_indicators_status_join(char * buffer, int buffer_size){
342     if (buffer_size < (hfp_ag_indicators_nr * 3)) return 0;
343     int i;
344     int offset = 0;
345     for (i = 0; i < (hfp_ag_indicators_nr-1); i++) {
346         offset += snprintf(buffer+offset, buffer_size-offset, "%d,", hfp_ag_indicators[i].status);
347     }
348     if (i<hfp_ag_indicators_nr){
349         offset += snprintf(buffer+offset, buffer_size-offset, "%d", hfp_ag_indicators[i].status);
350     }
351     return offset;
352 }
353 
354 static int hfp_ag_call_services_join(char * buffer, int buffer_size){
355     if (buffer_size < (hfp_ag_call_hold_services_nr * 3)) return 0;
356     int i;
357     int offset = snprintf(buffer, buffer_size, "(");
358     for (i = 0; i < (hfp_ag_call_hold_services_nr-1); i++) {
359         offset += snprintf(buffer+offset, buffer_size-offset, "%s,", hfp_ag_call_hold_services[i]);
360     }
361     if (i<hfp_ag_call_hold_services_nr){
362         offset += snprintf(buffer+offset, buffer_size-offset, "%s)", hfp_ag_call_hold_services[i]);
363     }
364     return offset;
365 }
366 
367 static int hfp_ag_send_cmd_via_generator(uint16_t cid, hfp_connection_t * hfp_connection,
368     int start_segment, int num_segments,
369     int (*get_segment_len)(hfp_connection_t * hfp_connection, int segment),
370     void (*store_segment) (hfp_connection_t * hfp_connection, int segment, uint8_t * buffer)){
371 
372     // assumes: can send now == true
373     // assumes: num segments > 0
374     // assumes: individual segments are smaller than MTU
375     rfcomm_reserve_packet_buffer();
376     int mtu = rfcomm_get_max_frame_size(cid);
377     uint8_t * data = rfcomm_get_outgoing_buffer();
378     int offset = 0;
379     int segment = start_segment;
380     while (segment < num_segments){
381         int segment_len = get_segment_len(hfp_connection, segment);
382         if ((offset + segment_len) > mtu) break;
383         // append segement
384         store_segment(hfp_connection, segment, data+offset);
385         offset += segment_len;
386         segment++;
387     }
388     rfcomm_send_prepared(cid, offset);
389     return segment;
390 }
391 
392 // returns next segment to store
393 static int hfp_ag_send_retrieve_indicators_cmd_via_generator(uint16_t cid, hfp_connection_t * hfp_connection, int start_segment){
394     int num_segments = hfp_ag_indicators_cmd_generator_num_segments(hfp_connection);
395     return hfp_ag_send_cmd_via_generator(cid, hfp_connection, start_segment, num_segments,
396         hfp_ag_indicators_cmd_generator_get_segment_len, hgp_ag_indicators_cmd_generator_store_segment);
397 }
398 
399 static int hfp_ag_send_retrieve_indicators_status_cmd(uint16_t cid){
400     char buffer[40];
401     const int size = sizeof(buffer);
402     int offset = snprintf(buffer, size, "\r\n%s:", HFP_INDICATOR);
403     offset += hfp_ag_indicators_status_join(buffer+offset, size-offset-9);
404     offset += snprintf(buffer+offset, size-offset, "\r\n\r\nOK\r\n");
405     return send_str_over_rfcomm(cid, buffer);
406 }
407 
408 static int hfp_ag_send_retrieve_can_hold_call_cmd(uint16_t cid){
409     char buffer[40];
410     const int size = sizeof(buffer);
411     int offset = snprintf(buffer, size, "\r\n%s:", HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES);
412     offset += hfp_ag_call_services_join(buffer+offset, size-offset-9);
413     offset += snprintf(buffer+offset, size-offset, "\r\n\r\nOK\r\n");
414     return send_str_over_rfcomm(cid, buffer);
415 }
416 
417 
418 static int hfp_ag_send_list_supported_generic_status_indicators_cmd(uint16_t cid){
419     return hfp_ag_send_ok(cid);
420 }
421 
422 static int hfp_ag_send_retrieve_supported_generic_status_indicators_cmd(uint16_t cid){
423     char buffer[40];
424     const int size = sizeof(buffer);
425     int offset = snprintf(buffer, size, "\r\n%s:(", HFP_GENERIC_STATUS_INDICATOR);
426     offset += hfp_hf_indicators_join(buffer+offset, size-offset-10);
427     offset += snprintf(buffer+offset, size-offset, ")\r\n\r\nOK\r\n");
428     return send_str_over_rfcomm(cid, buffer);
429 }
430 
431 static int hfp_ag_send_retrieve_initital_supported_generic_status_indicators_cmd(uint16_t cid){
432     char buffer[40];
433     int offset = hfp_hf_indicators_initial_status_join(buffer, sizeof(buffer) - 7);
434     snprintf(buffer+offset, sizeof(buffer)-offset, "\r\nOK\r\n");
435     return send_str_over_rfcomm(cid, buffer);
436 }
437 
438 static int hfp_ag_send_transfer_ag_indicators_status_cmd(uint16_t cid, hfp_ag_indicator_t * indicator){
439     char buffer[20];
440     sprintf(buffer, "\r\n%s:%d,%d\r\n", HFP_TRANSFER_AG_INDICATOR_STATUS, indicator->index, indicator->status);
441     return send_str_over_rfcomm(cid, buffer);
442 }
443 
444 static int hfp_ag_send_report_network_operator_name_cmd(uint16_t cid, hfp_network_opearator_t op){
445     char buffer[41];
446     if (strlen(op.name) == 0){
447         snprintf(buffer, sizeof(buffer), "\r\n%s:%d,,\r\n\r\nOK\r\n", HFP_QUERY_OPERATOR_SELECTION, op.mode);
448     } else {
449         int offset = snprintf(buffer,  sizeof(buffer), "\r\n%s:%d,%d,", HFP_QUERY_OPERATOR_SELECTION, op.mode, op.format);
450         offset += snprintf(buffer+offset, 16, "%s", op.name);
451         snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n\r\nOK\r\n");
452     }
453     return send_str_over_rfcomm(cid, buffer);
454 }
455 
456 static inline int hfp_ag_send_cmd_with_int(uint16_t cid, const char * cmd, uint8_t value){
457     char buffer[30];
458     snprintf(buffer, sizeof(buffer), "\r\n%s:%d\r\n", cmd, value);
459     return send_str_over_rfcomm(cid, buffer);
460 }
461 
462 static int hfp_ag_send_suggest_codec_cmd(uint16_t cid, uint8_t codec){
463     return hfp_ag_send_cmd_with_int(cid, HFP_CONFIRM_COMMON_CODEC, codec);
464 }
465 
466 static int hfp_ag_send_activate_voice_recognition_cmd(uint16_t cid, uint8_t activate_voice_recognition){
467     return hfp_ag_send_cmd_with_int(cid, HFP_ACTIVATE_VOICE_RECOGNITION, activate_voice_recognition);
468 }
469 
470 static int hfp_ag_send_set_speaker_gain_cmd(uint16_t cid, uint8_t gain){
471     return hfp_ag_send_cmd_with_int(cid, HFP_SET_SPEAKER_GAIN, gain);
472 }
473 
474 static int hfp_ag_send_set_microphone_gain_cmd(uint16_t cid, uint8_t gain){
475     return hfp_ag_send_cmd_with_int(cid, HFP_SET_MICROPHONE_GAIN, gain);
476 }
477 
478 static int hfp_ag_send_set_response_and_hold(uint16_t cid, int state){
479     return hfp_ag_send_cmd_with_int(cid, HFP_RESPONSE_AND_HOLD, state);
480 }
481 
482 static uint8_t hfp_ag_suggest_codec(hfp_connection_t *hfp_connection){
483     if (hfp_connection->sco_for_msbc_failed) return HFP_CODEC_CVSD;
484 
485     if (hfp_supports_codec(HFP_CODEC_MSBC, hfp_codecs_nr, hfp_codecs)){
486         if (hfp_supports_codec(HFP_CODEC_MSBC, hfp_connection->remote_codecs_nr, hfp_connection->remote_codecs)){
487             return HFP_CODEC_MSBC;
488         }
489     }
490     return HFP_CODEC_CVSD;
491 }
492 
493 /* state machines */
494 
495 static uint8_t hfp_ag_esco_s4_supported(hfp_connection_t * hfp_connection){
496     return (hfp_connection->remote_supported_features & (1<<HFP_HFSF_ESCO_S4)) &&  (hfp_supported_features  & (1<<HFP_AGSF_ESCO_S4));
497 }
498 
499 static int codecs_exchange_state_machine(hfp_connection_t * hfp_connection){
500     /* events ( == commands):
501         HFP_CMD_AVAILABLE_CODECS == received AT+BAC with list of codecs
502         HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP:
503             hf_trigger_codec_connection_setup == received BCC
504             ag_trigger_codec_connection_setup == received from AG to send BCS
505         HFP_CMD_HF_CONFIRMED_CODEC == received AT+BCS
506     */
507 
508      switch (hfp_connection->codecs_state){
509         case HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE:
510             hfp_connection->command = HFP_CMD_AG_SEND_COMMON_CODEC;
511             break;
512         case HFP_CODECS_AG_RESEND_COMMON_CODEC:
513             hfp_connection->command = HFP_CMD_AG_SEND_COMMON_CODEC;
514             break;
515         default:
516             break;
517     }
518 
519     switch (hfp_connection->command){
520         case HFP_CMD_AVAILABLE_CODECS:
521             if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
522                 hfp_connection->codecs_state = HFP_CODECS_RECEIVED_LIST;
523                 hfp_ag_send_ok(hfp_connection->rfcomm_cid);
524                 return 1;
525             }
526 
527             switch (hfp_connection->codecs_state){
528                 case HFP_CODECS_AG_SENT_COMMON_CODEC:
529                 case HFP_CODECS_EXCHANGED:
530                     hfp_connection->codecs_state = HFP_CODECS_AG_RESEND_COMMON_CODEC;
531                     break;
532                 default:
533                     break;
534             }
535             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
536             return 1;
537 
538         case HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP:
539             hfp_connection->codecs_state = HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE;
540             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
541             return 1;
542 
543         case HFP_CMD_AG_SEND_COMMON_CODEC:
544             hfp_connection->codecs_state = HFP_CODECS_AG_SENT_COMMON_CODEC;
545             hfp_connection->suggested_codec = hfp_ag_suggest_codec(hfp_connection);
546             hfp_ag_send_suggest_codec_cmd(hfp_connection->rfcomm_cid, hfp_connection->suggested_codec);
547             return 1;
548 
549         case HFP_CMD_HF_CONFIRMED_CODEC:
550             if (hfp_connection->codec_confirmed != hfp_connection->suggested_codec){
551                 hfp_connection->codecs_state = HFP_CODECS_ERROR;
552                 hfp_ag_send_error(hfp_connection->rfcomm_cid);
553                 return 1;
554             }
555             hfp_connection->negotiated_codec = hfp_connection->codec_confirmed;
556             hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
557             log_info("hfp: codec confirmed: %s", (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? "mSBC" : "CVSD");
558             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
559             // now, pick link settings
560             hfp_init_link_settings(hfp_connection, hfp_ag_esco_s4_supported(hfp_connection));
561 #ifdef ENABLE_CC256X_ASSISTED_HFP
562             hfp_cc256x_prepare_for_sco(hfp_connection);
563 #endif
564             return 1;
565         default:
566             break;
567     }
568     return 0;
569 }
570 
571 static void hfp_ag_slc_established(hfp_connection_t * hfp_connection){
572     hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
573     hfp_emit_slc_connection_event(hfp_connection, 0, hfp_connection->acl_handle, hfp_connection->remote_addr);
574 
575     // if active call exist, set per-hfp_connection state active, too (when audio is on)
576     if (hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT){
577         hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE;
578     }
579     // if AG is ringing, also start ringing on the HF
580     if ((hfp_gsm_call_status() == HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS) &&
581         (hfp_gsm_callsetup_status() == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS)){
582         hfp_ag_hf_start_ringing(hfp_connection);
583     }
584 }
585 
586 static int hfp_ag_run_for_context_service_level_connection(hfp_connection_t * hfp_connection){
587     // log_info("hfp_ag_run_for_context_service_level_connection state %u, command %u", hfp_connection->state, hfp_connection->command);
588     if (hfp_connection->state >= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) return 0;
589     int sent = 0;
590     switch(hfp_connection->command){
591         case HFP_CMD_SUPPORTED_FEATURES:
592             switch(hfp_connection->state){
593                 case HFP_W4_EXCHANGE_SUPPORTED_FEATURES:
594                 case HFP_EXCHANGE_SUPPORTED_FEATURES:
595                     hfp_hf_drop_mSBC_if_eSCO_not_supported(hfp_codecs, &hfp_codecs_nr);
596                     if (has_codec_negotiation_feature(hfp_connection)){
597                         hfp_connection->state = HFP_W4_NOTIFY_ON_CODECS;
598                     } else {
599                         hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS;
600                     }
601                     hfp_ag_exchange_supported_features_cmd(hfp_connection->rfcomm_cid);
602                     return 1;
603                 default:
604                     break;
605             }
606             break;
607         case HFP_CMD_AVAILABLE_CODECS:
608             sent = codecs_exchange_state_machine(hfp_connection);
609             if (hfp_connection->codecs_state == HFP_CODECS_RECEIVED_LIST){
610                 hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS;
611             }
612             return sent;
613 
614         case HFP_CMD_RETRIEVE_AG_INDICATORS:
615             if (hfp_connection->state == HFP_W4_RETRIEVE_INDICATORS) {
616                 // HF requested AG Indicators and we did expect it
617                 hfp_connection->send_ag_indicators_segment = 0;
618                 hfp_connection->state = HFP_RETRIEVE_INDICATORS;
619                 // continue below in state switch
620             }
621             break;
622 
623         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
624             if (hfp_connection->state != HFP_W4_RETRIEVE_INDICATORS_STATUS) break;
625             hfp_connection->state = HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE;
626             hfp_ag_send_retrieve_indicators_status_cmd(hfp_connection->rfcomm_cid);
627             return 1;
628 
629         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
630             if (hfp_connection->state != HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE) break;
631             if (has_call_waiting_and_3way_calling_feature(hfp_connection)){
632                 hfp_connection->state = HFP_W4_RETRIEVE_CAN_HOLD_CALL;
633             } else if (has_hf_indicators_feature(hfp_connection)){
634                 hfp_connection->state = HFP_W4_LIST_GENERIC_STATUS_INDICATORS;
635             } else {
636                 hfp_ag_slc_established(hfp_connection);
637             }
638             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
639             return 1;
640 
641         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
642             if (hfp_connection->state != HFP_W4_RETRIEVE_CAN_HOLD_CALL) break;
643             if (has_hf_indicators_feature(hfp_connection)){
644                 hfp_connection->state = HFP_W4_LIST_GENERIC_STATUS_INDICATORS;
645             }
646             hfp_ag_send_retrieve_can_hold_call_cmd(hfp_connection->rfcomm_cid);
647             if (!has_hf_indicators_feature(hfp_connection)){
648                 hfp_ag_slc_established(hfp_connection);
649             }
650             return 1;
651 
652         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
653             if (hfp_connection->state != HFP_W4_LIST_GENERIC_STATUS_INDICATORS) break;
654             hfp_connection->state = HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS;
655             hfp_ag_send_list_supported_generic_status_indicators_cmd(hfp_connection->rfcomm_cid);
656             return 1;
657 
658         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
659             if (hfp_connection->state != HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS) break;
660             hfp_connection->state = HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS;
661             hfp_ag_send_retrieve_supported_generic_status_indicators_cmd(hfp_connection->rfcomm_cid);
662             return 1;
663 
664         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
665             if (hfp_connection->state != HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS) break;
666             hfp_ag_slc_established(hfp_connection);
667             hfp_ag_send_retrieve_initital_supported_generic_status_indicators_cmd(hfp_connection->rfcomm_cid);
668             return 1;
669         default:
670             break;
671     }
672 
673     switch (hfp_connection->state){
674         case HFP_RETRIEVE_INDICATORS: {
675             int next_segment = hfp_ag_send_retrieve_indicators_cmd_via_generator(hfp_connection->rfcomm_cid, hfp_connection, hfp_connection->send_ag_indicators_segment);
676             int num_segments = hfp_ag_indicators_cmd_generator_num_segments(hfp_connection);
677             log_info("HFP_CMD_RETRIEVE_AG_INDICATORS next segment %u, num_segments %u", next_segment, num_segments);
678             if (next_segment < num_segments){
679                 // prepare sending of next segment
680                 hfp_connection->send_ag_indicators_segment = next_segment;
681                 log_info("HFP_CMD_RETRIEVE_AG_INDICATORS more. command %u, next seg %u", hfp_connection->command, next_segment);
682             } else {
683                 // done, go to next state
684                 hfp_connection->send_ag_indicators_segment = 0;
685                 hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS_STATUS;
686             }
687             return 1;
688         }
689         default:
690             break;
691     }
692     return 0;
693 }
694 
695 static int hfp_ag_run_for_context_service_level_connection_queries(hfp_connection_t * hfp_connection){
696     int sent = codecs_exchange_state_machine(hfp_connection);
697     if (sent) return 1;
698 
699     switch(hfp_connection->command){
700         case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
701             hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION, hfp_connection->ag_activate_voice_recognition);
702             hfp_ag_send_activate_voice_recognition_cmd(hfp_connection->rfcomm_cid, hfp_connection->ag_activate_voice_recognition);
703             return 1;
704         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
705             if (get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)){
706                 hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION, hfp_connection->ag_activate_voice_recognition);
707                 hfp_ag_send_ok(hfp_connection->rfcomm_cid);
708                 hfp_ag_setup_audio_connection(hfp_connection);
709             } else {
710                 hfp_ag_send_error(hfp_connection->rfcomm_cid);
711             }
712             return 1;
713         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
714             hfp_ag_send_change_in_band_ring_tone_setting_cmd(hfp_connection->rfcomm_cid);
715             return 1;
716         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
717             hfp_ag_send_report_network_operator_name_cmd(hfp_connection->rfcomm_cid, hfp_connection->network_operator);
718             return 1;
719         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
720             if (hfp_connection->network_operator.format != 0){
721                 hfp_ag_send_error(hfp_connection->rfcomm_cid);
722             } else {
723                 hfp_ag_send_ok(hfp_connection->rfcomm_cid);
724             }
725             return 1;
726         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
727             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
728             return 1;
729         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
730             if (hfp_connection->extended_audio_gateway_error){
731                 hfp_connection->extended_audio_gateway_error = 0;
732                 hfp_ag_send_report_extended_audio_gateway_error(hfp_connection->rfcomm_cid, hfp_connection->extended_audio_gateway_error_value);
733                 return 1;
734             }
735             break;
736         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
737             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
738             return 1;
739         default:
740             break;
741     }
742     return 0;
743 }
744 
745 static int hfp_ag_run_for_audio_connection(hfp_connection_t * hfp_connection){
746     if ((hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) ||
747         (hfp_connection->state > HFP_W2_DISCONNECT_SCO)) return 0;
748 
749 
750     if ((hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) && hfp_connection->release_audio_connection){
751         hfp_connection->state = HFP_W4_SCO_DISCONNECTED;
752         hfp_connection->release_audio_connection = 0;
753         gap_disconnect(hfp_connection->sco_handle);
754         return 1;
755     }
756 
757     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
758 
759     // run codecs exchange
760     int sent = codecs_exchange_state_machine(hfp_connection);
761     if (sent) return 1;
762 
763     if (hfp_connection->codecs_state != HFP_CODECS_EXCHANGED) return 0;
764     if (hfp_connection->establish_audio_connection){
765         hfp_connection->state = HFP_W4_SCO_CONNECTED;
766         hfp_connection->establish_audio_connection = 0;
767         hfp_setup_synchronous_connection(hfp_connection);
768         return 1;
769     }
770     return 0;
771 }
772 
773 static hfp_connection_t * hfp_ag_context_for_timer(btstack_timer_source_t * ts){
774     btstack_linked_list_iterator_t it;
775     btstack_linked_list_iterator_init(&it, hfp_get_connections());
776 
777     while (btstack_linked_list_iterator_has_next(&it)){
778         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
779         if ( & hfp_connection->hfp_timeout == ts) {
780             return hfp_connection;
781         }
782     }
783     return NULL;
784 }
785 
786 static void hfp_timeout_handler(btstack_timer_source_t * timer){
787     hfp_connection_t * hfp_connection = hfp_ag_context_for_timer(timer);
788     if (!hfp_connection) return;
789 
790     log_info("HFP start ring timeout, con handle 0x%02x", hfp_connection->acl_handle);
791     hfp_connection->ag_ring = 1;
792     hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
793 
794     btstack_run_loop_set_timer(& hfp_connection->hfp_timeout, 2000); // 2 seconds timeout
795     btstack_run_loop_add_timer(& hfp_connection->hfp_timeout);
796 
797     hfp_ag_run_for_context(hfp_connection);
798 }
799 
800 static void hfp_timeout_start(hfp_connection_t * hfp_connection){
801     btstack_run_loop_remove_timer(& hfp_connection->hfp_timeout);
802     btstack_run_loop_set_timer_handler(& hfp_connection->hfp_timeout, hfp_timeout_handler);
803     btstack_run_loop_set_timer(& hfp_connection->hfp_timeout, 2000); // 2 seconds timeout
804     btstack_run_loop_add_timer(& hfp_connection->hfp_timeout);
805 }
806 
807 static void hfp_timeout_stop(hfp_connection_t * hfp_connection){
808     log_info("HFP stop ring timeout, con handle 0x%02x", hfp_connection->acl_handle);
809     btstack_run_loop_remove_timer(& hfp_connection->hfp_timeout);
810 }
811 
812 //
813 // transitition implementations for hfp_ag_call_state_machine
814 //
815 
816 static void hfp_ag_hf_start_ringing(hfp_connection_t * hfp_connection){
817     if (use_in_band_tone()){
818         hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING;
819         hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
820     } else {
821         hfp_timeout_start(hfp_connection);
822         hfp_connection->ag_ring = 1;
823         hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
824         hfp_connection->call_state = HFP_CALL_RINGING;
825         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_START_RINGINIG);
826     }
827 }
828 
829 static void hfp_ag_hf_stop_ringing(hfp_connection_t * hfp_connection){
830     hfp_connection->ag_ring = 0;
831     hfp_connection->ag_send_clip = 0;
832     hfp_timeout_stop(hfp_connection);
833     hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_STOP_RINGINIG);
834 }
835 
836 static void hfp_ag_trigger_incoming_call(void){
837     int indicator_index = get_ag_indicator_index_for_name("callsetup");
838     if (indicator_index < 0) return;
839 
840     btstack_linked_list_iterator_t it;
841     btstack_linked_list_iterator_init(&it, hfp_get_connections());
842     while (btstack_linked_list_iterator_has_next(&it)){
843         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
844         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
845         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
846         if (hfp_connection->call_state == HFP_CALL_IDLE){
847             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
848             hfp_ag_hf_start_ringing(hfp_connection);
849         }
850         if (hfp_connection->call_state == HFP_CALL_ACTIVE){
851             hfp_connection->call_state = HFP_CALL_W2_SEND_CALL_WAITING;
852         }
853         hfp_ag_run_for_context(hfp_connection);
854     }
855 }
856 
857 static void hfp_ag_transfer_indicator(const char * name){
858     int indicator_index = get_ag_indicator_index_for_name(name);
859     if (indicator_index < 0) return;
860 
861     btstack_linked_list_iterator_t it;
862     btstack_linked_list_iterator_init(&it, hfp_get_connections());
863     while (btstack_linked_list_iterator_has_next(&it)){
864         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
865         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
866         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
867         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
868         hfp_ag_run_for_context(hfp_connection);
869     }
870 }
871 
872 static void hfp_ag_transfer_callsetup_state(void){
873     hfp_ag_transfer_indicator("callsetup");
874 }
875 
876 static void hfp_ag_transfer_call_state(void){
877     hfp_ag_transfer_indicator("call");
878 }
879 
880 static void hfp_ag_transfer_callheld_state(void){
881     hfp_ag_transfer_indicator("callheld");
882 }
883 
884 static void hfp_ag_hf_accept_call(hfp_connection_t * source){
885 
886     int call_indicator_index = get_ag_indicator_index_for_name("call");
887     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
888 
889     btstack_linked_list_iterator_t it;
890     btstack_linked_list_iterator_init(&it, hfp_get_connections());
891     while (btstack_linked_list_iterator_has_next(&it)){
892         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
893         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
894         if ((hfp_connection->call_state != HFP_CALL_RINGING) &&
895             (hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
896 
897         hfp_ag_hf_stop_ringing(hfp_connection);
898         if (hfp_connection == source){
899 
900             if (use_in_band_tone()){
901                 hfp_connection->call_state = HFP_CALL_ACTIVE;
902             } else {
903                 hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE;
904                 hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
905             }
906 
907             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
908             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
909 
910         } else {
911             hfp_connection->call_state = HFP_CALL_IDLE;
912         }
913         hfp_ag_run_for_context(hfp_connection);
914     }
915 }
916 
917 static void hfp_ag_ag_accept_call(void){
918 
919     int call_indicator_index = get_ag_indicator_index_for_name("call");
920     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
921 
922     btstack_linked_list_iterator_t it;
923     btstack_linked_list_iterator_init(&it, hfp_get_connections());
924     while (btstack_linked_list_iterator_has_next(&it)){
925         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
926         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
927         if (hfp_connection->call_state != HFP_CALL_RINGING) continue;
928 
929         hfp_ag_hf_stop_ringing(hfp_connection);
930         hfp_connection->call_state = HFP_CALL_TRIGGER_AUDIO_CONNECTION;
931 
932         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
933         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
934 
935         hfp_ag_run_for_context(hfp_connection);
936         break;  // only single
937     }
938 }
939 
940 static void hfp_ag_trigger_reject_call(void){
941     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
942     btstack_linked_list_iterator_t it;
943     btstack_linked_list_iterator_init(&it, hfp_get_connections());
944     while (btstack_linked_list_iterator_has_next(&it)){
945         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
946         if (connection->local_role != HFP_ROLE_AG) continue;
947         if ((connection->call_state != HFP_CALL_RINGING) &&
948             (connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
949         hfp_ag_hf_stop_ringing(connection);
950         connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
951         connection->call_state = HFP_CALL_IDLE;
952         hfp_ag_run_for_context(connection);
953     }
954 }
955 
956 static void hfp_ag_trigger_terminate_call(void){
957     int call_indicator_index = get_ag_indicator_index_for_name("call");
958 
959     btstack_linked_list_iterator_t it;
960     btstack_linked_list_iterator_init(&it, hfp_get_connections());
961     while (btstack_linked_list_iterator_has_next(&it)){
962         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
963         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
964         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
965         if (hfp_connection->call_state == HFP_CALL_IDLE) continue;
966         hfp_connection->call_state = HFP_CALL_IDLE;
967         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
968         if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
969             hfp_connection->release_audio_connection = 1;
970         }
971         hfp_ag_run_for_context(hfp_connection);
972     }
973     hfp_ag_emit_simple_event(HFP_SUBEVENT_CALL_TERMINATED);
974 }
975 
976 static void hfp_ag_set_callsetup_indicator(void){
977     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("callsetup");
978     if (!indicator){
979         log_error("hfp_ag_set_callsetup_indicator: callsetup indicator is missing");
980         return;
981     };
982     indicator->status = hfp_gsm_callsetup_status();
983 }
984 
985 static void hfp_ag_set_callheld_indicator(void){
986     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("callheld");
987     if (!indicator){
988         log_error("hfp_ag_set_callheld_state: callheld indicator is missing");
989         return;
990     };
991     indicator->status = hfp_gsm_callheld_status();
992 }
993 
994 static void hfp_ag_set_call_indicator(void){
995     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("call");
996     if (!indicator){
997         log_error("hfp_ag_set_call_state: call indicator is missing");
998         return;
999     };
1000     indicator->status = hfp_gsm_call_status();
1001 }
1002 
1003 static void hfp_ag_stop_ringing(void){
1004     btstack_linked_list_iterator_t it;
1005     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1006     while (btstack_linked_list_iterator_has_next(&it)){
1007         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1008         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1009         if ((hfp_connection->call_state != HFP_CALL_RINGING) &&
1010             (hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
1011         hfp_ag_hf_stop_ringing(hfp_connection);
1012     }
1013 }
1014 
1015 static hfp_connection_t * hfp_ag_connection_for_call_state(hfp_call_state_t call_state){
1016     btstack_linked_list_iterator_t it;
1017     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1018     while (btstack_linked_list_iterator_has_next(&it)){
1019         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1020         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1021         if (hfp_connection->call_state == call_state) return hfp_connection;
1022     }
1023     return NULL;
1024 }
1025 
1026 static void hfp_ag_send_response_and_hold_state(hfp_response_and_hold_state_t state){
1027     btstack_linked_list_iterator_t it;
1028     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1029     while (btstack_linked_list_iterator_has_next(&it)){
1030         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1031         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1032         hfp_connection->send_response_and_hold_status = state + 1;
1033     }
1034 }
1035 
1036 static int call_setup_state_machine(hfp_connection_t * hfp_connection){
1037     int indicator_index;
1038     switch (hfp_connection->call_state){
1039         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING:
1040             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1041             // we got event: audio hfp_connection established
1042             hfp_timeout_start(hfp_connection);
1043             hfp_connection->ag_ring = 1;
1044             hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
1045             hfp_connection->call_state = HFP_CALL_RINGING;
1046             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_START_RINGINIG);
1047             break;
1048         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE:
1049             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1050             // we got event: audio hfp_connection established
1051             hfp_connection->call_state = HFP_CALL_ACTIVE;
1052             break;
1053         case HFP_CALL_W2_SEND_CALL_WAITING:
1054             hfp_connection->call_state = HFP_CALL_W4_CHLD;
1055             hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1056             indicator_index = get_ag_indicator_index_for_name("callsetup");
1057             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1058             break;
1059         default:
1060             break;
1061     }
1062     return 0;
1063 }
1064 
1065 // functions extracted from hfp_ag_call_sm below
1066 static void hfp_ag_handle_reject_incoming_call(void){
1067     hfp_connection_t * hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1068     if (!hfp_connection){
1069         log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1070         return;
1071     }
1072 
1073     hfp_gsm_handler(HFP_AG_OUTGOING_CALL_REJECTED, 0, 0, NULL);
1074     hfp_connection->call_state = HFP_CALL_IDLE;
1075     hfp_connection->send_error = 1;
1076     hfp_ag_run_for_context(hfp_connection);
1077 }
1078 
1079 // hfp_connection is used to identify originating HF
1080 static void hfp_ag_call_sm(hfp_ag_call_event_t event, hfp_connection_t * hfp_connection){
1081     int indicator_index;
1082     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1083     int callheld_indicator_index = get_ag_indicator_index_for_name("callheld");
1084     int call_indicator_index = get_ag_indicator_index_for_name("call");
1085 
1086     switch (event){
1087         case HFP_AG_INCOMING_CALL:
1088             switch (hfp_gsm_call_status()){
1089                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1090                     switch (hfp_gsm_callsetup_status()){
1091                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1092                             hfp_gsm_handler(HFP_AG_INCOMING_CALL, 0, 0, NULL);
1093                             hfp_ag_set_callsetup_indicator();
1094                             hfp_ag_trigger_incoming_call();
1095                             log_info("AG rings");
1096                             break;
1097                         default:
1098                             break;
1099                     }
1100                     break;
1101                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1102                     switch (hfp_gsm_callsetup_status()){
1103                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1104                             hfp_gsm_handler(HFP_AG_INCOMING_CALL, 0, 0, NULL);
1105                             hfp_ag_set_callsetup_indicator();
1106                             hfp_ag_trigger_incoming_call();
1107                             log_info("AG call waiting");
1108                             break;
1109                         default:
1110                             break;
1111                     }
1112                     break;
1113                 default:
1114                     break;
1115             }
1116             break;
1117         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG:
1118             switch (hfp_gsm_call_status()){
1119                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1120                     switch (hfp_gsm_callsetup_status()){
1121                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1122                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, 0, 0, NULL);
1123                             hfp_ag_set_call_indicator();
1124                             hfp_ag_set_callsetup_indicator();
1125                             hfp_ag_ag_accept_call();
1126                             log_info("AG answers call, accept call by GSM");
1127                             break;
1128                         default:
1129                             break;
1130                     }
1131                     break;
1132                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1133                     switch (hfp_gsm_callsetup_status()){
1134                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1135                             log_info("AG: current call is placed on hold, incoming call gets active");
1136                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, 0, 0, NULL);
1137                             hfp_ag_set_callsetup_indicator();
1138                             hfp_ag_set_callheld_indicator();
1139                             hfp_ag_transfer_callsetup_state();
1140                             hfp_ag_transfer_callheld_state();
1141                             break;
1142                         default:
1143                             break;
1144                     }
1145                     break;
1146                 default:
1147                     break;
1148             }
1149             break;
1150 
1151         case HFP_AG_HELD_CALL_JOINED_BY_AG:
1152             switch (hfp_gsm_call_status()){
1153                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1154                     switch (hfp_gsm_callheld_status()){
1155                         case HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED:
1156                             log_info("AG: joining held call with active call");
1157                             hfp_gsm_handler(HFP_AG_HELD_CALL_JOINED_BY_AG, 0, 0, NULL);
1158                             hfp_ag_set_callheld_indicator();
1159                             hfp_ag_transfer_callheld_state();
1160                             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CONFERENCE_CALL);
1161                             break;
1162                         default:
1163                             break;
1164                     }
1165                     break;
1166                 default:
1167                     break;
1168             }
1169             break;
1170 
1171         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF:
1172             switch (hfp_gsm_call_status()){
1173                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1174                     switch (hfp_gsm_callsetup_status()){
1175                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1176                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, 0, 0, NULL);
1177                             hfp_ag_set_callsetup_indicator();
1178                             hfp_ag_set_call_indicator();
1179                             hfp_ag_hf_accept_call(hfp_connection);
1180                             hfp_connection->ok_pending = 1;
1181                             log_info("HF answers call, accept call by GSM");
1182                             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_ANSWERED);
1183                             break;
1184                         default:
1185                             break;
1186                     }
1187                     break;
1188                 default:
1189                     break;
1190             }
1191             break;
1192 
1193         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG:
1194             switch (hfp_gsm_call_status()){
1195                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1196                     switch (hfp_gsm_callsetup_status()){
1197                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1198                             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, 0, 0, NULL);
1199                             hfp_ag_response_and_hold_active = 1;
1200                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1201                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1202                             // as with regualr call
1203                             hfp_ag_set_call_indicator();
1204                             hfp_ag_set_callsetup_indicator();
1205                             hfp_ag_ag_accept_call();
1206                             log_info("AG response and hold - hold by AG");
1207                             break;
1208                         default:
1209                             break;
1210                     }
1211                     break;
1212                 default:
1213                     break;
1214             }
1215             break;
1216 
1217         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF:
1218             switch (hfp_gsm_call_status()){
1219                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1220                     switch (hfp_gsm_callsetup_status()){
1221                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1222                             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, 0, 0, NULL);
1223                             hfp_ag_response_and_hold_active = 1;
1224                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1225                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1226                             // as with regualr call
1227                             hfp_ag_set_call_indicator();
1228                             hfp_ag_set_callsetup_indicator();
1229                             hfp_ag_hf_accept_call(hfp_connection);
1230                             log_info("AG response and hold - hold by HF");
1231                             break;
1232                         default:
1233                             break;
1234                     }
1235                     break;
1236                 default:
1237                     break;
1238             }
1239             break;
1240 
1241         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG:
1242         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF:
1243             if (!hfp_ag_response_and_hold_active) break;
1244             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1245             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, 0, 0, NULL);
1246             hfp_ag_response_and_hold_active = 0;
1247             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED;
1248             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1249             log_info("Held Call accepted and active");
1250             break;
1251 
1252         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG:
1253         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF:
1254             if (!hfp_ag_response_and_hold_active) break;
1255             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1256             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, 0, 0, NULL);
1257             hfp_ag_response_and_hold_active = 0;
1258             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1259             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1260             // from terminate by ag
1261             hfp_ag_set_call_indicator();
1262             hfp_ag_trigger_terminate_call();
1263             break;
1264 
1265         case HFP_AG_TERMINATE_CALL_BY_HF:
1266             switch (hfp_gsm_call_status()){
1267                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1268                     switch (hfp_gsm_callsetup_status()){
1269                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1270                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1271                             hfp_ag_set_callsetup_indicator();
1272                             hfp_ag_transfer_callsetup_state();
1273                             hfp_ag_trigger_reject_call();
1274                             log_info("HF Rejected Incoming call, AG terminate call");
1275                             break;
1276                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1277                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1278                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1279                             hfp_ag_set_callsetup_indicator();
1280                             hfp_ag_transfer_callsetup_state();
1281                             log_info("AG terminate outgoing call process");
1282                             break;
1283                         default:
1284                             break;
1285                     }
1286                     break;
1287                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1288                     hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1289                     hfp_ag_set_callsetup_indicator();
1290                     hfp_ag_set_call_indicator();
1291                     hfp_ag_trigger_terminate_call();
1292                     log_info("AG terminate call");
1293                     break;
1294                 default:
1295                     break;
1296             }
1297             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_TERMINATED);
1298             break;
1299 
1300         case HFP_AG_TERMINATE_CALL_BY_AG:
1301             switch (hfp_gsm_call_status()){
1302                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1303                     switch (hfp_gsm_callsetup_status()){
1304                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1305                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_AG, 0, 0, NULL);
1306                             hfp_ag_set_callsetup_indicator();
1307                             hfp_ag_trigger_reject_call();
1308                             log_info("AG Rejected Incoming call, AG terminate call");
1309                             break;
1310                         default:
1311                             break;
1312                     }
1313                     break;
1314                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1315                     hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_AG, 0, 0, NULL);
1316                     hfp_ag_set_callsetup_indicator();
1317                     hfp_ag_set_call_indicator();
1318                     hfp_ag_trigger_terminate_call();
1319                     log_info("AG terminate call");
1320                     break;
1321                 default:
1322                     break;
1323             }
1324             break;
1325         case HFP_AG_CALL_DROPPED:
1326             switch (hfp_gsm_call_status()){
1327                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1328                     switch (hfp_gsm_callsetup_status()){
1329                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1330                             hfp_ag_stop_ringing();
1331                             log_info("Incoming call interrupted");
1332                             break;
1333                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1334                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1335                             log_info("Outgoing call interrupted\n");
1336                             log_info("AG notify call dropped\n");
1337                             break;
1338                         default:
1339                             break;
1340                     }
1341                     hfp_gsm_handler(HFP_AG_CALL_DROPPED, 0, 0, NULL);
1342                     hfp_ag_set_callsetup_indicator();
1343                     hfp_ag_transfer_callsetup_state();
1344                     hfp_ag_trigger_terminate_call();
1345                     break;
1346                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1347                     if (hfp_ag_response_and_hold_active) {
1348                         hfp_gsm_handler(HFP_AG_CALL_DROPPED, 0, 0, NULL);
1349                         hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1350                         hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1351                     }
1352                     hfp_gsm_handler(HFP_AG_CALL_DROPPED, 0, 0, NULL);
1353                     hfp_ag_set_callsetup_indicator();
1354                     hfp_ag_set_call_indicator();
1355                     hfp_ag_trigger_terminate_call();
1356                     log_info("AG notify call dropped");
1357                     break;
1358                 default:
1359                     break;
1360             }
1361             break;
1362 
1363         case HFP_AG_OUTGOING_CALL_INITIATED:
1364             // directly reject call if number of free slots is exceeded
1365             if (!hfp_gsm_call_possible()){
1366                 hfp_connection->send_error = 1;
1367                 hfp_ag_run_for_context(hfp_connection);
1368                 break;
1369             }
1370             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_INITIATED, 0, 0, (const char *) &hfp_connection->line_buffer[3]);
1371 
1372             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1373 
1374             hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, (const char *) &hfp_connection->line_buffer[3]);
1375             break;
1376 
1377         case HFP_AG_OUTGOING_REDIAL_INITIATED:{
1378             // directly reject call if number of free slots is exceeded
1379             if (!hfp_gsm_call_possible()){
1380                 hfp_connection->send_error = 1;
1381                 hfp_ag_run_for_context(hfp_connection);
1382                 break;
1383             }
1384 
1385             hfp_gsm_handler(HFP_AG_OUTGOING_REDIAL_INITIATED, 0, 0, NULL);
1386             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1387 
1388             log_info("Redial last number");
1389             char * last_dialed_number = hfp_gsm_last_dialed_number();
1390 
1391             if (strlen(last_dialed_number) > 0){
1392                 log_info("Last number exists: accept call");
1393                 hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, last_dialed_number);
1394             } else {
1395                 log_info("log_infoLast number missing: reject call");
1396                 hfp_ag_handle_reject_incoming_call();
1397             }
1398             break;
1399         }
1400         case HFP_AG_OUTGOING_CALL_REJECTED:
1401             hfp_ag_handle_reject_incoming_call();
1402             break;
1403 
1404         case HFP_AG_OUTGOING_CALL_ACCEPTED:{
1405             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1406             if (!hfp_connection){
1407                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1408                 break;
1409             }
1410 
1411             hfp_connection->ok_pending = 1;
1412             hfp_connection->call_state = HFP_CALL_OUTGOING_DIALING;
1413 
1414             // trigger callsetup to be
1415             int put_call_on_hold = hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT;
1416             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_ACCEPTED, 0, 0, NULL);
1417 
1418             hfp_ag_set_callsetup_indicator();
1419             indicator_index = get_ag_indicator_index_for_name("callsetup");
1420             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1421 
1422             // put current call on hold if active
1423             if (put_call_on_hold){
1424                 log_info("AG putting current call on hold for new outgoing calllog_info");
1425                 hfp_ag_set_callheld_indicator();
1426                 indicator_index = get_ag_indicator_index_for_name("callheld");
1427                 hfp_ag_send_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[indicator_index]);
1428             }
1429 
1430             // start audio if needed
1431             hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
1432             break;
1433         }
1434         case HFP_AG_OUTGOING_CALL_RINGING:
1435             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1436             if (!hfp_connection){
1437                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in dialing state");
1438                 break;
1439             }
1440 
1441             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_RINGING, 0, 0, NULL);
1442             hfp_connection->call_state = HFP_CALL_OUTGOING_RINGING;
1443             hfp_ag_set_callsetup_indicator();
1444             hfp_ag_transfer_callsetup_state();
1445             break;
1446 
1447         case HFP_AG_OUTGOING_CALL_ESTABLISHED:{
1448             // get outgoing call
1449             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_RINGING);
1450             if (!hfp_connection){
1451                 hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1452             }
1453             if (!hfp_connection){
1454                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection");
1455                 break;
1456             }
1457 
1458             int CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS = hfp_gsm_callheld_status() == HFP_CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS;
1459             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_ESTABLISHED, 0, 0, NULL);
1460             hfp_connection->call_state = HFP_CALL_ACTIVE;
1461             hfp_ag_set_callsetup_indicator();
1462             hfp_ag_set_call_indicator();
1463             hfp_ag_transfer_call_state();
1464             hfp_ag_transfer_callsetup_state();
1465             if (CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS){
1466                 hfp_ag_set_callheld_indicator();
1467                 hfp_ag_transfer_callheld_state();
1468             }
1469             break;
1470         }
1471 
1472         case HFP_AG_CALL_HOLD_USER_BUSY:
1473             hfp_gsm_handler(HFP_AG_CALL_HOLD_USER_BUSY, 0, 0, NULL);
1474             hfp_ag_set_callsetup_indicator();
1475             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1476             hfp_connection->call_state = HFP_CALL_ACTIVE;
1477             log_info("AG: Call Waiting, User Busy");
1478             break;
1479 
1480         case HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1481             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1482             int call_held = hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1483 
1484             // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1485             if (call_held || call_setup_in_progress){
1486                 hfp_gsm_handler(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index,
1487                                 0, NULL);
1488 
1489             }
1490 
1491             if (call_setup_in_progress){
1492                 log_info("AG: Call Dropped, Accept new call");
1493                 hfp_ag_set_callsetup_indicator();
1494                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1495             } else {
1496                 log_info("AG: Call Dropped, Resume held call");
1497             }
1498             if (call_held){
1499                 hfp_ag_set_callheld_indicator();
1500                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1501             }
1502 
1503             hfp_connection->call_state = HFP_CALL_ACTIVE;
1504             break;
1505         }
1506 
1507         case HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1508             // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1509             // only update if callsetup changed
1510             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1511             hfp_gsm_handler(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index, 0,
1512                             NULL);
1513 
1514             if (call_setup_in_progress){
1515                 log_info("AG: Call on Hold, Accept new call");
1516                 hfp_ag_set_callsetup_indicator();
1517                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1518             } else {
1519                 log_info("AG: Swap calls");
1520             }
1521 
1522             hfp_ag_set_callheld_indicator();
1523             // hfp_ag_set_callheld_state(HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED);
1524             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1525             hfp_connection->call_state = HFP_CALL_ACTIVE;
1526             break;
1527         }
1528 
1529         case HFP_AG_CALL_HOLD_ADD_HELD_CALL:
1530             // Adds a held call to the conversation.
1531             if (hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD){
1532                 log_info("AG: Join 3-way-call");
1533                 hfp_gsm_handler(HFP_AG_CALL_HOLD_ADD_HELD_CALL, 0, 0, NULL);
1534                 hfp_ag_set_callheld_indicator();
1535                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1536                 hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CONFERENCE_CALL);
1537             }
1538             hfp_connection->call_state = HFP_CALL_ACTIVE;
1539             break;
1540         case HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS:
1541             // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer)
1542             hfp_gsm_handler(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, 0, 0, NULL);
1543             log_info("AG: Transfer call -> Connect two calls and disconnect");
1544             hfp_ag_set_call_indicator();
1545             hfp_ag_set_callheld_indicator();
1546             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1547             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1548             hfp_connection->call_state = HFP_CALL_IDLE;
1549             break;
1550 
1551         default:
1552             break;
1553     }
1554 
1555 
1556 }
1557 
1558 
1559 static void hfp_ag_send_call_status(hfp_connection_t * hfp_connection, int call_index){
1560     hfp_gsm_call_t * active_call = hfp_gsm_call(call_index);
1561     if (!active_call) return;
1562 
1563     int idx = active_call->index;
1564     hfp_enhanced_call_dir_t dir = active_call->direction;
1565     hfp_enhanced_call_status_t status = active_call->enhanced_status;
1566     hfp_enhanced_call_mode_t mode = active_call->mode;
1567     hfp_enhanced_call_mpty_t mpty = active_call->mpty;
1568     uint8_t type = active_call->clip_type;
1569     char * number = active_call->clip_number;
1570 
1571     char buffer[100];
1572     // TODO: check length of a buffer, to fit the MTU
1573     int offset = snprintf(buffer, sizeof(buffer), "\r\n%s: %d,%d,%d,%d,%d", HFP_LIST_CURRENT_CALLS, idx, dir, status, mode, mpty);
1574     if (number){
1575         offset += snprintf(buffer+offset, sizeof(buffer)-offset-3, ", \"%s\",%u", number, type);
1576     }
1577     snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n");
1578     log_info("hfp_ag_send_current_call_status 000 index %d, dir %d, status %d, mode %d, mpty %d, type %d, number %s", idx, dir, status,
1579        mode, mpty, type, number);
1580     send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1581 }
1582 
1583 
1584 // sends pending command, returns if command was sent
1585 static int hfp_ag_send_commands(hfp_connection_t *hfp_connection){
1586 
1587     if (hfp_connection->send_status_of_current_calls){
1588         hfp_connection->ok_pending = 0;
1589         if (hfp_connection->next_call_index < hfp_gsm_get_number_of_calls()){
1590             hfp_connection->next_call_index++;
1591             hfp_ag_send_call_status(hfp_connection, hfp_connection->next_call_index);
1592             return 1;
1593         } else {
1594             // TODO: this code should be removed. check a) before setting send_status_of_current_calls, or b) right before hfp_ag_send_call_status above
1595             hfp_connection->next_call_index = 0;
1596             hfp_connection->ok_pending = 1;
1597             hfp_connection->send_status_of_current_calls = 0;
1598         }
1599     }
1600 
1601     if (hfp_connection->ag_notify_incoming_call_waiting){
1602         hfp_connection->ag_notify_incoming_call_waiting = 0;
1603         hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1604         return 1;
1605     }
1606 
1607     if (hfp_connection->command == HFP_CMD_UNKNOWN){
1608         hfp_connection->ok_pending = 0;
1609         hfp_connection->send_error = 0;
1610         hfp_connection->command = HFP_CMD_NONE;
1611         hfp_ag_send_error(hfp_connection->rfcomm_cid);
1612         return 1;
1613     }
1614 
1615     if (hfp_connection->send_error){
1616         hfp_connection->send_error = 0;
1617         hfp_connection->command = HFP_CMD_NONE;
1618         hfp_ag_send_error(hfp_connection->rfcomm_cid);
1619         return 1;
1620     }
1621 
1622     // note: before update AG indicators and ok_pending
1623     if (hfp_connection->send_response_and_hold_status){
1624         int status = hfp_connection->send_response_and_hold_status - 1;
1625         hfp_connection->send_response_and_hold_status = 0;
1626         hfp_ag_send_set_response_and_hold(hfp_connection->rfcomm_cid, status);
1627         return 1;
1628     }
1629 
1630     if (hfp_connection->ok_pending){
1631         hfp_connection->ok_pending = 0;
1632         hfp_connection->command = HFP_CMD_NONE;
1633         hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1634         return 1;
1635     }
1636 
1637     // update AG indicators
1638     if (hfp_connection->ag_indicators_status_update_bitmap){
1639         int i;
1640         for (i=0;i<hfp_connection->ag_indicators_nr;i++){
1641             if (get_bit(hfp_connection->ag_indicators_status_update_bitmap, i)){
1642                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, i, 0);
1643                 if (!hfp_connection->enable_status_update_for_ag_indicators) {
1644                     log_info("+CMER:3,0,0,0 - not sending update for '%s'", hfp_ag_indicators[i].name);
1645                     break;
1646                 }
1647                 hfp_ag_send_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[i]);
1648                 return 1;
1649             }
1650         }
1651     }
1652 
1653     if (hfp_connection->ag_ring){
1654         hfp_connection->ag_ring = 0;
1655         hfp_connection->command = HFP_CMD_NONE;
1656         hfp_ag_send_ring(hfp_connection->rfcomm_cid);
1657         return 1;
1658     }
1659 
1660     if (hfp_connection->ag_send_clip){
1661         hfp_connection->ag_send_clip = 0;
1662         hfp_connection->command = HFP_CMD_NONE;
1663         hfp_ag_send_clip(hfp_connection->rfcomm_cid);
1664         return 1;
1665     }
1666 
1667     if (hfp_connection->send_phone_number_for_voice_tag){
1668         hfp_connection->send_phone_number_for_voice_tag = 0;
1669         hfp_connection->command = HFP_CMD_NONE;
1670         hfp_connection->ok_pending = 1;
1671         hfp_ag_send_phone_number_for_voice_tag_cmd(hfp_connection->rfcomm_cid);
1672         return 1;
1673     }
1674 
1675     if (hfp_connection->send_subscriber_number){
1676         if (hfp_connection->next_subscriber_number_to_send < subscriber_numbers_count){
1677             hfp_phone_number_t phone = subscriber_numbers[hfp_connection->next_subscriber_number_to_send++];
1678             hfp_send_subscriber_number_cmd(hfp_connection->rfcomm_cid, phone.type, phone.number);
1679         } else {
1680             hfp_connection->send_subscriber_number = 0;
1681             hfp_connection->next_subscriber_number_to_send = 0;
1682             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1683         }
1684         hfp_connection->command = HFP_CMD_NONE;
1685         return 1;
1686     }
1687 
1688     if (hfp_connection->send_microphone_gain){
1689         hfp_connection->send_microphone_gain = 0;
1690         hfp_connection->command = HFP_CMD_NONE;
1691         hfp_ag_send_set_microphone_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->microphone_gain);
1692         return 1;
1693     }
1694 
1695     if (hfp_connection->send_speaker_gain){
1696         hfp_connection->send_speaker_gain = 0;
1697         hfp_connection->command = HFP_CMD_NONE;
1698         hfp_ag_send_set_speaker_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->speaker_gain);
1699         return 1;
1700     }
1701 
1702     if (hfp_connection->send_ag_status_indicators){
1703         hfp_connection->send_ag_status_indicators = 0;
1704         hfp_ag_send_retrieve_indicators_status_cmd(hfp_connection->rfcomm_cid);
1705         return 1;
1706     }
1707 
1708     return 0;
1709 }
1710 
1711 static void hfp_ag_run_for_context(hfp_connection_t *hfp_connection){
1712 
1713 	btstack_assert(hfp_connection != NULL);
1714 	btstack_assert(hfp_connection->local_role == HFP_ROLE_AG);
1715 
1716 	// during SDP query, RFCOMM CID is not set
1717 	if (hfp_connection->rfcomm_cid == 0) return;
1718 
1719     // assert command could be sent
1720     if (hci_can_send_command_packet_now() == 0) return;
1721 
1722 #ifdef ENABLE_CC256X_ASSISTED_HFP
1723     // WBS Disassociate
1724     if (hfp_connection->cc256x_send_wbs_disassociate){
1725         hfp_connection->cc256x_send_wbs_disassociate = false;
1726         hci_send_cmd(&hci_ti_wbs_disassociate);
1727         return;
1728     }
1729     // Write Codec Config
1730     if (hfp_connection->cc256x_send_write_codec_config){
1731         hfp_connection->cc256x_send_write_codec_config = false;
1732         hfp_cc256x_write_codec_config(hfp_connection);
1733         return;
1734     }
1735     // WBS Associate
1736     if (hfp_connection->cc256x_send_wbs_associate){
1737         hfp_connection->cc256x_send_wbs_associate = false;
1738         hci_send_cmd(&hci_ti_wbs_associate, hfp_connection->acl_handle);
1739         return;
1740     }
1741 #endif
1742 #ifdef ENABLE_BCM_PCM_WBS
1743     // Enable WBS
1744     if (hfp_connection->bcm_send_enable_wbs){
1745         hfp_connection->bcm_send_enable_wbs = false;
1746         hci_send_cmd(&hci_bcm_enable_wbs, 1, 2);
1747         return;
1748     }
1749     // Write I2S/PCM params
1750     if (hfp_connection->bcm_send_write_i2spcm_interface_param){
1751         hfp_connection->bcm_send_write_i2spcm_interface_param = false;
1752         hfp_bcm_write_i2spcm_interface_param(hfp_connection);
1753         return;
1754     }
1755     // Disable WBS
1756     if (hfp_connection->bcm_send_disable_wbs){
1757         hfp_connection->bcm_send_disable_wbs = false;
1758         hci_send_cmd(&hci_bcm_enable_wbs, 0, 2);
1759         return;
1760     }
1761 #endif
1762 
1763     if (!rfcomm_can_send_packet_now(hfp_connection->rfcomm_cid)) {
1764         log_info("hfp_ag_run_for_context: request can send for 0x%02x", hfp_connection->rfcomm_cid);
1765         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1766         return;
1767     }
1768 
1769     int cmd_sent = hfp_ag_send_commands(hfp_connection);
1770 
1771     // trigger codec exchange if requested by app
1772     if (hfp_connection->trigger_codec_exchange){
1773         log_info("trigger codec, command %u, codec state %u", hfp_connection->command, hfp_connection->codecs_state);
1774     }
1775 
1776     if (hfp_connection->trigger_codec_exchange && (hfp_connection->command == HFP_CMD_NONE)){
1777         switch (hfp_connection->codecs_state){
1778             case HFP_CODECS_IDLE:
1779             case HFP_CODECS_RECEIVED_LIST:
1780             case HFP_CODECS_AG_RESEND_COMMON_CODEC:
1781             case HFP_CODECS_ERROR:
1782                 hfp_connection->trigger_codec_exchange = 0;
1783                 hfp_connection->command = HFP_CMD_AG_SEND_COMMON_CODEC;
1784                 break;
1785             default:
1786                 break;
1787         }
1788     }
1789 
1790     if (!cmd_sent){
1791         cmd_sent = hfp_ag_run_for_context_service_level_connection(hfp_connection);
1792     }
1793 
1794     if (!cmd_sent){
1795         cmd_sent = hfp_ag_run_for_context_service_level_connection_queries(hfp_connection);
1796     }
1797 
1798     if (!cmd_sent){
1799         cmd_sent = call_setup_state_machine(hfp_connection);
1800     }
1801 
1802     if (!cmd_sent){
1803         cmd_sent = hfp_ag_run_for_audio_connection(hfp_connection);
1804     }
1805 
1806     if ((hfp_connection->command == HFP_CMD_NONE) && !cmd_sent){
1807         // log_info("hfp_connection->command == HFP_CMD_NONE");
1808         switch(hfp_connection->state){
1809             case HFP_W2_DISCONNECT_RFCOMM:
1810                 hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED;
1811                 rfcomm_disconnect(hfp_connection->rfcomm_cid);
1812                 break;
1813             default:
1814                 break;
1815         }
1816     }
1817 
1818     if (cmd_sent){
1819         hfp_connection->command = HFP_CMD_NONE;
1820         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1821     }
1822 }
1823 
1824 static hfp_generic_status_indicator_t *get_hf_indicator_by_number(int number){
1825     int i;
1826     for (i=0;i< hfp_generic_status_indicators_nr;i++){
1827         hfp_generic_status_indicator_t * indicator = &hfp_generic_status_indicators[i];
1828         if (indicator->uuid == number){
1829             return indicator;
1830         }
1831     }
1832     return NULL;
1833 }
1834 
1835 static int hfp_parser_is_end_of_line(uint8_t byte){
1836     return (byte == '\n') || (byte == '\r');
1837 }
1838 
1839 static void hfp_ag_handle_rfcomm_data(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1840     UNUSED(packet_type);    // ok: only called with RFCOMM_DATA_PACKET
1841 
1842     // assertion: size >= 1 as rfcomm.c does not deliver empty packets
1843     if (size < 1) return;
1844 
1845     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_rfcomm_cid(channel);
1846     if (!hfp_connection) return;
1847 
1848     hfp_log_rfcomm_message("HFP_AG_RX", packet, size);
1849 #ifdef ENABLE_HFP_AT_MESSAGES
1850     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_RECEIVED, (char *) packet);
1851 #endif
1852 
1853     // process messages byte-wise
1854     int pos;
1855     for (pos = 0; pos < size ; pos++){
1856         hfp_parse(hfp_connection, packet[pos], 0);
1857 
1858         // parse until end of line
1859         if (!hfp_parser_is_end_of_line(packet[pos])) continue;
1860 
1861         hfp_generic_status_indicator_t * indicator;
1862         switch(hfp_connection->command){
1863             case HFP_CMD_RESPONSE_AND_HOLD_QUERY:
1864                 if (hfp_ag_response_and_hold_active){
1865                     hfp_connection->send_response_and_hold_status = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD + 1;
1866                 }
1867                 hfp_connection->ok_pending = 1;
1868                 break;
1869             case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1870                 switch(hfp_connection->ag_response_and_hold_action){
1871                     case HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD:
1872                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, hfp_connection);
1873                         break;
1874                     case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED:
1875                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF, hfp_connection);
1876                         break;
1877                     case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED:
1878                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF, hfp_connection);
1879                         break;
1880                     default:
1881                         break;
1882                 }
1883                 hfp_connection->ok_pending = 1;
1884                 break;
1885             case HFP_CMD_HF_INDICATOR_STATUS:
1886                 hfp_connection->command = HFP_CMD_NONE;
1887                 // find indicator by assigned number
1888                 indicator = get_hf_indicator_by_number(hfp_connection->parser_indicator_index);
1889                 if (!indicator){
1890                     hfp_connection->send_error = 1;
1891                     break;
1892                 }
1893                 switch (indicator->uuid){
1894                     case 1: // enhanced security
1895                         if (hfp_connection->parser_indicator_value > 1) {
1896                             hfp_connection->send_error = 1;
1897                             return;
1898                         }
1899                         log_info("HF Indicator 'enhanced security' set to %u", (unsigned int) hfp_connection->parser_indicator_value);
1900                         break;
1901                     case 2: // battery level
1902                         if (hfp_connection->parser_indicator_value > 100){
1903                             hfp_connection->send_error = 1;
1904                             return;
1905                         }
1906                         log_info("HF Indicator 'battery' set to %u", (unsigned int) hfp_connection->parser_indicator_value);
1907                         break;
1908                     default:
1909                         log_info("HF Indicator unknown set to %u", (unsigned int) hfp_connection->parser_indicator_value);
1910                         break;
1911                 }
1912                 hfp_connection->ok_pending = 1;
1913                 break;
1914             case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1915                 // expected by SLC state machine
1916                 if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) break;
1917                 hfp_connection->send_ag_indicators_segment = 0;
1918                 hfp_connection->send_ag_status_indicators = 1;
1919                 break;
1920             case HFP_CMD_LIST_CURRENT_CALLS:
1921                 hfp_connection->command = HFP_CMD_NONE;
1922                 hfp_connection->next_call_index = 0;
1923                 hfp_connection->send_status_of_current_calls = 1;
1924                 break;
1925             case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1926                 if (subscriber_numbers_count == 0){
1927                     hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1928                     break;
1929                 }
1930                 hfp_connection->next_subscriber_number_to_send = 0;
1931                 hfp_connection->send_subscriber_number = 1;
1932                 break;
1933             case HFP_CMD_TRANSMIT_DTMF_CODES:
1934             {
1935                 hfp_connection->command = HFP_CMD_NONE;
1936                 char buffer[2];
1937                 buffer[0] = (char) hfp_connection->ag_dtmf_code;
1938                 buffer[1] = 0;
1939                 hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_TRANSMIT_DTMF_CODES, buffer);
1940                 break;
1941             }
1942             case HFP_CMD_HF_REQUEST_PHONE_NUMBER:
1943                 hfp_connection->command = HFP_CMD_NONE;
1944                 hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_ATTACH_NUMBER_TO_VOICE_TAG);
1945                 break;
1946             case HFP_CMD_TURN_OFF_EC_AND_NR:
1947                 hfp_connection->command = HFP_CMD_NONE;
1948                 if (get_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION)){
1949                     hfp_connection->ok_pending = 1;
1950                     hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION, hfp_connection->ag_echo_and_noise_reduction);
1951                     log_info("AG: EC/NR = %u", hfp_connection->ag_echo_and_noise_reduction);
1952                 } else {
1953                     hfp_connection->send_error = 1;
1954                 }
1955                 break;
1956             case HFP_CMD_CALL_ANSWERED:
1957                 hfp_connection->command = HFP_CMD_NONE;
1958                 log_info("HFP: ATA");
1959                 hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, hfp_connection);
1960                 break;
1961             case HFP_CMD_HANG_UP_CALL:
1962                 hfp_connection->command = HFP_CMD_NONE;
1963                 hfp_connection->ok_pending = 1;
1964                 hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_HF, hfp_connection);
1965                 break;
1966             case HFP_CMD_CALL_HOLD: {
1967                 hfp_connection->command = HFP_CMD_NONE;
1968                 hfp_connection->ok_pending = 1;
1969 
1970                 switch (hfp_connection->ag_call_hold_action){
1971                     case 0:
1972                         // Releases all held calls or sets User Determined User Busy (UDUB) for a waiting call.
1973                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_USER_BUSY, hfp_connection);
1974                         break;
1975                     case 1:
1976                         // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1977                         // Where both a held and a waiting call exist, the above procedures shall apply to the
1978                         // waiting call (i.e., not to the held call) in conflicting situation.
1979                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
1980                         break;
1981                     case 2:
1982                         // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1983                         // Where both a held and a waiting call exist, the above procedures shall apply to the
1984                         // waiting call (i.e., not to the held call) in conflicting situation.
1985                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
1986                         break;
1987                     case 3:
1988                         // Adds a held call to the conversation.
1989                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_ADD_HELD_CALL, hfp_connection);
1990                         break;
1991                     case 4:
1992                         // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer).
1993                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, hfp_connection);
1994                         break;
1995                     default:
1996                         break;
1997                 }
1998 				hfp_connection->call_index = 0;
1999                 break;
2000             }
2001             case HFP_CMD_CALL_PHONE_NUMBER:
2002                 hfp_connection->command = HFP_CMD_NONE;
2003                 hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED, hfp_connection);
2004                 break;
2005             case HFP_CMD_REDIAL_LAST_NUMBER:
2006                 hfp_connection->command = HFP_CMD_NONE;
2007                 hfp_ag_call_sm(HFP_AG_OUTGOING_REDIAL_INITIATED, hfp_connection);
2008                 break;
2009             case HFP_CMD_ENABLE_CLIP:
2010                 hfp_connection->command = HFP_CMD_NONE;
2011                 log_info("hfp: clip set, now: %u", hfp_connection->clip_enabled);
2012                 hfp_connection->ok_pending = 1;
2013                 break;
2014             case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
2015                 hfp_connection->command = HFP_CMD_NONE;
2016                 log_info("hfp: call waiting notification set, now: %u", hfp_connection->call_waiting_notification_enabled);
2017                 hfp_connection->ok_pending = 1;
2018                 break;
2019             case HFP_CMD_SET_SPEAKER_GAIN:
2020                 hfp_connection->command = HFP_CMD_NONE;
2021                 hfp_connection->ok_pending = 1;
2022                 log_info("HF speaker gain = %u", hfp_connection->speaker_gain);
2023                 break;
2024             case HFP_CMD_SET_MICROPHONE_GAIN:
2025                 hfp_connection->command = HFP_CMD_NONE;
2026                 hfp_connection->ok_pending = 1;
2027                 log_info("HF microphone gain = %u", hfp_connection->microphone_gain);
2028                 break;
2029             default:
2030                 break;
2031         }
2032     }
2033 }
2034 
2035 static void hfp_ag_run(void){
2036     btstack_linked_list_iterator_t it;
2037     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2038     while (btstack_linked_list_iterator_has_next(&it)){
2039         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2040         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2041         hfp_ag_run_for_context(hfp_connection);
2042     }
2043 }
2044 
2045 static void hfp_ag_rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2046     switch (packet_type){
2047         case RFCOMM_DATA_PACKET:
2048             hfp_ag_handle_rfcomm_data(packet_type, channel, packet, size);
2049             break;
2050         case HCI_EVENT_PACKET:
2051             if (packet[0] == RFCOMM_EVENT_CAN_SEND_NOW){
2052                 uint16_t rfcomm_cid = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
2053                 hfp_ag_run_for_context(get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid));
2054                 return;
2055             }
2056             hfp_handle_rfcomm_event(packet_type, channel, packet, size, HFP_ROLE_AG);
2057             break;
2058         default:
2059             break;
2060     }
2061 
2062     hfp_ag_run();
2063 }
2064 
2065 static void hfp_ag_hci_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2066     hfp_handle_hci_event(packet_type, channel, packet, size, HFP_ROLE_AG);
2067     hfp_ag_run();
2068 }
2069 
2070 void hfp_ag_init_codecs(int codecs_nr, uint8_t * codecs){
2071     if (codecs_nr > HFP_MAX_NUM_CODECS){
2072         log_error("hfp_init: codecs_nr (%d) > HFP_MAX_NUM_CODECS (%d)", codecs_nr, HFP_MAX_NUM_CODECS);
2073         return;
2074     }
2075     int i;
2076     hfp_codecs_nr = codecs_nr;
2077     for (i=0; i < codecs_nr; i++){
2078         hfp_codecs[i] = codecs[i];
2079     }
2080 }
2081 
2082 void hfp_ag_init_supported_features(uint32_t supported_features){
2083     hfp_supported_features = supported_features;
2084 }
2085 
2086 void hfp_ag_init_ag_indicators(int ag_indicators_nr, hfp_ag_indicator_t * ag_indicators){
2087     hfp_ag_indicators_nr = ag_indicators_nr;
2088     (void)memcpy(hfp_ag_indicators, ag_indicators,
2089                  ag_indicators_nr * sizeof(hfp_ag_indicator_t));
2090 }
2091 
2092 void hfp_ag_init_hf_indicators(int hf_indicators_nr, hfp_generic_status_indicator_t * hf_indicators){
2093     if (hf_indicators_nr > HFP_MAX_NUM_INDICATORS) return;
2094     hfp_generic_status_indicators_nr = hf_indicators_nr;
2095     (void)memcpy(hfp_generic_status_indicators, hf_indicators,
2096                  hf_indicators_nr * sizeof(hfp_generic_status_indicator_t));
2097 }
2098 
2099 void hfp_ag_init_call_hold_services(int call_hold_services_nr, const char * call_hold_services[]){
2100     hfp_ag_call_hold_services_nr = call_hold_services_nr;
2101     (void)memcpy(hfp_ag_call_hold_services, call_hold_services,
2102                  call_hold_services_nr * sizeof(char *));
2103 }
2104 
2105 
2106 void hfp_ag_init(uint16_t rfcomm_channel_nr){
2107 
2108     hfp_init();
2109     hfp_ag_call_hold_services_nr = 0;
2110     hfp_ag_response_and_hold_active = 0;
2111     hfp_ag_indicators_nr = 0;
2112     hfp_codecs_nr = 0;
2113     hfp_supported_features = HFP_DEFAULT_AG_SUPPORTED_FEATURES;
2114     subscriber_numbers = NULL;
2115     subscriber_numbers_count = 0;
2116 
2117     hfp_ag_hci_event_callback_registration.callback = &hfp_ag_hci_event_packet_handler;
2118     hci_add_event_handler(&hfp_ag_hci_event_callback_registration);
2119 
2120     rfcomm_register_service(&hfp_ag_rfcomm_packet_handler, rfcomm_channel_nr, 0xffff);
2121 
2122     // used to set packet handler for outgoing rfcomm connections - could be handled by emitting an event to us
2123     hfp_set_ag_rfcomm_packet_handler(&hfp_ag_rfcomm_packet_handler);
2124 
2125     hfp_gsm_init();
2126 }
2127 
2128 void hfp_ag_deinit(void){
2129     hfp_deinit();
2130     hfp_gsm_deinit();
2131     (void) memset(&hfp_ag_hci_event_callback_registration, 0, sizeof(btstack_packet_callback_registration_t));
2132     (void) memset(&hfp_ag_callback, 0, sizeof(btstack_packet_handler_t));
2133     (void) memset(&hfp_ag_call_hold_services, 0, sizeof(hfp_ag_call_hold_services));
2134     (void) memset(&hfp_ag_response_and_hold_state, 0, sizeof(hfp_response_and_hold_state_t));
2135 }
2136 
2137 void hfp_ag_establish_service_level_connection(bd_addr_t bd_addr){
2138     hfp_establish_service_level_connection(bd_addr, BLUETOOTH_SERVICE_CLASS_HANDSFREE, HFP_ROLE_AG);
2139 }
2140 
2141 void hfp_ag_release_service_level_connection(hci_con_handle_t acl_handle){
2142     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2143     if (!hfp_connection){
2144         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2145         return;
2146     }
2147     hfp_release_service_level_connection(hfp_connection);
2148     hfp_ag_run_for_context(hfp_connection);
2149 }
2150 
2151 void hfp_ag_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle, hfp_cme_error_t error){
2152     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2153     if (!hfp_connection){
2154         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2155         return;
2156     }
2157     hfp_connection->extended_audio_gateway_error = 0;
2158     if (!hfp_connection->enable_extended_audio_gateway_error_report){
2159         return;
2160     }
2161     hfp_connection->extended_audio_gateway_error = error;
2162     hfp_ag_run_for_context(hfp_connection);
2163 }
2164 
2165 static void hfp_ag_setup_audio_connection(hfp_connection_t * hfp_connection){
2166     log_info("hfp_ag_setup_audio_connection state %u", hfp_connection->state);
2167     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return;
2168     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
2169 
2170     hfp_connection->establish_audio_connection = 1;
2171     if (!has_codec_negotiation_feature(hfp_connection)){
2172         log_info("hfp_ag_establish_audio_connection - no codec negotiation feature, using CVSD");
2173         hfp_connection->negotiated_codec = HFP_CODEC_CVSD;
2174         hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
2175         // now, pick link settings
2176         hfp_init_link_settings(hfp_connection, hfp_ag_esco_s4_supported(hfp_connection));
2177 #ifdef ENABLE_CC256X_ASSISTED_HFP
2178         hfp_cc256x_prepare_for_sco(hfp_connection);
2179 #endif
2180         return;
2181     }
2182 
2183     hfp_connection->trigger_codec_exchange = 1;
2184 }
2185 
2186 void hfp_ag_establish_audio_connection(hci_con_handle_t acl_handle){
2187     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2188     if (!hfp_connection){
2189         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2190         return;
2191     }
2192     hfp_connection->trigger_codec_exchange = 0;
2193     hfp_connection->establish_audio_connection = 0;
2194     hfp_ag_setup_audio_connection(hfp_connection);
2195     hfp_ag_run_for_context(hfp_connection);
2196 }
2197 
2198 void hfp_ag_release_audio_connection(hci_con_handle_t acl_handle){
2199     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2200     if (!hfp_connection){
2201         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2202         return;
2203     }
2204     hfp_release_audio_connection(hfp_connection);
2205     hfp_ag_run_for_context(hfp_connection);
2206 }
2207 
2208 /**
2209  * @brief Enable in-band ring tone
2210  */
2211 void hfp_ag_set_use_in_band_ring_tone(int use_in_band_ring_tone){
2212     if (get_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE) == use_in_band_ring_tone){
2213         return;
2214     }
2215     hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE, use_in_band_ring_tone);
2216 
2217     btstack_linked_list_iterator_t it;
2218     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2219     while (btstack_linked_list_iterator_has_next(&it)){
2220         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2221         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2222         hfp_connection->command = HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING;
2223         hfp_ag_run_for_context(hfp_connection);
2224     }
2225 }
2226 
2227 /**
2228  * @brief Called from GSM
2229  */
2230 void hfp_ag_incoming_call(void){
2231     hfp_ag_call_sm(HFP_AG_INCOMING_CALL, NULL);
2232 }
2233 
2234 /**
2235  * @brief number is stored.
2236  */
2237 void hfp_ag_set_clip(uint8_t type, const char * number){
2238     hfp_gsm_handler(HFP_AG_SET_CLIP, 0, type, number);
2239 }
2240 
2241 void hfp_ag_call_dropped(void){
2242     hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2243 }
2244 
2245 // call from AG UI
2246 void hfp_ag_answer_incoming_call(void){
2247     hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, NULL);
2248 }
2249 
2250 void hfp_ag_join_held_call(void){
2251     hfp_ag_call_sm(HFP_AG_HELD_CALL_JOINED_BY_AG, NULL);
2252 }
2253 
2254 void hfp_ag_terminate_call(void){
2255     hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_AG, NULL);
2256 }
2257 
2258 void hfp_ag_outgoing_call_ringing(void){
2259     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_RINGING, NULL);
2260 }
2261 
2262 void hfp_ag_outgoing_call_established(void){
2263     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ESTABLISHED, NULL);
2264 }
2265 
2266 void hfp_ag_outgoing_call_rejected(void){
2267     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_REJECTED, NULL);
2268 }
2269 
2270 void hfp_ag_outgoing_call_accepted(void){
2271     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ACCEPTED, NULL);
2272 }
2273 
2274 void hfp_ag_hold_incoming_call(void){
2275     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, NULL);
2276 }
2277 
2278 void hfp_ag_accept_held_incoming_call(void) {
2279     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, NULL);
2280 }
2281 
2282 void hfp_ag_reject_held_incoming_call(void){
2283     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, NULL);
2284 }
2285 
2286 static void hfp_ag_set_ag_indicator(const char * name, int value){
2287     int indicator_index = get_ag_indicator_index_for_name(name);
2288     if (indicator_index < 0) return;
2289     hfp_ag_indicators[indicator_index].status = value;
2290 
2291 
2292     btstack_linked_list_iterator_t it;
2293     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2294     while (btstack_linked_list_iterator_has_next(&it)){
2295         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2296         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2297         if (! hfp_connection->ag_indicators[indicator_index].enabled) {
2298             log_info("AG indicator '%s' changed to %u but not enabled", hfp_ag_indicators[indicator_index].name, value);
2299             continue;
2300         }
2301         log_info("AG indicator '%s' changed to %u, request transfer statur", hfp_ag_indicators[indicator_index].name, value);
2302         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
2303         hfp_ag_run_for_context(hfp_connection);
2304     }
2305 }
2306 
2307 void hfp_ag_set_registration_status(int status){
2308     hfp_ag_set_ag_indicator("service", status);
2309 }
2310 
2311 void hfp_ag_set_signal_strength(int strength){
2312     hfp_ag_set_ag_indicator("signal", strength);
2313 }
2314 
2315 void hfp_ag_set_roaming_status(int status){
2316     hfp_ag_set_ag_indicator("roam", status);
2317 }
2318 
2319 void hfp_ag_set_battery_level(int level){
2320     hfp_ag_set_ag_indicator("battchg", level);
2321 }
2322 
2323 void hfp_ag_activate_voice_recognition(hci_con_handle_t acl_handle, int activate){
2324     if (!get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)) return;
2325     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2326     if (!hfp_connection){
2327         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2328         return;
2329     }
2330 
2331     if (!get_bit(hfp_connection->remote_supported_features, HFP_HFSF_VOICE_RECOGNITION_FUNCTION)) {
2332         log_info("AG cannot acivate voice recognition - not supported by HF");
2333         return;
2334     }
2335 
2336     if (activate){
2337         hfp_ag_establish_audio_connection(acl_handle);
2338     }
2339 
2340     hfp_connection->ag_activate_voice_recognition = activate;
2341     hfp_connection->command = HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
2342     hfp_ag_run_for_context(hfp_connection);
2343 }
2344 
2345 void hfp_ag_set_microphone_gain(hci_con_handle_t acl_handle, int gain){
2346     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2347     if (!hfp_connection){
2348         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2349         return;
2350     }
2351     if (hfp_connection->microphone_gain != gain){
2352         hfp_connection->command = HFP_CMD_SET_MICROPHONE_GAIN;
2353         hfp_connection->microphone_gain = gain;
2354         hfp_connection->send_microphone_gain = 1;
2355     }
2356     hfp_ag_run_for_context(hfp_connection);
2357 }
2358 
2359 void hfp_ag_set_speaker_gain(hci_con_handle_t acl_handle, int gain){
2360     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2361     if (!hfp_connection){
2362         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2363         return;
2364     }
2365     if (hfp_connection->speaker_gain != gain){
2366         hfp_connection->speaker_gain = gain;
2367         hfp_connection->send_speaker_gain = 1;
2368     }
2369     hfp_ag_run_for_context(hfp_connection);
2370 }
2371 
2372 void hfp_ag_send_phone_number_for_voice_tag(hci_con_handle_t acl_handle, const char * number){
2373     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2374     if (!hfp_connection){
2375         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2376         return;
2377     }
2378     hfp_ag_set_clip(0, number);
2379     hfp_connection->send_phone_number_for_voice_tag = 1;
2380 }
2381 
2382 void hfp_ag_reject_phone_number_for_voice_tag(hci_con_handle_t acl_handle){
2383     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2384     if (!hfp_connection){
2385         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2386         return;
2387     }
2388     hfp_connection->send_error = 1;
2389 }
2390 
2391 void hfp_ag_send_dtmf_code_done(hci_con_handle_t acl_handle){
2392     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2393     if (!hfp_connection){
2394         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2395         return;
2396     }
2397     hfp_connection->ok_pending = 1;
2398 }
2399 
2400 void hfp_ag_set_subcriber_number_information(hfp_phone_number_t * numbers, int numbers_count){
2401     subscriber_numbers = numbers;
2402     subscriber_numbers_count = numbers_count;
2403 }
2404 
2405 void hfp_ag_clear_last_dialed_number(void){
2406     hfp_gsm_clear_last_dialed_number();
2407 }
2408 
2409 void hfp_ag_notify_incoming_call_waiting(hci_con_handle_t acl_handle){
2410     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2411     if (!hfp_connection){
2412         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2413         return;
2414     }
2415     if (!hfp_connection->call_waiting_notification_enabled) return;
2416 
2417     hfp_connection->ag_notify_incoming_call_waiting = 1;
2418     hfp_ag_run_for_context(hfp_connection);
2419 }
2420 
2421 void hfp_ag_create_sdp_record(uint8_t * service, uint32_t service_record_handle, int rfcomm_channel_nr, const char * name, uint8_t ability_to_reject_call, uint16_t supported_features, int wide_band_speech){
2422 	if (!name){
2423 		name = default_hfp_ag_service_name;
2424 	}
2425 	hfp_create_sdp_record(service, service_record_handle, BLUETOOTH_SERVICE_CLASS_HANDSFREE_AUDIO_GATEWAY, rfcomm_channel_nr, name);
2426 
2427 	/*
2428 	 * 0x01 – Ability to reject a call
2429 	 * 0x00 – No ability to reject a call
2430 	 */
2431 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0301);    // Hands-Free Profile - Network
2432 	de_add_number(service, DE_UINT, DE_SIZE_8, ability_to_reject_call);
2433 
2434 	// Construct SupportedFeatures for SDP bitmap:
2435 	//
2436 	// "The values of the “SupportedFeatures” bitmap given in Table 5.4 shall be the same as the values
2437 	//  of the Bits 0 to 4 of the unsolicited result code +BRSF"
2438 	//
2439 	// Wide band speech (bit 5) requires Codec negotiation
2440 	//
2441 	uint16_t sdp_features = supported_features & 0x1f;
2442 	if (wide_band_speech && (supported_features & (1 << HFP_AGSF_CODEC_NEGOTIATION))){
2443 		sdp_features |= 1 << 5;
2444 	}
2445 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);    // Hands-Free Profile - SupportedFeatures
2446 	de_add_number(service, DE_UINT, DE_SIZE_16, sdp_features);
2447 }
2448 
2449 void hfp_ag_register_packet_handler(btstack_packet_handler_t callback){
2450 	if (callback == NULL){
2451 		log_error("hfp_ag_register_packet_handler called with NULL callback");
2452 		return;
2453 	}
2454 	hfp_ag_callback = callback;
2455 	hfp_set_ag_callback(callback);
2456 }
2457