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