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