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