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