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