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