xref: /btstack/src/classic/hfp_ag.c (revision f8fbdce0c5067e7e7edd3a29934b1f9b79c8ff2d)
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_cmd.h"
52 #include "btstack_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(btstack_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(btstack_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     btstack_run_loop_set_timer(&context->hfp_timeout, 2000); // 5 seconds timeout
825     btstack_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     btstack_run_loop_remove_timer(&context->hfp_timeout);
832     btstack_run_loop_set_timer_handler(&context->hfp_timeout, hfp_timeout_handler);
833     btstack_run_loop_set_timer(&context->hfp_timeout, 2000); // 5 seconds timeout
834     btstack_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     btstack_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_with_call_number(HFP_AG_OUTGOING_CALL_INITIATED, (const char *) &connection->line_buffer[3]);
1380 
1381             connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1382 
1383             hfp_emit_string_event(hfp_callback, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, (const char *) &connection->line_buffer[3]);
1384             break;
1385 
1386         case HFP_AG_OUTGOING_REDIAL_INITIATED:{
1387             // directly reject call if number of free slots is exceeded
1388             if (!hfp_gsm_call_possible()){
1389                 connection->send_error = 1;
1390                 hfp_run_for_context(connection);
1391                 break;
1392             }
1393 
1394             hfp_gsm_handle_event(HFP_AG_OUTGOING_REDIAL_INITIATED);
1395             connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1396 
1397             printf("\nRedial last number");
1398             char * last_dialed_number = hfp_gsm_last_dialed_number();
1399 
1400             if (strlen(last_dialed_number) > 0){
1401                 printf("\nLast number exists: accept call");
1402                 hfp_emit_string_event(hfp_callback, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, last_dialed_number);
1403             } else {
1404                 printf("\nLast number missing: reject call");
1405                 hfp_ag_outgoing_call_rejected();
1406             }
1407             break;
1408         }
1409         case HFP_AG_OUTGOING_CALL_REJECTED:
1410             connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1411             if (!connection){
1412                 log_info("hfp_ag_call_sm: did not find outgoing connection in initiated state");
1413                 break;
1414             }
1415 
1416             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_REJECTED);
1417             connection->call_state = HFP_CALL_IDLE;
1418             connection->send_error = 1;
1419             hfp_run_for_context(connection);
1420             break;
1421 
1422         case HFP_AG_OUTGOING_CALL_ACCEPTED:{
1423             connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1424             if (!connection){
1425                 log_info("hfp_ag_call_sm: did not find outgoing connection in initiated state");
1426                 break;
1427             }
1428 
1429             connection->ok_pending = 1;
1430             connection->call_state = HFP_CALL_OUTGOING_DIALING;
1431 
1432             // trigger callsetup to be
1433             int put_call_on_hold = hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT;
1434             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_ACCEPTED);
1435 
1436             hfp_ag_set_callsetup_indicator();
1437             indicator_index = get_ag_indicator_index_for_name("callsetup");
1438             connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1439 
1440             // put current call on hold if active
1441             if (put_call_on_hold){
1442                 printf("AG putting current call on hold for new outgoing call\n");
1443                 hfp_ag_set_callheld_indicator();
1444                 indicator_index = get_ag_indicator_index_for_name("callheld");
1445                 hfp_ag_transfer_ag_indicators_status_cmd(connection->rfcomm_cid, &hfp_ag_indicators[indicator_index]);
1446             }
1447 
1448             // start audio if needed
1449             hfp_ag_establish_audio_connection(connection->remote_addr);
1450             break;
1451         }
1452         case HFP_AG_OUTGOING_CALL_RINGING:
1453             connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1454             if (!connection){
1455                 log_info("hfp_ag_call_sm: did not find outgoing connection in dialing state");
1456                 break;
1457             }
1458 
1459             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_RINGING);
1460             connection->call_state = HFP_CALL_OUTGOING_RINGING;
1461             hfp_ag_set_callsetup_indicator();
1462             hfp_ag_transfer_callsetup_state();
1463             break;
1464 
1465         case HFP_AG_OUTGOING_CALL_ESTABLISHED:{
1466             // get outgoing call
1467             connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_RINGING);
1468             if (!connection){
1469                 connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1470             }
1471             if (!connection){
1472                 log_info("hfp_ag_call_sm: did not find outgoing connection");
1473                 break;
1474             }
1475 
1476             int CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS = hfp_gsm_callheld_status() == HFP_CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS;
1477             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_ESTABLISHED);
1478             connection->call_state = HFP_CALL_ACTIVE;
1479             hfp_ag_set_callsetup_indicator();
1480             hfp_ag_set_call_indicator();
1481             hfp_ag_transfer_call_state();
1482             hfp_ag_transfer_callsetup_state();
1483             if (CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS){
1484                 hfp_ag_set_callheld_indicator();
1485                 hfp_ag_transfer_callheld_state();
1486             }
1487             break;
1488         }
1489 
1490         case HFP_AG_CALL_HOLD_USER_BUSY:
1491             hfp_gsm_handle_event(HFP_AG_CALL_HOLD_USER_BUSY);
1492             hfp_ag_set_callsetup_indicator();
1493             connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1494             connection->call_state = HFP_CALL_ACTIVE;
1495             printf("AG: Call Waiting, User Busy\n");
1496             break;
1497 
1498         case HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1499             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1500             int call_held = hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1501 
1502             // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1503             if (call_held || call_setup_in_progress){
1504                 hfp_gsm_handle_event_with_call_index(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, connection->call_index);
1505 
1506             }
1507 
1508             if (call_setup_in_progress){
1509                 printf("AG: Call Dropped, Accept new call\n");
1510                 hfp_ag_set_callsetup_indicator();
1511                 connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1512             } else {
1513                 printf("AG: Call Dropped, Resume held call\n");
1514             }
1515             if (call_held){
1516                 hfp_ag_set_callheld_indicator();
1517                 connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1518             }
1519 
1520             connection->call_state = HFP_CALL_ACTIVE;
1521             break;
1522         }
1523 
1524         case HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1525             // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1526             // only update if callsetup changed
1527             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1528             hfp_gsm_handle_event_with_call_index(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, connection->call_index);
1529 
1530             if (call_setup_in_progress){
1531                 printf("AG: Call on Hold, Accept new call\n");
1532                 hfp_ag_set_callsetup_indicator();
1533                 connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1534             } else {
1535                 printf("AG: Swap calls\n");
1536             }
1537 
1538             hfp_ag_set_callheld_indicator();
1539             // hfp_ag_set_callheld_state(HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED);
1540             connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1541             connection->call_state = HFP_CALL_ACTIVE;
1542             break;
1543         }
1544 
1545         case HFP_AG_CALL_HOLD_ADD_HELD_CALL:
1546             // Adds a held call to the conversation.
1547             if (hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD){
1548                 printf("AG: Join 3-way-call\n");
1549                 hfp_gsm_handle_event(HFP_AG_CALL_HOLD_ADD_HELD_CALL);
1550                 hfp_ag_set_callheld_indicator();
1551                 connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1552                 hfp_emit_event(hfp_callback, HFP_SUBEVENT_CONFERENCE_CALL, 0);
1553             }
1554             connection->call_state = HFP_CALL_ACTIVE;
1555             break;
1556         case HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS:
1557             // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer)
1558             hfp_gsm_handle_event(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS);
1559             printf("AG: Transfer call -> Connect two calls and disconnect\n");
1560             hfp_ag_set_call_indicator();
1561             hfp_ag_set_callheld_indicator();
1562             connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1563             connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1564             connection->call_state = HFP_CALL_IDLE;
1565             break;
1566 
1567         default:
1568             break;
1569     }
1570 
1571 
1572 }
1573 
1574 
1575 static void hfp_ag_send_call_status(hfp_connection_t * connection, int call_index){
1576     hfp_gsm_call_t * active_call = hfp_gsm_call(call_index);
1577     if (!active_call) return;
1578 
1579     int idx = active_call->index;
1580     hfp_enhanced_call_dir_t dir = active_call->direction;
1581     hfp_enhanced_call_status_t status = active_call->enhanced_status;
1582     hfp_enhanced_call_mode_t mode = active_call->mode;
1583     hfp_enhanced_call_mpty_t mpty = active_call->mpty;
1584     uint8_t type = active_call->clip_type;
1585     char * number = active_call->clip_number;
1586 
1587     char buffer[100];
1588     // TODO: check length of a buffer, to fit the MTU
1589     int offset = snprintf(buffer, sizeof(buffer), "\r\n%s: %d,%d,%d,%d,%d", HFP_LIST_CURRENT_CALLS, idx, dir, status, mode, mpty);
1590     if (number){
1591         offset += snprintf(buffer+offset, sizeof(buffer)-offset, ", \"%s\",%u", number, type);
1592     }
1593     snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n");
1594     printf("hfp_ag_send_current_call_status 000 index %d, dir %d, status %d, mode %d, mpty %d, type %d, number %s\n", idx, dir, status,
1595        mode, mpty, type, number);
1596     send_str_over_rfcomm(connection->rfcomm_cid, buffer);
1597 }
1598 
1599 static void hfp_run_for_context(hfp_connection_t *context){
1600     if (!context) return;
1601     if (!rfcomm_can_send_packet_now(context->rfcomm_cid)) return;
1602 
1603     if (context->send_status_of_current_calls){
1604         context->ok_pending = 0;
1605         if (context->next_call_index < hfp_gsm_get_number_of_calls()){
1606             context->next_call_index++;
1607             hfp_ag_send_call_status(context, context->next_call_index);
1608         } else {
1609             context->next_call_index = 0;
1610             context->ok_pending = 1;
1611             context->send_status_of_current_calls = 0;
1612         }
1613         return;
1614     }
1615 
1616     if (context->command == HFP_CMD_UNKNOWN){
1617         context->ok_pending = 0;
1618         context->send_error = 0;
1619         context->command = HFP_CMD_NONE;
1620         hfp_ag_error(context->rfcomm_cid);
1621         return;
1622     }
1623 
1624     if (context->send_error){
1625         context->send_error = 0;
1626         context->command = HFP_CMD_NONE;
1627         hfp_ag_error(context->rfcomm_cid);
1628         return;
1629     }
1630 
1631     // note: before update AG indicators and ok_pending
1632     if (context->send_response_and_hold_status){
1633         int status = context->send_response_and_hold_status - 1;
1634         context->send_response_and_hold_status = 0;
1635         hfp_ag_set_response_and_hold(context->rfcomm_cid, status);
1636         return;
1637     }
1638 
1639     if (context->ok_pending){
1640         context->ok_pending = 0;
1641         context->command = HFP_CMD_NONE;
1642         hfp_ag_ok(context->rfcomm_cid);
1643         return;
1644     }
1645 
1646     // update AG indicators
1647     if (context->ag_indicators_status_update_bitmap){
1648         int i;
1649         for (i=0;i<context->ag_indicators_nr;i++){
1650             if (get_bit(context->ag_indicators_status_update_bitmap, i)){
1651                 context->ag_indicators_status_update_bitmap = store_bit(context->ag_indicators_status_update_bitmap, i, 0);
1652                 if (!context->enable_status_update_for_ag_indicators) {
1653                     log_info("+CMER:3,0,0,0 - not sending update for '%s'", hfp_ag_indicators[i].name);
1654                     break;
1655                 }
1656                 hfp_ag_transfer_ag_indicators_status_cmd(context->rfcomm_cid, &hfp_ag_indicators[i]);
1657                 return;
1658             }
1659         }
1660     }
1661 
1662     if (context->ag_ring){
1663         context->ag_ring = 0;
1664         context->command = HFP_CMD_NONE;
1665         hfp_ag_ring(context->rfcomm_cid);
1666         return;
1667     }
1668 
1669     if (context->ag_send_clip){
1670         context->ag_send_clip = 0;
1671         context->command = HFP_CMD_NONE;
1672         hfp_ag_send_clip(context->rfcomm_cid);
1673         return;
1674     }
1675 
1676     if (context->send_phone_number_for_voice_tag){
1677         context->send_phone_number_for_voice_tag = 0;
1678         context->command = HFP_CMD_NONE;
1679         context->ok_pending = 1;
1680         hfp_ag_send_phone_number_for_voice_tag_cmd(context->rfcomm_cid);
1681         return;
1682     }
1683 
1684     if (context->send_subscriber_number){
1685         if (context->next_subscriber_number_to_send < subscriber_numbers_count){
1686             hfp_phone_number_t phone = subscriber_numbers[context->next_subscriber_number_to_send++];
1687             hfp_send_subscriber_number_cmd(context->rfcomm_cid, phone.type, phone.number);
1688         } else {
1689             context->send_subscriber_number = 0;
1690             context->next_subscriber_number_to_send = 0;
1691             hfp_ag_ok(context->rfcomm_cid);
1692         }
1693         context->command = HFP_CMD_NONE;
1694     }
1695 
1696     if (context->send_microphone_gain){
1697         context->send_microphone_gain = 0;
1698         context->command = HFP_CMD_NONE;
1699         hfp_ag_set_microphone_gain_cmd(context->rfcomm_cid, context->microphone_gain);
1700         return;
1701     }
1702 
1703     if (context->send_speaker_gain){
1704         context->send_speaker_gain = 0;
1705         context->command = HFP_CMD_NONE;
1706         hfp_ag_set_speaker_gain_cmd(context->rfcomm_cid, context->speaker_gain);
1707         return;
1708     }
1709 
1710     if (context->send_ag_status_indicators){
1711         context->send_ag_status_indicators = 0;
1712         hfp_ag_retrieve_indicators_status_cmd(context->rfcomm_cid);
1713         return;
1714     }
1715 
1716     int done = hfp_ag_run_for_context_service_level_connection(context);
1717     if (!done){
1718         done = hfp_ag_run_for_context_service_level_connection_queries(context);
1719     }
1720 
1721     if (!done){
1722         done = call_setup_state_machine(context);
1723     }
1724 
1725     if (!done){
1726         done = hfp_ag_run_for_audio_connection(context);
1727     }
1728 
1729     if (context->command == HFP_CMD_NONE && !done){
1730         // log_info("context->command == HFP_CMD_NONE");
1731         switch(context->state){
1732             case HFP_W2_DISCONNECT_RFCOMM:
1733                 context->state = HFP_W4_RFCOMM_DISCONNECTED;
1734                 rfcomm_disconnect(context->rfcomm_cid);
1735                 break;
1736             default:
1737                 break;
1738         }
1739     }
1740     if (done){
1741         context->command = HFP_CMD_NONE;
1742     }
1743 }
1744 static hfp_generic_status_indicator_t *get_hf_indicator_by_number(int number){
1745     int i;
1746     for (i=0;i< get_hfp_generic_status_indicators_nr();i++){
1747         hfp_generic_status_indicator_t * indicator = &get_hfp_generic_status_indicators()[i];
1748         if (indicator->uuid == number){
1749             return indicator;
1750         }
1751     }
1752     return NULL;
1753 }
1754 
1755 static void hfp_handle_rfcomm_data(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1756     hfp_connection_t * context = get_hfp_connection_context_for_rfcomm_cid(channel);
1757     if (!context) return;
1758 
1759     char last_char = packet[size-1];
1760     packet[size-1] = 0;
1761     log_info("HFP_RX %s", packet);
1762     packet[size-1] = last_char;
1763 
1764     int pos;
1765     for (pos = 0; pos < size ; pos++){
1766         hfp_parse(context, packet[pos], 0);
1767     }
1768     hfp_generic_status_indicator_t * indicator;
1769     int value;
1770     switch(context->command){
1771         case HFP_CMD_RESPONSE_AND_HOLD_QUERY:
1772             if (hfp_ag_response_and_hold_active){
1773                 context->send_response_and_hold_status = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD + 1;
1774             }
1775             context->ok_pending = 1;
1776             break;
1777         case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1778             value = atoi((char *)&context->line_buffer[0]);
1779             printf("HF Response and Hold: %u\n", value);
1780             switch(value){
1781                 case HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD:
1782                     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, context);
1783                     break;
1784                 case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED:
1785                     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF, context);
1786                     break;
1787                 case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED:
1788                     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF, context);
1789                     break;
1790                 default:
1791                     break;
1792             }
1793             context->ok_pending = 1;
1794             break;
1795         case HFP_CMD_HF_INDICATOR_STATUS:
1796             context->command = HFP_CMD_NONE;
1797             // find indicator by assigned number
1798             indicator = get_hf_indicator_by_number(context->parser_indicator_index);
1799             if (!indicator){
1800                 context->send_error = 1;
1801                 break;
1802             }
1803             value = atoi((char *)&context->line_buffer[0]);
1804             switch (indicator->uuid){
1805                 case 1: // enhanced security
1806                     if (value > 1) {
1807                         context->send_error = 1;
1808                         return;
1809                     }
1810                     printf("HF Indicator 'enhanced security' set to %u\n", value);
1811                     break;
1812                 case 2: // battery level
1813                     if (value > 100){
1814                         context->send_error = 1;
1815                         return;
1816                     }
1817                     printf("HF Indicator 'battery' set to %u\n", value);
1818                     break;
1819                 default:
1820                     printf("HF Indicator unknown set to %u\n", value);
1821                     break;
1822             }
1823             context->ok_pending = 1;
1824             break;
1825         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1826             // expected by SLC state machine
1827             if (context->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) break;
1828             context->send_ag_indicators_segment = 0;
1829             context->send_ag_status_indicators = 1;
1830             break;
1831         case HFP_CMD_LIST_CURRENT_CALLS:
1832             context->command = HFP_CMD_NONE;
1833             context->next_call_index = 0;
1834             context->send_status_of_current_calls = 1;
1835             break;
1836         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1837             if (subscriber_numbers_count == 0){
1838                 hfp_ag_ok(context->rfcomm_cid);
1839                 break;
1840             }
1841             context->next_subscriber_number_to_send = 0;
1842             context->send_subscriber_number = 1;
1843             break;
1844         case HFP_CMD_TRANSMIT_DTMF_CODES:
1845             context->command = HFP_CMD_NONE;
1846             hfp_emit_string_event(hfp_callback, HFP_SUBEVENT_TRANSMIT_DTMF_CODES, (const char *) &context->line_buffer[0]);
1847             break;
1848         case HFP_CMD_HF_REQUEST_PHONE_NUMBER:
1849             context->command = HFP_CMD_NONE;
1850             hfp_emit_event(hfp_callback, HFP_SUBEVENT_ATTACH_NUMBER_TO_VOICE_TAG, 0);
1851             break;
1852         case HFP_CMD_TURN_OFF_EC_AND_NR:
1853             context->command = HFP_CMD_NONE;
1854             if (get_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION)){
1855                 context->ok_pending = 1;
1856                 hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION, context->ag_echo_and_noise_reduction);
1857                 printf("AG: EC/NR = %u\n", context->ag_echo_and_noise_reduction);
1858             } else {
1859                 context->send_error = 1;
1860             }
1861             break;
1862         case HFP_CMD_CALL_ANSWERED:
1863             context->command = HFP_CMD_NONE;
1864             printf("HFP: ATA\n");
1865             hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, context);
1866             break;
1867         case HFP_CMD_HANG_UP_CALL:
1868             context->command = HFP_CMD_NONE;
1869             context->ok_pending = 1;
1870             hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_HF, context);
1871             break;
1872         case HFP_CMD_CALL_HOLD: {
1873             // TODO: fully implement this
1874             log_error("HFP: unhandled call hold type %c", context->line_buffer[0]);
1875             context->command = HFP_CMD_NONE;
1876             context->ok_pending = 1;
1877             context->call_index = 0;
1878 
1879             if (context->line_buffer[1] != '\0'){
1880                 context->call_index = atoi((char *)&context->line_buffer[1]);
1881             }
1882 
1883             switch (context->line_buffer[0]){
1884                 case '0':
1885                     // Releases all held calls or sets User Determined User Busy (UDUB) for a waiting call.
1886                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_USER_BUSY, context);
1887                     break;
1888                 case '1':
1889                     // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1890                     // Where both a held and a waiting call exist, the above procedures shall apply to the
1891                     // waiting call (i.e., not to the held call) in conflicting situation.
1892                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, context);
1893                     break;
1894                 case '2':
1895                     // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1896                     // Where both a held and a waiting call exist, the above procedures shall apply to the
1897                     // waiting call (i.e., not to the held call) in conflicting situation.
1898                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, context);
1899                     break;
1900                 case '3':
1901                     // Adds a held call to the conversation.
1902                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_ADD_HELD_CALL, context);
1903                     break;
1904                 case '4':
1905                     // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer).
1906                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, context);
1907                     break;
1908                 default:
1909                     break;
1910             }
1911             break;
1912         }
1913         case HFP_CMD_CALL_PHONE_NUMBER:
1914             context->command = HFP_CMD_NONE;
1915             hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED, context);
1916             break;
1917         case HFP_CMD_REDIAL_LAST_NUMBER:
1918             context->command = HFP_CMD_NONE;
1919             hfp_ag_call_sm(HFP_AG_OUTGOING_REDIAL_INITIATED, context);
1920             break;
1921         case HFP_CMD_ENABLE_CLIP:
1922             context->command = HFP_CMD_NONE;
1923             context->clip_enabled = context->line_buffer[8] != '0';
1924             log_info("hfp: clip set, now: %u", context->clip_enabled);
1925             context->ok_pending = 1;
1926             break;
1927         case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1928             context->command = HFP_CMD_NONE;
1929             context->call_waiting_notification_enabled = context->line_buffer[8] != '0';
1930             log_info("hfp: call waiting notification set, now: %u", context->call_waiting_notification_enabled);
1931             context->ok_pending = 1;
1932             break;
1933         case HFP_CMD_SET_SPEAKER_GAIN:
1934             context->command = HFP_CMD_NONE;
1935             context->ok_pending = 1;
1936             printf("HF speaker gain = %u\n", context->speaker_gain);
1937             break;
1938         case HFP_CMD_SET_MICROPHONE_GAIN:
1939             context->command = HFP_CMD_NONE;
1940             context->ok_pending = 1;
1941             printf("HF microphone gain = %u\n", context->microphone_gain);
1942             break;
1943         default:
1944             break;
1945     }
1946 }
1947 
1948 static void hfp_run(void){
1949     btstack_linked_list_iterator_t it;
1950     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1951     while (btstack_linked_list_iterator_has_next(&it)){
1952         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1953         hfp_run_for_context(connection);
1954     }
1955 }
1956 
1957 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1958     switch (packet_type){
1959         case RFCOMM_DATA_PACKET:
1960             hfp_handle_rfcomm_data(packet_type, channel, packet, size);
1961             break;
1962         case HCI_EVENT_PACKET:
1963             hfp_handle_hci_event(hfp_callback, packet_type, packet, size);
1964             break;
1965         default:
1966             break;
1967     }
1968 
1969     hfp_run();
1970 }
1971 
1972 static void hfp_ag_set_ag_indicators(hfp_ag_indicator_t * ag_indicators, int ag_indicators_nr){
1973     hfp_ag_indicators_nr = ag_indicators_nr;
1974     memcpy(hfp_ag_indicators, ag_indicators, ag_indicators_nr * sizeof(hfp_ag_indicator_t));
1975 }
1976 
1977 void hfp_ag_init(uint16_t rfcomm_channel_nr, uint32_t supported_features,
1978     uint8_t * codecs, int codecs_nr,
1979     hfp_ag_indicator_t * ag_indicators, int ag_indicators_nr,
1980     hfp_generic_status_indicator_t * hf_indicators, int hf_indicators_nr,
1981     const char *call_hold_services[], int call_hold_services_nr){
1982     if (codecs_nr > HFP_MAX_NUM_CODECS){
1983         log_error("hfp_init: codecs_nr (%d) > HFP_MAX_NUM_CODECS (%d)", codecs_nr, HFP_MAX_NUM_CODECS);
1984         return;
1985     }
1986     l2cap_init();
1987     l2cap_register_packet_handler(packet_handler);
1988 
1989     rfcomm_register_packet_handler(packet_handler);
1990 
1991     hfp_init(rfcomm_channel_nr);
1992 
1993     hfp_supported_features = supported_features;
1994     hfp_codecs_nr = codecs_nr;
1995 
1996     int i;
1997     for (i=0; i<codecs_nr; i++){
1998         hfp_codecs[i] = codecs[i];
1999     }
2000 
2001     hfp_ag_set_ag_indicators(ag_indicators, ag_indicators_nr);
2002 
2003     set_hfp_generic_status_indicators(hf_indicators, hf_indicators_nr);
2004 
2005     hfp_ag_call_hold_services_nr = call_hold_services_nr;
2006     memcpy(hfp_ag_call_hold_services, call_hold_services, call_hold_services_nr * sizeof(char *));
2007 
2008     hfp_ag_response_and_hold_active = 0;
2009     subscriber_numbers = NULL;
2010     subscriber_numbers_count = 0;
2011 
2012     hfp_gsm_init();
2013 }
2014 
2015 void hfp_ag_establish_service_level_connection(bd_addr_t bd_addr){
2016     hfp_establish_service_level_connection(bd_addr, SDP_Handsfree);
2017 }
2018 
2019 void hfp_ag_release_service_level_connection(bd_addr_t bd_addr){
2020     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr);
2021     hfp_release_service_level_connection(connection);
2022     hfp_run_for_context(connection);
2023 }
2024 
2025 void hfp_ag_report_extended_audio_gateway_error_result_code(bd_addr_t bd_addr, hfp_cme_error_t error){
2026     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr);
2027     if (!connection){
2028         log_error("HFP HF: connection doesn't exist.");
2029         return;
2030     }
2031     connection->extended_audio_gateway_error = 0;
2032     if (!connection->enable_extended_audio_gateway_error_report){
2033         return;
2034     }
2035     connection->extended_audio_gateway_error = error;
2036     hfp_run_for_context(connection);
2037 }
2038 
2039 static void hfp_ag_setup_audio_connection(hfp_connection_t * connection){
2040     if (connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return;
2041     if (connection->state >= HFP_W2_DISCONNECT_SCO) return;
2042 
2043     connection->establish_audio_connection = 1;
2044 
2045     if (!has_codec_negotiation_feature(connection)){
2046         log_info("hfp_ag_establish_audio_connection - no codec negotiation feature, using defaults");
2047         connection->codecs_state = HFP_CODECS_EXCHANGED;
2048     }
2049 
2050     switch (connection->codecs_state){
2051         case HFP_CODECS_IDLE:
2052         case HFP_CODECS_RECEIVED_LIST:
2053         case HFP_CODECS_AG_RESEND_COMMON_CODEC:
2054         case HFP_CODECS_ERROR:
2055             connection->command = HFP_CMD_AG_SEND_COMMON_CODEC;
2056             break;
2057         default:
2058             break;
2059     }
2060 }
2061 
2062 void hfp_ag_establish_audio_connection(bd_addr_t bd_addr){
2063     hfp_ag_establish_service_level_connection(bd_addr);
2064     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr);
2065 
2066     connection->establish_audio_connection = 0;
2067     hfp_ag_setup_audio_connection(connection);
2068     hfp_run_for_context(connection);
2069 }
2070 
2071 void hfp_ag_release_audio_connection(bd_addr_t bd_addr){
2072     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr);
2073     hfp_release_audio_connection(connection);
2074     hfp_run_for_context(connection);
2075 }
2076 
2077 /**
2078  * @brief Enable in-band ring tone
2079  */
2080 void hfp_ag_set_use_in_band_ring_tone(int use_in_band_ring_tone){
2081     if (get_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE) == use_in_band_ring_tone){
2082         return;
2083     }
2084     hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE, use_in_band_ring_tone);
2085 
2086     btstack_linked_list_iterator_t it;
2087     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2088     while (btstack_linked_list_iterator_has_next(&it)){
2089         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2090         connection->command = HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING;
2091         hfp_run_for_context(connection);
2092     }
2093 }
2094 
2095 /**
2096  * @brief Called from GSM
2097  */
2098 void hfp_ag_incoming_call(void){
2099     hfp_ag_call_sm(HFP_AG_INCOMING_CALL, NULL);
2100 }
2101 
2102 /**
2103  * @brief number is stored.
2104  */
2105 void hfp_ag_set_clip(uint8_t type, const char * number){
2106     hfp_gsm_handle_event_with_clip(HFP_AG_SET_CLIP, type, number);
2107 }
2108 
2109 void hfp_ag_call_dropped(void){
2110     hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2111 }
2112 
2113 // call from AG UI
2114 void hfp_ag_answer_incoming_call(void){
2115     hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, NULL);
2116 }
2117 
2118 void hfp_ag_join_held_call(void){
2119     hfp_ag_call_sm(HFP_AG_HELD_CALL_JOINED_BY_AG, NULL);
2120 }
2121 
2122 void hfp_ag_terminate_call(void){
2123     hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_AG, NULL);
2124 }
2125 
2126 void hfp_ag_outgoing_call_ringing(void){
2127     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_RINGING, NULL);
2128 }
2129 
2130 void hfp_ag_outgoing_call_established(void){
2131     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ESTABLISHED, NULL);
2132 }
2133 
2134 void hfp_ag_outgoing_call_rejected(void){
2135     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_REJECTED, NULL);
2136 }
2137 
2138 void hfp_ag_outgoing_call_accepted(void){
2139     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ACCEPTED, NULL);
2140 }
2141 
2142 void hfp_ag_hold_incoming_call(void){
2143     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, NULL);
2144 }
2145 
2146 void hfp_ag_accept_held_incoming_call(void) {
2147     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, NULL);
2148 }
2149 
2150 void hfp_ag_reject_held_incoming_call(void){
2151     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, NULL);
2152 }
2153 
2154 static void hfp_ag_set_ag_indicator(const char * name, int value){
2155     int indicator_index = get_ag_indicator_index_for_name(name);
2156     if (indicator_index < 0) return;
2157     hfp_ag_indicators[indicator_index].status = value;
2158 
2159 
2160     btstack_linked_list_iterator_t it;
2161     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2162     while (btstack_linked_list_iterator_has_next(&it)){
2163         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2164         if (!connection->ag_indicators[indicator_index].enabled) {
2165             log_info("AG indicator '%s' changed to %u but not enabled", hfp_ag_indicators[indicator_index].name, value);
2166             continue;
2167         }
2168         log_info("AG indicator '%s' changed to %u, request transfer statur", hfp_ag_indicators[indicator_index].name, value);
2169         connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, indicator_index, 1);
2170         hfp_run_for_context(connection);
2171     }
2172 }
2173 
2174 /*
2175  * @brief
2176  */
2177 void hfp_ag_set_registration_status(int status){
2178     hfp_ag_set_ag_indicator("service", status);
2179 }
2180 
2181 /*
2182  * @brief
2183  */
2184 void hfp_ag_set_signal_strength(int strength){
2185     hfp_ag_set_ag_indicator("signal", strength);
2186 }
2187 
2188 /*
2189  * @brief
2190  */
2191 void hfp_ag_set_roaming_status(int status){
2192     hfp_ag_set_ag_indicator("roam", status);
2193 }
2194 
2195 /*
2196  * @brief
2197  */
2198 void hfp_ag_set_battery_level(int level){
2199     hfp_ag_set_ag_indicator("battchg", level);
2200 }
2201 
2202 /*
2203  * @brief
2204  */
2205 void hfp_ag_activate_voice_recognition(bd_addr_t bd_addr, int activate){
2206     if (!get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)) return;
2207     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr);
2208 
2209     if (!get_bit(connection->remote_supported_features, HFP_HFSF_VOICE_RECOGNITION_FUNCTION)) {
2210         printf("AG cannot acivate voice recognition - not supported by HF\n");
2211         return;
2212     }
2213 
2214     if (activate){
2215         hfp_ag_establish_audio_connection(bd_addr);
2216     }
2217 
2218     connection->ag_activate_voice_recognition = activate;
2219     connection->command = HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
2220     hfp_run_for_context(connection);
2221 }
2222 
2223 /*
2224  * @brief
2225  */
2226 void hfp_ag_set_microphone_gain(bd_addr_t bd_addr, int gain){
2227     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr);
2228     if (connection->microphone_gain != gain){
2229         connection->command = HFP_CMD_SET_MICROPHONE_GAIN;
2230         connection->microphone_gain = gain;
2231         connection->send_microphone_gain = 1;
2232     }
2233     hfp_run_for_context(connection);
2234 }
2235 
2236 /*
2237  * @brief
2238  */
2239 void hfp_ag_set_speaker_gain(bd_addr_t bd_addr, int gain){
2240     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr);
2241     if (connection->speaker_gain != gain){
2242         connection->speaker_gain = gain;
2243         connection->send_speaker_gain = 1;
2244     }
2245     hfp_run_for_context(connection);
2246 }
2247 
2248 /*
2249  * @brief
2250  */
2251 void hfp_ag_send_phone_number_for_voice_tag(bd_addr_t bd_addr, const char * number){
2252     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr);
2253     hfp_ag_set_clip(0, number);
2254     connection->send_phone_number_for_voice_tag = 1;
2255 }
2256 
2257 void hfp_ag_reject_phone_number_for_voice_tag(bd_addr_t bd_addr){
2258     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr);
2259     connection->send_error = 1;
2260 }
2261 
2262 void hfp_ag_send_dtmf_code_done(bd_addr_t bd_addr){
2263     hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr);
2264     connection->ok_pending = 1;
2265 }
2266 
2267 void hfp_ag_set_subcriber_number_information(hfp_phone_number_t * numbers, int numbers_count){
2268     subscriber_numbers = numbers;
2269     subscriber_numbers_count = numbers_count;
2270 }
2271 
2272 void hfp_ag_clear_last_dialed_number(void){
2273     hfp_gsm_clear_last_dialed_number();
2274 }
2275 
2276 
2277