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