xref: /btstack/src/classic/hfp_ag.c (revision 79b02f79ab95d5314fe0ff250a2c8d5727813da9)
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 static btstack_packet_callback_registration_t hci_event_callback_registration;
83 
84 // gobals
85 static const char default_hfp_ag_service_name[] = "Voice gateway";
86 
87 static uint16_t hfp_supported_features = HFP_DEFAULT_AG_SUPPORTED_FEATURES;
88 
89 static uint8_t hfp_codecs_nr = 0;
90 static uint8_t hfp_codecs[HFP_MAX_NUM_CODECS];
91 
92 static int  hfp_ag_indicators_nr = 0;
93 static hfp_ag_indicator_t hfp_ag_indicators[HFP_MAX_NUM_INDICATORS];
94 
95 static int hfp_generic_status_indicators_nr = 0;
96 static hfp_generic_status_indicator_t hfp_generic_status_indicators[HFP_MAX_NUM_INDICATORS];
97 
98 static int  hfp_ag_call_hold_services_nr = 0;
99 static char *hfp_ag_call_hold_services[6];
100 static btstack_packet_handler_t hfp_ag_callback;
101 
102 static hfp_response_and_hold_state_t hfp_ag_response_and_hold_state;
103 static int hfp_ag_response_and_hold_active = 0;
104 
105 // Subcriber information entries
106 static hfp_phone_number_t * subscriber_numbers = NULL;
107 static int subscriber_numbers_count = 0;
108 
109 hfp_ag_indicator_t * hfp_ag_get_ag_indicators(hfp_connection_t * hfp_connection);
110 
111 
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 
561             hfp_init_link_settings(hfp_connection, hfp_ag_esco_s4_supported(hfp_connection));
562             return 1;
563         default:
564             break;
565     }
566     return 0;
567 }
568 
569 static void hfp_ag_slc_established(hfp_connection_t * hfp_connection){
570     hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
571     hfp_emit_slc_connection_event(hfp_connection, 0, hfp_connection->acl_handle, hfp_connection->remote_addr);
572 
573     // if active call exist, set per-hfp_connection state active, too (when audio is on)
574     if (hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT){
575         hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE;
576     }
577     // if AG is ringing, also start ringing on the HF
578     if ((hfp_gsm_call_status() == HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS) &&
579         (hfp_gsm_callsetup_status() == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS)){
580         hfp_ag_hf_start_ringing(hfp_connection);
581     }
582 }
583 
584 static int hfp_ag_run_for_context_service_level_connection(hfp_connection_t * hfp_connection){
585     // log_info("hfp_ag_run_for_context_service_level_connection state %u, command %u", hfp_connection->state, hfp_connection->command);
586     if (hfp_connection->state >= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) return 0;
587     int sent = 0;
588     switch(hfp_connection->command){
589         case HFP_CMD_SUPPORTED_FEATURES:
590             switch(hfp_connection->state){
591                 case HFP_W4_EXCHANGE_SUPPORTED_FEATURES:
592                 case HFP_EXCHANGE_SUPPORTED_FEATURES:
593                     hfp_hf_drop_mSBC_if_eSCO_not_supported(hfp_codecs, &hfp_codecs_nr);
594                     if (has_codec_negotiation_feature(hfp_connection)){
595                         hfp_connection->state = HFP_W4_NOTIFY_ON_CODECS;
596                     } else {
597                         hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS;
598                     }
599                     hfp_ag_exchange_supported_features_cmd(hfp_connection->rfcomm_cid);
600                     return 1;
601                 default:
602                     break;
603             }
604             break;
605         case HFP_CMD_AVAILABLE_CODECS:
606             sent = codecs_exchange_state_machine(hfp_connection);
607             if (hfp_connection->codecs_state == HFP_CODECS_RECEIVED_LIST){
608                 hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS;
609             }
610             return sent;
611 
612         case HFP_CMD_RETRIEVE_AG_INDICATORS:
613             if (hfp_connection->state == HFP_W4_RETRIEVE_INDICATORS) {
614                 // HF requested AG Indicators and we did expect it
615                 hfp_connection->send_ag_indicators_segment = 0;
616                 hfp_connection->state = HFP_RETRIEVE_INDICATORS;
617                 // continue below in state switch
618             }
619             break;
620 
621         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
622             if (hfp_connection->state != HFP_W4_RETRIEVE_INDICATORS_STATUS) break;
623             hfp_connection->state = HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE;
624             hfp_ag_send_retrieve_indicators_status_cmd(hfp_connection->rfcomm_cid);
625             return 1;
626 
627         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
628             if (hfp_connection->state != HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE) break;
629             if (has_call_waiting_and_3way_calling_feature(hfp_connection)){
630                 hfp_connection->state = HFP_W4_RETRIEVE_CAN_HOLD_CALL;
631             } else if (has_hf_indicators_feature(hfp_connection)){
632                 hfp_connection->state = HFP_W4_LIST_GENERIC_STATUS_INDICATORS;
633             } else {
634                 hfp_ag_slc_established(hfp_connection);
635             }
636             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
637             return 1;
638 
639         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
640             if (hfp_connection->state != HFP_W4_RETRIEVE_CAN_HOLD_CALL) break;
641             if (has_hf_indicators_feature(hfp_connection)){
642                 hfp_connection->state = HFP_W4_LIST_GENERIC_STATUS_INDICATORS;
643             }
644             hfp_ag_send_retrieve_can_hold_call_cmd(hfp_connection->rfcomm_cid);
645             if (!has_hf_indicators_feature(hfp_connection)){
646                 hfp_ag_slc_established(hfp_connection);
647             }
648             return 1;
649 
650         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
651             if (hfp_connection->state != HFP_W4_LIST_GENERIC_STATUS_INDICATORS) break;
652             hfp_connection->state = HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS;
653             hfp_ag_send_list_supported_generic_status_indicators_cmd(hfp_connection->rfcomm_cid);
654             return 1;
655 
656         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
657             if (hfp_connection->state != HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS) break;
658             hfp_connection->state = HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS;
659             hfp_ag_send_retrieve_supported_generic_status_indicators_cmd(hfp_connection->rfcomm_cid);
660             return 1;
661 
662         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
663             if (hfp_connection->state != HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS) break;
664             hfp_ag_slc_established(hfp_connection);
665             hfp_ag_send_retrieve_initital_supported_generic_status_indicators_cmd(hfp_connection->rfcomm_cid);
666             return 1;
667         default:
668             break;
669     }
670 
671     switch (hfp_connection->state){
672         case HFP_RETRIEVE_INDICATORS: {
673             int next_segment = hfp_ag_send_retrieve_indicators_cmd_via_generator(hfp_connection->rfcomm_cid, hfp_connection, hfp_connection->send_ag_indicators_segment);
674             int num_segments = hfp_ag_indicators_cmd_generator_num_segments(hfp_connection);
675             log_info("HFP_CMD_RETRIEVE_AG_INDICATORS next segment %u, num_segments %u", next_segment, num_segments);
676             if (next_segment < num_segments){
677                 // prepare sending of next segment
678                 hfp_connection->send_ag_indicators_segment = next_segment;
679                 log_info("HFP_CMD_RETRIEVE_AG_INDICATORS more. command %u, next seg %u", hfp_connection->command, next_segment);
680             } else {
681                 // done, go to next state
682                 hfp_connection->send_ag_indicators_segment = 0;
683                 hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS_STATUS;
684             }
685             return 1;
686         }
687         default:
688             break;
689     }
690     return 0;
691 }
692 
693 static int hfp_ag_run_for_context_service_level_connection_queries(hfp_connection_t * hfp_connection){
694     int sent = codecs_exchange_state_machine(hfp_connection);
695     if (sent) return 1;
696 
697     switch(hfp_connection->command){
698         case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
699             hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION, hfp_connection->ag_activate_voice_recognition);
700             hfp_ag_send_activate_voice_recognition_cmd(hfp_connection->rfcomm_cid, hfp_connection->ag_activate_voice_recognition);
701             return 1;
702         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
703             if (get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)){
704                 hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION, hfp_connection->ag_activate_voice_recognition);
705                 hfp_ag_send_ok(hfp_connection->rfcomm_cid);
706                 hfp_ag_setup_audio_connection(hfp_connection);
707             } else {
708                 hfp_ag_send_error(hfp_connection->rfcomm_cid);
709             }
710             return 1;
711         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
712             hfp_ag_send_change_in_band_ring_tone_setting_cmd(hfp_connection->rfcomm_cid);
713             return 1;
714         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
715             hfp_ag_send_report_network_operator_name_cmd(hfp_connection->rfcomm_cid, hfp_connection->network_operator);
716             return 1;
717         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
718             if (hfp_connection->network_operator.format != 0){
719                 hfp_ag_send_error(hfp_connection->rfcomm_cid);
720             } else {
721                 hfp_ag_send_ok(hfp_connection->rfcomm_cid);
722             }
723             return 1;
724         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
725             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
726             return 1;
727         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
728             if (hfp_connection->extended_audio_gateway_error){
729                 hfp_connection->extended_audio_gateway_error = 0;
730                 hfp_ag_send_report_extended_audio_gateway_error(hfp_connection->rfcomm_cid, hfp_connection->extended_audio_gateway_error_value);
731                 return 1;
732             }
733             break;
734         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
735             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
736             return 1;
737         default:
738             break;
739     }
740     return 0;
741 }
742 
743 static int hfp_ag_run_for_audio_connection(hfp_connection_t * hfp_connection){
744     if ((hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) ||
745         (hfp_connection->state > HFP_W2_DISCONNECT_SCO)) return 0;
746 
747 
748     if ((hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) && hfp_connection->release_audio_connection){
749         hfp_connection->state = HFP_W4_SCO_DISCONNECTED;
750         hfp_connection->release_audio_connection = 0;
751         gap_disconnect(hfp_connection->sco_handle);
752         return 1;
753     }
754 
755     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
756 
757     // run codecs exchange
758     int sent = codecs_exchange_state_machine(hfp_connection);
759     if (sent) return 1;
760 
761     if (hfp_connection->codecs_state != HFP_CODECS_EXCHANGED) return 0;
762     if (hfp_connection->establish_audio_connection){
763         hfp_connection->state = HFP_W4_SCO_CONNECTED;
764         hfp_connection->establish_audio_connection = 0;
765         hfp_setup_synchronous_connection(hfp_connection);
766         return 1;
767     }
768     return 0;
769 }
770 
771 static hfp_connection_t * hfp_ag_context_for_timer(btstack_timer_source_t * ts){
772     btstack_linked_list_iterator_t it;
773     btstack_linked_list_iterator_init(&it, hfp_get_connections());
774 
775     while (btstack_linked_list_iterator_has_next(&it)){
776         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
777         if ( & hfp_connection->hfp_timeout == ts) {
778             return hfp_connection;
779         }
780     }
781     return NULL;
782 }
783 
784 static void hfp_timeout_handler(btstack_timer_source_t * timer){
785     hfp_connection_t * hfp_connection = hfp_ag_context_for_timer(timer);
786     if (!hfp_connection) return;
787 
788     log_info("HFP start ring timeout, con handle 0x%02x", hfp_connection->acl_handle);
789     hfp_connection->ag_ring = 1;
790     hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
791 
792     btstack_run_loop_set_timer(& hfp_connection->hfp_timeout, 2000); // 2 seconds timeout
793     btstack_run_loop_add_timer(& hfp_connection->hfp_timeout);
794 
795     hfp_ag_run_for_context(hfp_connection);
796 }
797 
798 static void hfp_timeout_start(hfp_connection_t * hfp_connection){
799     btstack_run_loop_remove_timer(& hfp_connection->hfp_timeout);
800     btstack_run_loop_set_timer_handler(& hfp_connection->hfp_timeout, hfp_timeout_handler);
801     btstack_run_loop_set_timer(& hfp_connection->hfp_timeout, 2000); // 2 seconds timeout
802     btstack_run_loop_add_timer(& hfp_connection->hfp_timeout);
803 }
804 
805 static void hfp_timeout_stop(hfp_connection_t * hfp_connection){
806     log_info("HFP stop ring timeout, con handle 0x%02x", hfp_connection->acl_handle);
807     btstack_run_loop_remove_timer(& hfp_connection->hfp_timeout);
808 }
809 
810 //
811 // transitition implementations for hfp_ag_call_state_machine
812 //
813 
814 static void hfp_ag_hf_start_ringing(hfp_connection_t * hfp_connection){
815     if (use_in_band_tone()){
816         hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING;
817         hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
818     } else {
819         hfp_timeout_start(hfp_connection);
820         hfp_connection->ag_ring = 1;
821         hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
822         hfp_connection->call_state = HFP_CALL_RINGING;
823         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_START_RINGINIG);
824     }
825 }
826 
827 static void hfp_ag_hf_stop_ringing(hfp_connection_t * hfp_connection){
828     hfp_connection->ag_ring = 0;
829     hfp_connection->ag_send_clip = 0;
830     hfp_timeout_stop(hfp_connection);
831     hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_STOP_RINGINIG);
832 }
833 
834 static void hfp_ag_trigger_incoming_call(void){
835     int indicator_index = get_ag_indicator_index_for_name("callsetup");
836     if (indicator_index < 0) return;
837 
838     btstack_linked_list_iterator_t it;
839     btstack_linked_list_iterator_init(&it, hfp_get_connections());
840     while (btstack_linked_list_iterator_has_next(&it)){
841         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
842         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
843         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
844         if (hfp_connection->call_state == HFP_CALL_IDLE){
845             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
846             hfp_ag_hf_start_ringing(hfp_connection);
847         }
848         if (hfp_connection->call_state == HFP_CALL_ACTIVE){
849             hfp_connection->call_state = HFP_CALL_W2_SEND_CALL_WAITING;
850         }
851         hfp_ag_run_for_context(hfp_connection);
852     }
853 }
854 
855 static void hfp_ag_transfer_callsetup_state(void){
856     int indicator_index = get_ag_indicator_index_for_name("callsetup");
857     if (indicator_index < 0) return;
858 
859     btstack_linked_list_iterator_t it;
860     btstack_linked_list_iterator_init(&it, hfp_get_connections());
861     while (btstack_linked_list_iterator_has_next(&it)){
862         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
863         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
864         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
865         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
866         hfp_ag_run_for_context(hfp_connection);
867     }
868 }
869 
870 static void hfp_ag_transfer_call_state(void){
871     int indicator_index = get_ag_indicator_index_for_name("call");
872     if (indicator_index < 0) return;
873 
874     btstack_linked_list_iterator_t it;
875     btstack_linked_list_iterator_init(&it, hfp_get_connections());
876     while (btstack_linked_list_iterator_has_next(&it)){
877         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
878         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
879         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
880         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
881         hfp_ag_run_for_context(hfp_connection);
882     }
883 }
884 
885 static void hfp_ag_transfer_callheld_state(void){
886     int indicator_index = get_ag_indicator_index_for_name("callheld");
887     if (indicator_index < 0) return;
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         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
895         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
896         hfp_ag_run_for_context(hfp_connection);
897     }
898 }
899 
900 static void hfp_ag_hf_accept_call(hfp_connection_t * source){
901 
902     int call_indicator_index = get_ag_indicator_index_for_name("call");
903     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
904 
905     btstack_linked_list_iterator_t it;
906     btstack_linked_list_iterator_init(&it, hfp_get_connections());
907     while (btstack_linked_list_iterator_has_next(&it)){
908         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
909         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
910         if ((hfp_connection->call_state != HFP_CALL_RINGING) &&
911             (hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
912 
913         hfp_ag_hf_stop_ringing(hfp_connection);
914         if (hfp_connection == source){
915 
916             if (use_in_band_tone()){
917                 hfp_connection->call_state = HFP_CALL_ACTIVE;
918             } else {
919                 hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE;
920                 hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
921             }
922 
923             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
924             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
925 
926         } else {
927             hfp_connection->call_state = HFP_CALL_IDLE;
928         }
929         hfp_ag_run_for_context(hfp_connection);
930     }
931 }
932 
933 static void hfp_ag_ag_accept_call(void){
934 
935     int call_indicator_index = get_ag_indicator_index_for_name("call");
936     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
937 
938     btstack_linked_list_iterator_t it;
939     btstack_linked_list_iterator_init(&it, hfp_get_connections());
940     while (btstack_linked_list_iterator_has_next(&it)){
941         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
942         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
943         if (hfp_connection->call_state != HFP_CALL_RINGING) continue;
944 
945         hfp_ag_hf_stop_ringing(hfp_connection);
946         hfp_connection->call_state = HFP_CALL_TRIGGER_AUDIO_CONNECTION;
947 
948         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
949         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
950 
951         hfp_ag_run_for_context(hfp_connection);
952         break;  // only single
953     }
954 }
955 
956 static void hfp_ag_trigger_reject_call(void){
957     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
958     btstack_linked_list_iterator_t it;
959     btstack_linked_list_iterator_init(&it, hfp_get_connections());
960     while (btstack_linked_list_iterator_has_next(&it)){
961         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
962         if (connection->local_role != HFP_ROLE_AG) continue;
963         if ((connection->call_state != HFP_CALL_RINGING) &&
964             (connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
965         hfp_ag_hf_stop_ringing(connection);
966         connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
967         connection->call_state = HFP_CALL_IDLE;
968         hfp_ag_run_for_context(connection);
969     }
970 }
971 
972 static void hfp_ag_trigger_terminate_call(void){
973     int call_indicator_index = get_ag_indicator_index_for_name("call");
974 
975     btstack_linked_list_iterator_t it;
976     btstack_linked_list_iterator_init(&it, hfp_get_connections());
977     while (btstack_linked_list_iterator_has_next(&it)){
978         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
979         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
980         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
981         if (hfp_connection->call_state == HFP_CALL_IDLE) continue;
982         hfp_connection->call_state = HFP_CALL_IDLE;
983         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
984         if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
985             hfp_connection->release_audio_connection = 1;
986         }
987         hfp_ag_run_for_context(hfp_connection);
988     }
989     hfp_ag_emit_simple_event(HFP_SUBEVENT_CALL_TERMINATED);
990 }
991 
992 static void hfp_ag_set_callsetup_indicator(void){
993     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("callsetup");
994     if (!indicator){
995         log_error("hfp_ag_set_callsetup_indicator: callsetup indicator is missing");
996         return;
997     };
998     indicator->status = hfp_gsm_callsetup_status();
999 }
1000 
1001 static void hfp_ag_set_callheld_indicator(void){
1002     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("callheld");
1003     if (!indicator){
1004         log_error("hfp_ag_set_callheld_state: callheld indicator is missing");
1005         return;
1006     };
1007     indicator->status = hfp_gsm_callheld_status();
1008 }
1009 
1010 static void hfp_ag_set_call_indicator(void){
1011     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("call");
1012     if (!indicator){
1013         log_error("hfp_ag_set_call_state: call indicator is missing");
1014         return;
1015     };
1016     indicator->status = hfp_gsm_call_status();
1017 }
1018 
1019 static void hfp_ag_stop_ringing(void){
1020     btstack_linked_list_iterator_t it;
1021     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1022     while (btstack_linked_list_iterator_has_next(&it)){
1023         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1024         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1025         if ((hfp_connection->call_state != HFP_CALL_RINGING) &&
1026             (hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
1027         hfp_ag_hf_stop_ringing(hfp_connection);
1028     }
1029 }
1030 
1031 static hfp_connection_t * hfp_ag_connection_for_call_state(hfp_call_state_t call_state){
1032     btstack_linked_list_iterator_t it;
1033     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1034     while (btstack_linked_list_iterator_has_next(&it)){
1035         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1036         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1037         if (hfp_connection->call_state == call_state) return hfp_connection;
1038     }
1039     return NULL;
1040 }
1041 
1042 static void hfp_ag_send_response_and_hold_state(hfp_response_and_hold_state_t state){
1043     btstack_linked_list_iterator_t it;
1044     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1045     while (btstack_linked_list_iterator_has_next(&it)){
1046         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1047         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1048         hfp_connection->send_response_and_hold_status = state + 1;
1049     }
1050 }
1051 
1052 static int call_setup_state_machine(hfp_connection_t * hfp_connection){
1053     int indicator_index;
1054     switch (hfp_connection->call_state){
1055         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING:
1056             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1057             // we got event: audio hfp_connection established
1058             hfp_timeout_start(hfp_connection);
1059             hfp_connection->ag_ring = 1;
1060             hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
1061             hfp_connection->call_state = HFP_CALL_RINGING;
1062             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_START_RINGINIG);
1063             break;
1064         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE:
1065             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1066             // we got event: audio hfp_connection established
1067             hfp_connection->call_state = HFP_CALL_ACTIVE;
1068             break;
1069         case HFP_CALL_W2_SEND_CALL_WAITING:
1070             hfp_connection->call_state = HFP_CALL_W4_CHLD;
1071             hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1072             indicator_index = get_ag_indicator_index_for_name("callsetup");
1073             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1074             break;
1075         default:
1076             break;
1077     }
1078     return 0;
1079 }
1080 
1081 // functions extracted from hfp_ag_call_sm below
1082 static void hfp_ag_handle_reject_incoming_call(void){
1083     hfp_connection_t * hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1084     if (!hfp_connection){
1085         log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1086         return;
1087     }
1088 
1089     hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_REJECTED);
1090     hfp_connection->call_state = HFP_CALL_IDLE;
1091     hfp_connection->send_error = 1;
1092     hfp_ag_run_for_context(hfp_connection);
1093 }
1094 
1095 // hfp_connection is used to identify originating HF
1096 static void hfp_ag_call_sm(hfp_ag_call_event_t event, hfp_connection_t * hfp_connection){
1097     int indicator_index;
1098     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1099     int callheld_indicator_index = get_ag_indicator_index_for_name("callheld");
1100     int call_indicator_index = get_ag_indicator_index_for_name("call");
1101 
1102     switch (event){
1103         case HFP_AG_INCOMING_CALL:
1104             switch (hfp_gsm_call_status()){
1105                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1106                     switch (hfp_gsm_callsetup_status()){
1107                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1108                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL);
1109                             hfp_ag_set_callsetup_indicator();
1110                             hfp_ag_trigger_incoming_call();
1111                             log_info("AG rings");
1112                             break;
1113                         default:
1114                             break;
1115                     }
1116                     break;
1117                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1118                     switch (hfp_gsm_callsetup_status()){
1119                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1120                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL);
1121                             hfp_ag_set_callsetup_indicator();
1122                             hfp_ag_trigger_incoming_call();
1123                             log_info("AG call waiting");
1124                             break;
1125                         default:
1126                             break;
1127                     }
1128                     break;
1129                 default:
1130                     break;
1131             }
1132             break;
1133         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG:
1134             switch (hfp_gsm_call_status()){
1135                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1136                     switch (hfp_gsm_callsetup_status()){
1137                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1138                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG);
1139                             hfp_ag_set_call_indicator();
1140                             hfp_ag_set_callsetup_indicator();
1141                             hfp_ag_ag_accept_call();
1142                             log_info("AG answers call, accept call by GSM");
1143                             break;
1144                         default:
1145                             break;
1146                     }
1147                     break;
1148                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1149                     switch (hfp_gsm_callsetup_status()){
1150                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1151                             log_info("AG: current call is placed on hold, incoming call gets active");
1152                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG);
1153                             hfp_ag_set_callsetup_indicator();
1154                             hfp_ag_set_callheld_indicator();
1155                             hfp_ag_transfer_callsetup_state();
1156                             hfp_ag_transfer_callheld_state();
1157                             break;
1158                         default:
1159                             break;
1160                     }
1161                     break;
1162                 default:
1163                     break;
1164             }
1165             break;
1166 
1167         case HFP_AG_HELD_CALL_JOINED_BY_AG:
1168             switch (hfp_gsm_call_status()){
1169                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1170                     switch (hfp_gsm_callheld_status()){
1171                         case HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED:
1172                             log_info("AG: joining held call with active call");
1173                             hfp_gsm_handle_event(HFP_AG_HELD_CALL_JOINED_BY_AG);
1174                             hfp_ag_set_callheld_indicator();
1175                             hfp_ag_transfer_callheld_state();
1176                             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CONFERENCE_CALL);
1177                             break;
1178                         default:
1179                             break;
1180                     }
1181                     break;
1182                 default:
1183                     break;
1184             }
1185             break;
1186 
1187         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF:
1188             switch (hfp_gsm_call_status()){
1189                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1190                     switch (hfp_gsm_callsetup_status()){
1191                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1192                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF);
1193                             hfp_ag_set_callsetup_indicator();
1194                             hfp_ag_set_call_indicator();
1195                             hfp_ag_hf_accept_call(hfp_connection);
1196                             hfp_connection->ok_pending = 1;
1197                             log_info("HF answers call, accept call by GSM");
1198                             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_ANSWERED);
1199                             break;
1200                         default:
1201                             break;
1202                     }
1203                     break;
1204                 default:
1205                     break;
1206             }
1207             break;
1208 
1209         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG:
1210             switch (hfp_gsm_call_status()){
1211                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1212                     switch (hfp_gsm_callsetup_status()){
1213                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1214                             hfp_gsm_handle_event(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG);
1215                             hfp_ag_response_and_hold_active = 1;
1216                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1217                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1218                             // as with regualr call
1219                             hfp_ag_set_call_indicator();
1220                             hfp_ag_set_callsetup_indicator();
1221                             hfp_ag_ag_accept_call();
1222                             log_info("AG response and hold - hold by AG");
1223                             break;
1224                         default:
1225                             break;
1226                     }
1227                     break;
1228                 default:
1229                     break;
1230             }
1231             break;
1232 
1233         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF:
1234             switch (hfp_gsm_call_status()){
1235                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1236                     switch (hfp_gsm_callsetup_status()){
1237                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1238                             hfp_gsm_handle_event(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF);
1239                             hfp_ag_response_and_hold_active = 1;
1240                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1241                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1242                             // as with regualr call
1243                             hfp_ag_set_call_indicator();
1244                             hfp_ag_set_callsetup_indicator();
1245                             hfp_ag_hf_accept_call(hfp_connection);
1246                             log_info("AG response and hold - hold by HF");
1247                             break;
1248                         default:
1249                             break;
1250                     }
1251                     break;
1252                 default:
1253                     break;
1254             }
1255             break;
1256 
1257         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG:
1258         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF:
1259             if (!hfp_ag_response_and_hold_active) break;
1260             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1261             hfp_gsm_handle_event(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG);
1262             hfp_ag_response_and_hold_active = 0;
1263             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED;
1264             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1265             log_info("Held Call accepted and active");
1266             break;
1267 
1268         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG:
1269         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF:
1270             if (!hfp_ag_response_and_hold_active) break;
1271             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1272             hfp_gsm_handle_event(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG);
1273             hfp_ag_response_and_hold_active = 0;
1274             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1275             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1276             // from terminate by ag
1277             hfp_ag_set_call_indicator();
1278             hfp_ag_trigger_terminate_call();
1279             break;
1280 
1281         case HFP_AG_TERMINATE_CALL_BY_HF:
1282             switch (hfp_gsm_call_status()){
1283                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1284                     switch (hfp_gsm_callsetup_status()){
1285                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1286                             hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_HF);
1287                             hfp_ag_set_callsetup_indicator();
1288                             hfp_ag_transfer_callsetup_state();
1289                             hfp_ag_trigger_reject_call();
1290                             log_info("HF Rejected Incoming call, AG terminate call");
1291                             break;
1292                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1293                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1294                             hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_HF);
1295                             hfp_ag_set_callsetup_indicator();
1296                             hfp_ag_transfer_callsetup_state();
1297                             log_info("AG terminate outgoing call process");
1298                             break;
1299                         default:
1300                             break;
1301                     }
1302                     break;
1303                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1304                     hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_HF);
1305                     hfp_ag_set_call_indicator();
1306                     hfp_ag_transfer_call_state();
1307                     hfp_connection->call_state = HFP_CALL_IDLE;
1308                     log_info("AG terminate call");
1309                     break;
1310                 default:
1311                     break;
1312             }
1313             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_TERMINATED);
1314             break;
1315 
1316         case HFP_AG_TERMINATE_CALL_BY_AG:
1317             switch (hfp_gsm_call_status()){
1318                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1319                     switch (hfp_gsm_callsetup_status()){
1320                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1321                             hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_AG);
1322                             hfp_ag_set_callsetup_indicator();
1323                             hfp_ag_trigger_reject_call();
1324                             log_info("AG Rejected Incoming call, AG terminate call");
1325                             break;
1326                         default:
1327                             break;
1328                     }
1329                     break;
1330                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1331                     hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_AG);
1332                     hfp_ag_set_callsetup_indicator();
1333                     hfp_ag_set_call_indicator();
1334                     hfp_ag_trigger_terminate_call();
1335                     log_info("AG terminate call");
1336                     break;
1337                 default:
1338                     break;
1339             }
1340             break;
1341         case HFP_AG_CALL_DROPPED:
1342             switch (hfp_gsm_call_status()){
1343                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1344                     switch (hfp_gsm_callsetup_status()){
1345                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1346                             hfp_ag_stop_ringing();
1347                             log_info("Incoming call interrupted");
1348                             break;
1349                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1350                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1351                             log_info("Outgoing call interrupted\n");
1352                             log_info("AG notify call dropped\n");
1353                             break;
1354                         default:
1355                             break;
1356                     }
1357                     hfp_gsm_handle_event(HFP_AG_CALL_DROPPED);
1358                     hfp_ag_set_callsetup_indicator();
1359                     hfp_ag_transfer_callsetup_state();
1360                     hfp_ag_trigger_terminate_call();
1361                     break;
1362                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1363                     if (hfp_ag_response_and_hold_active) {
1364                         hfp_gsm_handle_event(HFP_AG_CALL_DROPPED);
1365                         hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1366                         hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1367                     }
1368                     hfp_gsm_handle_event(HFP_AG_CALL_DROPPED);
1369                     hfp_ag_set_callsetup_indicator();
1370                     hfp_ag_set_call_indicator();
1371                     hfp_ag_trigger_terminate_call();
1372                     log_info("AG notify call dropped");
1373                     break;
1374                 default:
1375                     break;
1376             }
1377             break;
1378 
1379         case HFP_AG_OUTGOING_CALL_INITIATED:
1380             // directly reject call if number of free slots is exceeded
1381             if (!hfp_gsm_call_possible()){
1382                 hfp_connection->send_error = 1;
1383                 hfp_ag_run_for_context(hfp_connection);
1384                 break;
1385             }
1386             hfp_gsm_handle_event_with_call_number(HFP_AG_OUTGOING_CALL_INITIATED, (const char *) &hfp_connection->line_buffer[3]);
1387 
1388             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1389 
1390             hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, (const char *) &hfp_connection->line_buffer[3]);
1391             break;
1392 
1393         case HFP_AG_OUTGOING_REDIAL_INITIATED:{
1394             // directly reject call if number of free slots is exceeded
1395             if (!hfp_gsm_call_possible()){
1396                 hfp_connection->send_error = 1;
1397                 hfp_ag_run_for_context(hfp_connection);
1398                 break;
1399             }
1400 
1401             hfp_gsm_handle_event(HFP_AG_OUTGOING_REDIAL_INITIATED);
1402             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1403 
1404             log_info("Redial last number");
1405             char * last_dialed_number = hfp_gsm_last_dialed_number();
1406 
1407             if (strlen(last_dialed_number) > 0){
1408                 log_info("Last number exists: accept call");
1409                 hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, last_dialed_number);
1410             } else {
1411                 log_info("log_infoLast number missing: reject call");
1412                 hfp_ag_handle_reject_incoming_call();
1413             }
1414             break;
1415         }
1416         case HFP_AG_OUTGOING_CALL_REJECTED:
1417             hfp_ag_handle_reject_incoming_call();
1418             break;
1419 
1420         case HFP_AG_OUTGOING_CALL_ACCEPTED:{
1421             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1422             if (!hfp_connection){
1423                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1424                 break;
1425             }
1426 
1427             hfp_connection->ok_pending = 1;
1428             hfp_connection->call_state = HFP_CALL_OUTGOING_DIALING;
1429 
1430             // trigger callsetup to be
1431             int put_call_on_hold = hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT;
1432             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_ACCEPTED);
1433 
1434             hfp_ag_set_callsetup_indicator();
1435             indicator_index = get_ag_indicator_index_for_name("callsetup");
1436             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1437 
1438             // put current call on hold if active
1439             if (put_call_on_hold){
1440                 log_info("AG putting current call on hold for new outgoing calllog_info");
1441                 hfp_ag_set_callheld_indicator();
1442                 indicator_index = get_ag_indicator_index_for_name("callheld");
1443                 hfp_ag_send_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[indicator_index]);
1444             }
1445 
1446             // start audio if needed
1447             hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
1448             break;
1449         }
1450         case HFP_AG_OUTGOING_CALL_RINGING:
1451             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1452             if (!hfp_connection){
1453                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in dialing state");
1454                 break;
1455             }
1456 
1457             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_RINGING);
1458             hfp_connection->call_state = HFP_CALL_OUTGOING_RINGING;
1459             hfp_ag_set_callsetup_indicator();
1460             hfp_ag_transfer_callsetup_state();
1461             break;
1462 
1463         case HFP_AG_OUTGOING_CALL_ESTABLISHED:{
1464             // get outgoing call
1465             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_RINGING);
1466             if (!hfp_connection){
1467                 hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1468             }
1469             if (!hfp_connection){
1470                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection");
1471                 break;
1472             }
1473 
1474             int CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS = hfp_gsm_callheld_status() == HFP_CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS;
1475             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_ESTABLISHED);
1476             hfp_connection->call_state = HFP_CALL_ACTIVE;
1477             hfp_ag_set_callsetup_indicator();
1478             hfp_ag_set_call_indicator();
1479             hfp_ag_transfer_call_state();
1480             hfp_ag_transfer_callsetup_state();
1481             if (CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS){
1482                 hfp_ag_set_callheld_indicator();
1483                 hfp_ag_transfer_callheld_state();
1484             }
1485             break;
1486         }
1487 
1488         case HFP_AG_CALL_HOLD_USER_BUSY:
1489             hfp_gsm_handle_event(HFP_AG_CALL_HOLD_USER_BUSY);
1490             hfp_ag_set_callsetup_indicator();
1491             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1492             hfp_connection->call_state = HFP_CALL_ACTIVE;
1493             log_info("AG: Call Waiting, User Busy");
1494             break;
1495 
1496         case HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1497             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1498             int call_held = hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1499 
1500             // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1501             if (call_held || call_setup_in_progress){
1502                 hfp_gsm_handle_event_with_call_index(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index);
1503 
1504             }
1505 
1506             if (call_setup_in_progress){
1507                 log_info("AG: Call Dropped, Accept new call");
1508                 hfp_ag_set_callsetup_indicator();
1509                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1510             } else {
1511                 log_info("AG: Call Dropped, Resume held call");
1512             }
1513             if (call_held){
1514                 hfp_ag_set_callheld_indicator();
1515                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1516             }
1517 
1518             hfp_connection->call_state = HFP_CALL_ACTIVE;
1519             break;
1520         }
1521 
1522         case HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1523             // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1524             // only update if callsetup changed
1525             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1526             hfp_gsm_handle_event_with_call_index(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index);
1527 
1528             if (call_setup_in_progress){
1529                 log_info("AG: Call on Hold, Accept new call");
1530                 hfp_ag_set_callsetup_indicator();
1531                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1532             } else {
1533                 log_info("AG: Swap calls");
1534             }
1535 
1536             hfp_ag_set_callheld_indicator();
1537             // hfp_ag_set_callheld_state(HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED);
1538             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1539             hfp_connection->call_state = HFP_CALL_ACTIVE;
1540             break;
1541         }
1542 
1543         case HFP_AG_CALL_HOLD_ADD_HELD_CALL:
1544             // Adds a held call to the conversation.
1545             if (hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD){
1546                 log_info("AG: Join 3-way-call");
1547                 hfp_gsm_handle_event(HFP_AG_CALL_HOLD_ADD_HELD_CALL);
1548                 hfp_ag_set_callheld_indicator();
1549                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1550                 hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CONFERENCE_CALL);
1551             }
1552             hfp_connection->call_state = HFP_CALL_ACTIVE;
1553             break;
1554         case HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS:
1555             // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer)
1556             hfp_gsm_handle_event(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS);
1557             log_info("AG: Transfer call -> Connect two calls and disconnect");
1558             hfp_ag_set_call_indicator();
1559             hfp_ag_set_callheld_indicator();
1560             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1561             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1562             hfp_connection->call_state = HFP_CALL_IDLE;
1563             break;
1564 
1565         default:
1566             break;
1567     }
1568 
1569 
1570 }
1571 
1572 
1573 static void hfp_ag_send_call_status(hfp_connection_t * hfp_connection, int call_index){
1574     hfp_gsm_call_t * active_call = hfp_gsm_call(call_index);
1575     if (!active_call) return;
1576 
1577     int idx = active_call->index;
1578     hfp_enhanced_call_dir_t dir = active_call->direction;
1579     hfp_enhanced_call_status_t status = active_call->enhanced_status;
1580     hfp_enhanced_call_mode_t mode = active_call->mode;
1581     hfp_enhanced_call_mpty_t mpty = active_call->mpty;
1582     uint8_t type = active_call->clip_type;
1583     char * number = active_call->clip_number;
1584 
1585     char buffer[100];
1586     // TODO: check length of a buffer, to fit the MTU
1587     int offset = snprintf(buffer, sizeof(buffer), "\r\n%s: %d,%d,%d,%d,%d", HFP_LIST_CURRENT_CALLS, idx, dir, status, mode, mpty);
1588     if (number){
1589         offset += snprintf(buffer+offset, sizeof(buffer)-offset-3, ", \"%s\",%u", number, type);
1590     }
1591     snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n");
1592     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,
1593        mode, mpty, type, number);
1594     send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1595 }
1596 
1597 
1598 // sends pending command, returns if command was sent
1599 static int hfp_ag_send_commands(hfp_connection_t *hfp_connection){
1600 
1601     if (hfp_connection->send_status_of_current_calls){
1602         hfp_connection->ok_pending = 0;
1603         if (hfp_connection->next_call_index < hfp_gsm_get_number_of_calls()){
1604             hfp_connection->next_call_index++;
1605             hfp_ag_send_call_status(hfp_connection, hfp_connection->next_call_index);
1606             return 1;
1607         } else {
1608             // 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
1609             hfp_connection->next_call_index = 0;
1610             hfp_connection->ok_pending = 1;
1611             hfp_connection->send_status_of_current_calls = 0;
1612         }
1613     }
1614 
1615     if (hfp_connection->ag_notify_incoming_call_waiting){
1616         hfp_connection->ag_notify_incoming_call_waiting = 0;
1617         hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1618         return 1;
1619     }
1620 
1621     if (hfp_connection->command == HFP_CMD_UNKNOWN){
1622         hfp_connection->ok_pending = 0;
1623         hfp_connection->send_error = 0;
1624         hfp_connection->command = HFP_CMD_NONE;
1625         hfp_ag_send_error(hfp_connection->rfcomm_cid);
1626         return 1;
1627     }
1628 
1629     if (hfp_connection->send_error){
1630         hfp_connection->send_error = 0;
1631         hfp_connection->command = HFP_CMD_NONE;
1632         hfp_ag_send_error(hfp_connection->rfcomm_cid);
1633         return 1;
1634     }
1635 
1636     // note: before update AG indicators and ok_pending
1637     if (hfp_connection->send_response_and_hold_status){
1638         int status = hfp_connection->send_response_and_hold_status - 1;
1639         hfp_connection->send_response_and_hold_status = 0;
1640         hfp_ag_send_set_response_and_hold(hfp_connection->rfcomm_cid, status);
1641         return 1;
1642     }
1643 
1644     if (hfp_connection->ok_pending){
1645         hfp_connection->ok_pending = 0;
1646         hfp_connection->command = HFP_CMD_NONE;
1647         hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1648         return 1;
1649     }
1650 
1651     // update AG indicators
1652     if (hfp_connection->ag_indicators_status_update_bitmap){
1653         int i;
1654         for (i=0;i<hfp_connection->ag_indicators_nr;i++){
1655             if (get_bit(hfp_connection->ag_indicators_status_update_bitmap, i)){
1656                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, i, 0);
1657                 if (!hfp_connection->enable_status_update_for_ag_indicators) {
1658                     log_info("+CMER:3,0,0,0 - not sending update for '%s'", hfp_ag_indicators[i].name);
1659                     break;
1660                 }
1661                 hfp_ag_send_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[i]);
1662                 return 1;
1663             }
1664         }
1665     }
1666 
1667     if (hfp_connection->ag_ring){
1668         hfp_connection->ag_ring = 0;
1669         hfp_connection->command = HFP_CMD_NONE;
1670         hfp_ag_send_ring(hfp_connection->rfcomm_cid);
1671         return 1;
1672     }
1673 
1674     if (hfp_connection->ag_send_clip){
1675         hfp_connection->ag_send_clip = 0;
1676         hfp_connection->command = HFP_CMD_NONE;
1677         hfp_ag_send_clip(hfp_connection->rfcomm_cid);
1678         return 1;
1679     }
1680 
1681     if (hfp_connection->send_phone_number_for_voice_tag){
1682         hfp_connection->send_phone_number_for_voice_tag = 0;
1683         hfp_connection->command = HFP_CMD_NONE;
1684         hfp_connection->ok_pending = 1;
1685         hfp_ag_send_phone_number_for_voice_tag_cmd(hfp_connection->rfcomm_cid);
1686         return 1;
1687     }
1688 
1689     if (hfp_connection->send_subscriber_number){
1690         if (hfp_connection->next_subscriber_number_to_send < subscriber_numbers_count){
1691             hfp_phone_number_t phone = subscriber_numbers[hfp_connection->next_subscriber_number_to_send++];
1692             hfp_send_subscriber_number_cmd(hfp_connection->rfcomm_cid, phone.type, phone.number);
1693         } else {
1694             hfp_connection->send_subscriber_number = 0;
1695             hfp_connection->next_subscriber_number_to_send = 0;
1696             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1697         }
1698         hfp_connection->command = HFP_CMD_NONE;
1699         return 1;
1700     }
1701 
1702     if (hfp_connection->send_microphone_gain){
1703         hfp_connection->send_microphone_gain = 0;
1704         hfp_connection->command = HFP_CMD_NONE;
1705         hfp_ag_send_set_microphone_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->microphone_gain);
1706         return 1;
1707     }
1708 
1709     if (hfp_connection->send_speaker_gain){
1710         hfp_connection->send_speaker_gain = 0;
1711         hfp_connection->command = HFP_CMD_NONE;
1712         hfp_ag_send_set_speaker_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->speaker_gain);
1713         return 1;
1714     }
1715 
1716     if (hfp_connection->send_ag_status_indicators){
1717         hfp_connection->send_ag_status_indicators = 0;
1718         hfp_ag_send_retrieve_indicators_status_cmd(hfp_connection->rfcomm_cid);
1719         return 1;
1720     }
1721 
1722     return 0;
1723 }
1724 
1725 static void hfp_ag_run_for_context(hfp_connection_t *hfp_connection){
1726 
1727 	btstack_assert(hfp_connection != NULL);
1728 	btstack_assert(hfp_connection->local_role == HFP_ROLE_AG);
1729 
1730 	// during SDP query, RFCOMM CID is not set
1731 	if (hfp_connection->rfcomm_cid == 0) return;
1732 
1733     if (!rfcomm_can_send_packet_now(hfp_connection->rfcomm_cid)) {
1734         log_info("hfp_ag_run_for_context: request can send for 0x%02x", hfp_connection->rfcomm_cid);
1735         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1736         return;
1737     }
1738 
1739     int cmd_sent = hfp_ag_send_commands(hfp_connection);
1740 
1741     // trigger codec exchange if requested by app
1742     if (hfp_connection->trigger_codec_exchange){
1743         log_info("trigger codec, command %u, codec state %u", hfp_connection->command, hfp_connection->codecs_state);
1744     }
1745 
1746     if (hfp_connection->trigger_codec_exchange && (hfp_connection->command == HFP_CMD_NONE)){
1747         switch (hfp_connection->codecs_state){
1748             case HFP_CODECS_IDLE:
1749             case HFP_CODECS_RECEIVED_LIST:
1750             case HFP_CODECS_AG_RESEND_COMMON_CODEC:
1751             case HFP_CODECS_ERROR:
1752                 hfp_connection->trigger_codec_exchange = 0;
1753                 hfp_connection->command = HFP_CMD_AG_SEND_COMMON_CODEC;
1754                 break;
1755             default:
1756                 break;
1757         }
1758     }
1759 
1760     if (!cmd_sent){
1761         cmd_sent = hfp_ag_run_for_context_service_level_connection(hfp_connection);
1762     }
1763 
1764     if (!cmd_sent){
1765         cmd_sent = hfp_ag_run_for_context_service_level_connection_queries(hfp_connection);
1766     }
1767 
1768     if (!cmd_sent){
1769         cmd_sent = call_setup_state_machine(hfp_connection);
1770     }
1771 
1772     if (!cmd_sent){
1773         cmd_sent = hfp_ag_run_for_audio_connection(hfp_connection);
1774     }
1775 
1776     if ((hfp_connection->command == HFP_CMD_NONE) && !cmd_sent){
1777         // log_info("hfp_connection->command == HFP_CMD_NONE");
1778         switch(hfp_connection->state){
1779             case HFP_W2_DISCONNECT_RFCOMM:
1780                 hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED;
1781                 rfcomm_disconnect(hfp_connection->rfcomm_cid);
1782                 break;
1783             default:
1784                 break;
1785         }
1786     }
1787 
1788     if (cmd_sent){
1789         hfp_connection->command = HFP_CMD_NONE;
1790         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1791     }
1792 }
1793 
1794 static hfp_generic_status_indicator_t *get_hf_indicator_by_number(int number){
1795     int i;
1796     for (i=0;i< hfp_generic_status_indicators_nr;i++){
1797         hfp_generic_status_indicator_t * indicator = &hfp_generic_status_indicators[i];
1798         if (indicator->uuid == number){
1799             return indicator;
1800         }
1801     }
1802     return NULL;
1803 }
1804 
1805 static int hfp_parser_is_end_of_line(uint8_t byte){
1806     return (byte == '\n') || (byte == '\r');
1807 }
1808 
1809 static void hfp_ag_handle_rfcomm_data(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1810     UNUSED(packet_type);    // ok: only called with RFCOMM_DATA_PACKET
1811 
1812     // assertion: size >= 1 as rfcomm.c does not deliver empty packets
1813     if (size < 1) return;
1814 
1815     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_rfcomm_cid(channel);
1816     if (!hfp_connection) return;
1817 
1818     hfp_log_rfcomm_message("HFP_AG_RX", packet, size);
1819 
1820     // process messages byte-wise
1821     int pos;
1822     for (pos = 0; pos < size ; pos++){
1823         hfp_parse(hfp_connection, packet[pos], 0);
1824 
1825         // parse until end of line
1826         if (!hfp_parser_is_end_of_line(packet[pos])) continue;
1827 
1828         hfp_generic_status_indicator_t * indicator;
1829         switch(hfp_connection->command){
1830             case HFP_CMD_RESPONSE_AND_HOLD_QUERY:
1831                 if (hfp_ag_response_and_hold_active){
1832                     hfp_connection->send_response_and_hold_status = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD + 1;
1833                 }
1834                 hfp_connection->ok_pending = 1;
1835                 break;
1836             case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1837                 switch(hfp_connection->ag_response_and_hold_action){
1838                     case HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD:
1839                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, hfp_connection);
1840                         break;
1841                     case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED:
1842                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF, hfp_connection);
1843                         break;
1844                     case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED:
1845                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF, hfp_connection);
1846                         break;
1847                     default:
1848                         break;
1849                 }
1850                 hfp_connection->ok_pending = 1;
1851                 break;
1852             case HFP_CMD_HF_INDICATOR_STATUS:
1853                 hfp_connection->command = HFP_CMD_NONE;
1854                 // find indicator by assigned number
1855                 indicator = get_hf_indicator_by_number(hfp_connection->parser_indicator_index);
1856                 if (!indicator){
1857                     hfp_connection->send_error = 1;
1858                     break;
1859                 }
1860                 switch (indicator->uuid){
1861                     case 1: // enhanced security
1862                         if (hfp_connection->parser_indicator_value > 1) {
1863                             hfp_connection->send_error = 1;
1864                             return;
1865                         }
1866                         log_info("HF Indicator 'enhanced security' set to %u", hfp_connection->parser_indicator_value);
1867                         break;
1868                     case 2: // battery level
1869                         if (hfp_connection->parser_indicator_value > 100){
1870                             hfp_connection->send_error = 1;
1871                             return;
1872                         }
1873                         log_info("HF Indicator 'battery' set to %u", hfp_connection->parser_indicator_value);
1874                         break;
1875                     default:
1876                         log_info("HF Indicator unknown set to %u", hfp_connection->parser_indicator_value);
1877                         break;
1878                 }
1879                 hfp_connection->ok_pending = 1;
1880                 break;
1881             case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1882                 // expected by SLC state machine
1883                 if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) break;
1884                 hfp_connection->send_ag_indicators_segment = 0;
1885                 hfp_connection->send_ag_status_indicators = 1;
1886                 break;
1887             case HFP_CMD_LIST_CURRENT_CALLS:
1888                 hfp_connection->command = HFP_CMD_NONE;
1889                 hfp_connection->next_call_index = 0;
1890                 hfp_connection->send_status_of_current_calls = 1;
1891                 break;
1892             case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1893                 if (subscriber_numbers_count == 0){
1894                     hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1895                     break;
1896                 }
1897                 hfp_connection->next_subscriber_number_to_send = 0;
1898                 hfp_connection->send_subscriber_number = 1;
1899                 break;
1900             case HFP_CMD_TRANSMIT_DTMF_CODES:
1901             {
1902                 hfp_connection->command = HFP_CMD_NONE;
1903                 char buffer[2];
1904                 buffer[0] = (char) hfp_connection->ag_dtmf_code;
1905                 buffer[1] = 0;
1906                 hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_TRANSMIT_DTMF_CODES, buffer);
1907                 break;
1908             }
1909             case HFP_CMD_HF_REQUEST_PHONE_NUMBER:
1910                 hfp_connection->command = HFP_CMD_NONE;
1911                 hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_ATTACH_NUMBER_TO_VOICE_TAG);
1912                 break;
1913             case HFP_CMD_TURN_OFF_EC_AND_NR:
1914                 hfp_connection->command = HFP_CMD_NONE;
1915                 if (get_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION)){
1916                     hfp_connection->ok_pending = 1;
1917                     hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION, hfp_connection->ag_echo_and_noise_reduction);
1918                     log_info("AG: EC/NR = %u", hfp_connection->ag_echo_and_noise_reduction);
1919                 } else {
1920                     hfp_connection->send_error = 1;
1921                 }
1922                 break;
1923             case HFP_CMD_CALL_ANSWERED:
1924                 hfp_connection->command = HFP_CMD_NONE;
1925                 log_info("HFP: ATA");
1926                 hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, hfp_connection);
1927                 break;
1928             case HFP_CMD_HANG_UP_CALL:
1929                 hfp_connection->command = HFP_CMD_NONE;
1930                 hfp_connection->ok_pending = 1;
1931                 hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_HF, hfp_connection);
1932                 break;
1933             case HFP_CMD_CALL_HOLD: {
1934                 hfp_connection->command = HFP_CMD_NONE;
1935                 hfp_connection->ok_pending = 1;
1936 
1937                 switch (hfp_connection->ag_call_hold_action){
1938                     case 0:
1939                         // Releases all held calls or sets User Determined User Busy (UDUB) for a waiting call.
1940                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_USER_BUSY, hfp_connection);
1941                         break;
1942                     case 1:
1943                         // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1944                         // Where both a held and a waiting call exist, the above procedures shall apply to the
1945                         // waiting call (i.e., not to the held call) in conflicting situation.
1946                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
1947                         break;
1948                     case 2:
1949                         // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1950                         // Where both a held and a waiting call exist, the above procedures shall apply to the
1951                         // waiting call (i.e., not to the held call) in conflicting situation.
1952                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
1953                         break;
1954                     case 3:
1955                         // Adds a held call to the conversation.
1956                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_ADD_HELD_CALL, hfp_connection);
1957                         break;
1958                     case 4:
1959                         // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer).
1960                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, hfp_connection);
1961                         break;
1962                     default:
1963                         break;
1964                 }
1965 				hfp_connection->call_index = 0;
1966                 break;
1967             }
1968             case HFP_CMD_CALL_PHONE_NUMBER:
1969                 hfp_connection->command = HFP_CMD_NONE;
1970                 hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED, hfp_connection);
1971                 break;
1972             case HFP_CMD_REDIAL_LAST_NUMBER:
1973                 hfp_connection->command = HFP_CMD_NONE;
1974                 hfp_ag_call_sm(HFP_AG_OUTGOING_REDIAL_INITIATED, hfp_connection);
1975                 break;
1976             case HFP_CMD_ENABLE_CLIP:
1977                 hfp_connection->command = HFP_CMD_NONE;
1978                 log_info("hfp: clip set, now: %u", hfp_connection->clip_enabled);
1979                 hfp_connection->ok_pending = 1;
1980                 break;
1981             case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1982                 hfp_connection->command = HFP_CMD_NONE;
1983                 log_info("hfp: call waiting notification set, now: %u", hfp_connection->call_waiting_notification_enabled);
1984                 hfp_connection->ok_pending = 1;
1985                 break;
1986             case HFP_CMD_SET_SPEAKER_GAIN:
1987                 hfp_connection->command = HFP_CMD_NONE;
1988                 hfp_connection->ok_pending = 1;
1989                 log_info("HF speaker gain = %u", hfp_connection->speaker_gain);
1990                 break;
1991             case HFP_CMD_SET_MICROPHONE_GAIN:
1992                 hfp_connection->command = HFP_CMD_NONE;
1993                 hfp_connection->ok_pending = 1;
1994                 log_info("HF microphone gain = %u", hfp_connection->microphone_gain);
1995                 break;
1996             default:
1997                 break;
1998         }
1999     }
2000 }
2001 
2002 static void hfp_run(void){
2003     btstack_linked_list_iterator_t it;
2004     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2005     while (btstack_linked_list_iterator_has_next(&it)){
2006         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2007         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2008         hfp_ag_run_for_context(hfp_connection);
2009     }
2010 }
2011 
2012 static void rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2013     switch (packet_type){
2014         case RFCOMM_DATA_PACKET:
2015             hfp_ag_handle_rfcomm_data(packet_type, channel, packet, size);
2016             break;
2017         case HCI_EVENT_PACKET:
2018             if (packet[0] == RFCOMM_EVENT_CAN_SEND_NOW){
2019                 uint16_t rfcomm_cid = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
2020                 hfp_ag_run_for_context(get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid));
2021                 return;
2022             }
2023             hfp_handle_rfcomm_event(packet_type, channel, packet, size, HFP_ROLE_AG);
2024             break;
2025         default:
2026             break;
2027     }
2028 
2029     hfp_run();
2030 }
2031 
2032 static void hci_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2033     hfp_handle_hci_event(packet_type, channel, packet, size, HFP_ROLE_AG);
2034 
2035     // allow for sco established -> ring transition
2036     if (packet_type != HCI_EVENT_PACKET) return;
2037     if (hci_event_packet_get_type(packet) != HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE) return;
2038     hfp_run();
2039 }
2040 
2041 void hfp_ag_init_codecs(int codecs_nr, uint8_t * codecs){
2042     if (codecs_nr > HFP_MAX_NUM_CODECS){
2043         log_error("hfp_init: codecs_nr (%d) > HFP_MAX_NUM_CODECS (%d)", codecs_nr, HFP_MAX_NUM_CODECS);
2044         return;
2045     }
2046     int i;
2047     hfp_codecs_nr = codecs_nr;
2048     for (i=0; i < codecs_nr; i++){
2049         hfp_codecs[i] = codecs[i];
2050     }
2051 }
2052 
2053 void hfp_ag_init_supported_features(uint32_t supported_features){
2054     hfp_supported_features = supported_features;
2055 }
2056 
2057 void hfp_ag_init_ag_indicators(int ag_indicators_nr, hfp_ag_indicator_t * ag_indicators){
2058     hfp_ag_indicators_nr = ag_indicators_nr;
2059     (void)memcpy(hfp_ag_indicators, ag_indicators,
2060                  ag_indicators_nr * sizeof(hfp_ag_indicator_t));
2061 }
2062 
2063 void hfp_ag_init_hf_indicators(int hf_indicators_nr, hfp_generic_status_indicator_t * hf_indicators){
2064     if (hf_indicators_nr > HFP_MAX_NUM_INDICATORS) return;
2065     hfp_generic_status_indicators_nr = hf_indicators_nr;
2066     (void)memcpy(hfp_generic_status_indicators, hf_indicators,
2067                  hf_indicators_nr * sizeof(hfp_generic_status_indicator_t));
2068 }
2069 
2070 void hfp_ag_init_call_hold_services(int call_hold_services_nr, const char * call_hold_services[]){
2071     hfp_ag_call_hold_services_nr = call_hold_services_nr;
2072     (void)memcpy(hfp_ag_call_hold_services, call_hold_services,
2073                  call_hold_services_nr * sizeof(char *));
2074 }
2075 
2076 
2077 void hfp_ag_init(uint16_t rfcomm_channel_nr){
2078 
2079     hfp_init();
2080 
2081     hci_event_callback_registration.callback = &hci_event_packet_handler;
2082     hci_add_event_handler(&hci_event_callback_registration);
2083 
2084     rfcomm_register_service(&rfcomm_packet_handler, rfcomm_channel_nr, 0xffff);
2085 
2086     // used to set packet handler for outgoing rfcomm connections - could be handled by emitting an event to us
2087     hfp_set_ag_rfcomm_packet_handler(&rfcomm_packet_handler);
2088 
2089     hfp_ag_response_and_hold_active = 0;
2090     subscriber_numbers = NULL;
2091     subscriber_numbers_count = 0;
2092 
2093     hfp_gsm_init();
2094 }
2095 
2096 void hfp_ag_establish_service_level_connection(bd_addr_t bd_addr){
2097     hfp_establish_service_level_connection(bd_addr, BLUETOOTH_SERVICE_CLASS_HANDSFREE, HFP_ROLE_AG);
2098 }
2099 
2100 void hfp_ag_release_service_level_connection(hci_con_handle_t acl_handle){
2101     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2102     if (!hfp_connection){
2103         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2104         return;
2105     }
2106     hfp_release_service_level_connection(hfp_connection);
2107     hfp_ag_run_for_context(hfp_connection);
2108 }
2109 
2110 void hfp_ag_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle, hfp_cme_error_t error){
2111     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2112     if (!hfp_connection){
2113         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2114         return;
2115     }
2116     hfp_connection->extended_audio_gateway_error = 0;
2117     if (!hfp_connection->enable_extended_audio_gateway_error_report){
2118         return;
2119     }
2120     hfp_connection->extended_audio_gateway_error = error;
2121     hfp_ag_run_for_context(hfp_connection);
2122 }
2123 
2124 static void hfp_ag_setup_audio_connection(hfp_connection_t * hfp_connection){
2125     log_info("hfp_ag_setup_audio_connection state %u", hfp_connection->state);
2126     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return;
2127     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
2128 
2129     hfp_connection->establish_audio_connection = 1;
2130     if (!has_codec_negotiation_feature(hfp_connection)){
2131         log_info("hfp_ag_establish_audio_connection - no codec negotiation feature, using CVSD");
2132         hfp_connection->negotiated_codec = HFP_CODEC_CVSD;
2133         hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
2134         // now, pick link settings
2135         hfp_init_link_settings(hfp_connection, hfp_ag_esco_s4_supported(hfp_connection));
2136         return;
2137     }
2138 
2139     hfp_connection->trigger_codec_exchange = 1;
2140 }
2141 
2142 void hfp_ag_establish_audio_connection(hci_con_handle_t acl_handle){
2143     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2144     if (!hfp_connection){
2145         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2146         return;
2147     }
2148     hfp_connection->trigger_codec_exchange = 0;
2149     hfp_connection->establish_audio_connection = 0;
2150     hfp_ag_setup_audio_connection(hfp_connection);
2151     hfp_ag_run_for_context(hfp_connection);
2152 }
2153 
2154 void hfp_ag_release_audio_connection(hci_con_handle_t acl_handle){
2155     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2156     if (!hfp_connection){
2157         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2158         return;
2159     }
2160     hfp_release_audio_connection(hfp_connection);
2161     hfp_ag_run_for_context(hfp_connection);
2162 }
2163 
2164 /**
2165  * @brief Enable in-band ring tone
2166  */
2167 void hfp_ag_set_use_in_band_ring_tone(int use_in_band_ring_tone){
2168     if (get_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE) == use_in_band_ring_tone){
2169         return;
2170     }
2171     hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE, use_in_band_ring_tone);
2172 
2173     btstack_linked_list_iterator_t it;
2174     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2175     while (btstack_linked_list_iterator_has_next(&it)){
2176         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2177         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2178         hfp_connection->command = HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING;
2179         hfp_ag_run_for_context(hfp_connection);
2180     }
2181 }
2182 
2183 /**
2184  * @brief Called from GSM
2185  */
2186 void hfp_ag_incoming_call(void){
2187     hfp_ag_call_sm(HFP_AG_INCOMING_CALL, NULL);
2188 }
2189 
2190 /**
2191  * @brief number is stored.
2192  */
2193 void hfp_ag_set_clip(uint8_t type, const char * number){
2194     hfp_gsm_handle_event_with_clip(HFP_AG_SET_CLIP, type, number);
2195 }
2196 
2197 void hfp_ag_call_dropped(void){
2198     hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2199 }
2200 
2201 // call from AG UI
2202 void hfp_ag_answer_incoming_call(void){
2203     hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, NULL);
2204 }
2205 
2206 void hfp_ag_join_held_call(void){
2207     hfp_ag_call_sm(HFP_AG_HELD_CALL_JOINED_BY_AG, NULL);
2208 }
2209 
2210 void hfp_ag_terminate_call(void){
2211     hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_AG, NULL);
2212 }
2213 
2214 void hfp_ag_outgoing_call_ringing(void){
2215     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_RINGING, NULL);
2216 }
2217 
2218 void hfp_ag_outgoing_call_established(void){
2219     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ESTABLISHED, NULL);
2220 }
2221 
2222 void hfp_ag_outgoing_call_rejected(void){
2223     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_REJECTED, NULL);
2224 }
2225 
2226 void hfp_ag_outgoing_call_accepted(void){
2227     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ACCEPTED, NULL);
2228 }
2229 
2230 void hfp_ag_hold_incoming_call(void){
2231     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, NULL);
2232 }
2233 
2234 void hfp_ag_accept_held_incoming_call(void) {
2235     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, NULL);
2236 }
2237 
2238 void hfp_ag_reject_held_incoming_call(void){
2239     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, NULL);
2240 }
2241 
2242 static void hfp_ag_set_ag_indicator(const char * name, int value){
2243     int indicator_index = get_ag_indicator_index_for_name(name);
2244     if (indicator_index < 0) return;
2245     hfp_ag_indicators[indicator_index].status = value;
2246 
2247 
2248     btstack_linked_list_iterator_t it;
2249     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2250     while (btstack_linked_list_iterator_has_next(&it)){
2251         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2252         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2253         if (! hfp_connection->ag_indicators[indicator_index].enabled) {
2254             log_info("AG indicator '%s' changed to %u but not enabled", hfp_ag_indicators[indicator_index].name, value);
2255             continue;
2256         }
2257         log_info("AG indicator '%s' changed to %u, request transfer statur", hfp_ag_indicators[indicator_index].name, value);
2258         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
2259         hfp_ag_run_for_context(hfp_connection);
2260     }
2261 }
2262 
2263 void hfp_ag_set_registration_status(int status){
2264     hfp_ag_set_ag_indicator("service", status);
2265 }
2266 
2267 void hfp_ag_set_signal_strength(int strength){
2268     hfp_ag_set_ag_indicator("signal", strength);
2269 }
2270 
2271 void hfp_ag_set_roaming_status(int status){
2272     hfp_ag_set_ag_indicator("roam", status);
2273 }
2274 
2275 void hfp_ag_set_battery_level(int level){
2276     hfp_ag_set_ag_indicator("battchg", level);
2277 }
2278 
2279 void hfp_ag_activate_voice_recognition(hci_con_handle_t acl_handle, int activate){
2280     if (!get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)) return;
2281     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2282     if (!hfp_connection){
2283         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2284         return;
2285     }
2286 
2287     if (!get_bit(hfp_connection->remote_supported_features, HFP_HFSF_VOICE_RECOGNITION_FUNCTION)) {
2288         log_info("AG cannot acivate voice recognition - not supported by HF");
2289         return;
2290     }
2291 
2292     if (activate){
2293         hfp_ag_establish_audio_connection(acl_handle);
2294     }
2295 
2296     hfp_connection->ag_activate_voice_recognition = activate;
2297     hfp_connection->command = HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
2298     hfp_ag_run_for_context(hfp_connection);
2299 }
2300 
2301 void hfp_ag_set_microphone_gain(hci_con_handle_t acl_handle, int gain){
2302     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2303     if (!hfp_connection){
2304         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2305         return;
2306     }
2307     if (hfp_connection->microphone_gain != gain){
2308         hfp_connection->command = HFP_CMD_SET_MICROPHONE_GAIN;
2309         hfp_connection->microphone_gain = gain;
2310         hfp_connection->send_microphone_gain = 1;
2311     }
2312     hfp_ag_run_for_context(hfp_connection);
2313 }
2314 
2315 void hfp_ag_set_speaker_gain(hci_con_handle_t acl_handle, int gain){
2316     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2317     if (!hfp_connection){
2318         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2319         return;
2320     }
2321     if (hfp_connection->speaker_gain != gain){
2322         hfp_connection->speaker_gain = gain;
2323         hfp_connection->send_speaker_gain = 1;
2324     }
2325     hfp_ag_run_for_context(hfp_connection);
2326 }
2327 
2328 void hfp_ag_send_phone_number_for_voice_tag(hci_con_handle_t acl_handle, const char * number){
2329     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2330     if (!hfp_connection){
2331         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2332         return;
2333     }
2334     hfp_ag_set_clip(0, number);
2335     hfp_connection->send_phone_number_for_voice_tag = 1;
2336 }
2337 
2338 void hfp_ag_reject_phone_number_for_voice_tag(hci_con_handle_t acl_handle){
2339     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2340     if (!hfp_connection){
2341         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2342         return;
2343     }
2344     hfp_connection->send_error = 1;
2345 }
2346 
2347 void hfp_ag_send_dtmf_code_done(hci_con_handle_t acl_handle){
2348     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2349     if (!hfp_connection){
2350         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2351         return;
2352     }
2353     hfp_connection->ok_pending = 1;
2354 }
2355 
2356 void hfp_ag_set_subcriber_number_information(hfp_phone_number_t * numbers, int numbers_count){
2357     subscriber_numbers = numbers;
2358     subscriber_numbers_count = numbers_count;
2359 }
2360 
2361 void hfp_ag_clear_last_dialed_number(void){
2362     hfp_gsm_clear_last_dialed_number();
2363 }
2364 
2365 void hfp_ag_notify_incoming_call_waiting(hci_con_handle_t acl_handle){
2366     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2367     if (!hfp_connection){
2368         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2369         return;
2370     }
2371     if (!hfp_connection->call_waiting_notification_enabled) return;
2372 
2373     hfp_connection->ag_notify_incoming_call_waiting = 1;
2374     hfp_ag_run_for_context(hfp_connection);
2375 }
2376 
2377 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){
2378 	if (!name){
2379 		name = default_hfp_ag_service_name;
2380 	}
2381 	hfp_create_sdp_record(service, service_record_handle, BLUETOOTH_SERVICE_CLASS_HANDSFREE_AUDIO_GATEWAY, rfcomm_channel_nr, name);
2382 
2383 	/*
2384 	 * 0x01 – Ability to reject a call
2385 	 * 0x00 – No ability to reject a call
2386 	 */
2387 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0301);    // Hands-Free Profile - Network
2388 	de_add_number(service, DE_UINT, DE_SIZE_8, ability_to_reject_call);
2389 
2390 	// Construct SupportedFeatures for SDP bitmap:
2391 	//
2392 	// "The values of the “SupportedFeatures” bitmap given in Table 5.4 shall be the same as the values
2393 	//  of the Bits 0 to 4 of the unsolicited result code +BRSF"
2394 	//
2395 	// Wide band speech (bit 5) requires Codec negotiation
2396 	//
2397 	uint16_t sdp_features = supported_features & 0x1f;
2398 	if (wide_band_speech && (supported_features & (1 << HFP_AGSF_CODEC_NEGOTIATION))){
2399 		sdp_features |= 1 << 5;
2400 	}
2401 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);    // Hands-Free Profile - SupportedFeatures
2402 	de_add_number(service, DE_UINT, DE_SIZE_16, sdp_features);
2403 }
2404 
2405 void hfp_ag_register_packet_handler(btstack_packet_handler_t callback){
2406 	if (callback == NULL){
2407 		log_error("hfp_ag_register_packet_handler called with NULL callback");
2408 		return;
2409 	}
2410 	hfp_ag_callback = callback;
2411 	hfp_set_ag_callback(callback);
2412 }
2413