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