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