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