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