xref: /btstack/src/classic/hfp_ag.c (revision 64a157956a29a7201f9722442a322467773fe872)
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     // anything else requires eSCO support on both sides
545     if (hci_extended_sco_link_supported() && hci_remote_esco_supported(hfp_connection->acl_handle)){
546         switch (hfp_connection->negotiated_codec){
547             case HFP_CODEC_CVSD:
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                 break;
554             case HFP_CODEC_MSBC:
555                 hfp_connection->link_setting = HFP_LINK_SETTINGS_T2;
556                 break;
557             default:
558                 break;
559         }
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             break;
801         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
802             hfp_ag_ok(hfp_connection->rfcomm_cid);
803             return 1;
804         default:
805             break;
806     }
807     return 0;
808 }
809 
810 static int hfp_ag_run_for_audio_connection(hfp_connection_t * hfp_connection){
811     if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED ||
812         hfp_connection->state > HFP_W2_DISCONNECT_SCO) return 0;
813 
814 
815     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED && hfp_connection->release_audio_connection){
816         hfp_connection->state = HFP_W4_SCO_DISCONNECTED;
817         hfp_connection->release_audio_connection = 0;
818         gap_disconnect(hfp_connection->sco_handle);
819         return 1;
820     }
821 
822     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
823 
824     // run codecs exchange
825     int done = codecs_exchange_state_machine(hfp_connection);
826     if (done) return done;
827 
828     if (hfp_connection->codecs_state != HFP_CODECS_EXCHANGED) return done;
829     if (hfp_connection->establish_audio_connection){
830         hfp_connection->state = HFP_W4_SCO_CONNECTED;
831         hfp_connection->establish_audio_connection = 0;
832         hfp_setup_synchronous_connection(hfp_connection);
833         return 1;
834     }
835     return 0;
836 }
837 
838 static hfp_connection_t * hfp_ag_context_for_timer(btstack_timer_source_t * ts){
839     btstack_linked_list_iterator_t it;
840     btstack_linked_list_iterator_init(&it, hfp_get_connections());
841 
842     while (btstack_linked_list_iterator_has_next(&it)){
843         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
844         if ( & hfp_connection->hfp_timeout == ts) {
845             return hfp_connection;
846         }
847     }
848     return NULL;
849 }
850 
851 static void hfp_timeout_handler(btstack_timer_source_t * timer){
852     hfp_connection_t * hfp_connection = hfp_ag_context_for_timer(timer);
853     if (!hfp_connection) return;
854 
855     log_info("HFP start ring timeout, con handle 0x%02x", hfp_connection->acl_handle);
856     hfp_connection->ag_ring = 1;
857     hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
858 
859     btstack_run_loop_set_timer(& hfp_connection->hfp_timeout, 2000); // 2 seconds timeout
860     btstack_run_loop_add_timer(& hfp_connection->hfp_timeout);
861 
862     hfp_run_for_context(hfp_connection);
863 }
864 
865 static void hfp_timeout_start(hfp_connection_t * hfp_connection){
866     btstack_run_loop_remove_timer(& hfp_connection->hfp_timeout);
867     btstack_run_loop_set_timer_handler(& hfp_connection->hfp_timeout, hfp_timeout_handler);
868     btstack_run_loop_set_timer(& hfp_connection->hfp_timeout, 2000); // 2 seconds timeout
869     btstack_run_loop_add_timer(& hfp_connection->hfp_timeout);
870 }
871 
872 static void hfp_timeout_stop(hfp_connection_t * hfp_connection){
873     log_info("HFP stop ring timeout, con handle 0x%02x", hfp_connection->acl_handle);
874     btstack_run_loop_remove_timer(& hfp_connection->hfp_timeout);
875 }
876 
877 //
878 // transitition implementations for hfp_ag_call_state_machine
879 //
880 
881 static void hfp_ag_hf_start_ringing(hfp_connection_t * hfp_connection){
882     if (use_in_band_tone()){
883         hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING;
884         hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
885     } else {
886         hfp_timeout_start(hfp_connection);
887         hfp_connection->ag_ring = 1;
888         hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
889         hfp_connection->call_state = HFP_CALL_RINGING;
890         hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_START_RINGINIG);
891     }
892 }
893 
894 static void hfp_ag_hf_stop_ringing(hfp_connection_t * hfp_connection){
895     hfp_connection->ag_ring = 0;
896     hfp_connection->ag_send_clip = 0;
897     hfp_timeout_stop(hfp_connection);
898     hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_STOP_RINGINIG);
899 }
900 
901 static void hfp_ag_trigger_incoming_call(void){
902     int indicator_index = get_ag_indicator_index_for_name("callsetup");
903     if (indicator_index < 0) return;
904 
905     btstack_linked_list_iterator_t it;
906     btstack_linked_list_iterator_init(&it, hfp_get_connections());
907     while (btstack_linked_list_iterator_has_next(&it)){
908         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
909         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
910         if (hfp_connection->call_state == HFP_CALL_IDLE){
911             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
912             hfp_ag_hf_start_ringing(hfp_connection);
913         }
914         if (hfp_connection->call_state == HFP_CALL_ACTIVE){
915             hfp_connection->call_state = HFP_CALL_W2_SEND_CALL_WAITING;
916         }
917         hfp_run_for_context(hfp_connection);
918     }
919 }
920 
921 static void hfp_ag_transfer_callsetup_state(void){
922     int indicator_index = get_ag_indicator_index_for_name("callsetup");
923     if (indicator_index < 0) return;
924 
925     btstack_linked_list_iterator_t it;
926     btstack_linked_list_iterator_init(&it, hfp_get_connections());
927     while (btstack_linked_list_iterator_has_next(&it)){
928         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
929         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
930         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
931         hfp_run_for_context(hfp_connection);
932     }
933 }
934 
935 static void hfp_ag_transfer_call_state(void){
936     int indicator_index = get_ag_indicator_index_for_name("call");
937     if (indicator_index < 0) return;
938 
939     btstack_linked_list_iterator_t it;
940     btstack_linked_list_iterator_init(&it, hfp_get_connections());
941     while (btstack_linked_list_iterator_has_next(&it)){
942         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
943         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
944         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
945         hfp_run_for_context(hfp_connection);
946     }
947 }
948 
949 static void hfp_ag_transfer_callheld_state(void){
950     int indicator_index = get_ag_indicator_index_for_name("callheld");
951     if (indicator_index < 0) return;
952 
953     btstack_linked_list_iterator_t it;
954     btstack_linked_list_iterator_init(&it, hfp_get_connections());
955     while (btstack_linked_list_iterator_has_next(&it)){
956         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
957         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
958         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
959         hfp_run_for_context(hfp_connection);
960     }
961 }
962 
963 static void hfp_ag_hf_accept_call(hfp_connection_t * source){
964 
965     int call_indicator_index = get_ag_indicator_index_for_name("call");
966     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
967 
968     btstack_linked_list_iterator_t it;
969     btstack_linked_list_iterator_init(&it, hfp_get_connections());
970     while (btstack_linked_list_iterator_has_next(&it)){
971         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
972         if (hfp_connection->call_state != HFP_CALL_RINGING &&
973             hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING) continue;
974 
975         hfp_ag_hf_stop_ringing(hfp_connection);
976         if (hfp_connection == source){
977             hfp_connection->ok_pending = 1;
978 
979             if (use_in_band_tone()){
980                 hfp_connection->call_state = HFP_CALL_ACTIVE;
981             } else {
982                 hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE;
983                 hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
984             }
985 
986             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
987             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
988 
989         } else {
990             hfp_connection->call_state = HFP_CALL_IDLE;
991         }
992         hfp_run_for_context(hfp_connection);
993     }
994 }
995 
996 static void hfp_ag_ag_accept_call(void){
997 
998     int call_indicator_index = get_ag_indicator_index_for_name("call");
999     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1000 
1001     btstack_linked_list_iterator_t it;
1002     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1003     while (btstack_linked_list_iterator_has_next(&it)){
1004         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1005         if (hfp_connection->call_state != HFP_CALL_RINGING) continue;
1006 
1007         hfp_ag_hf_stop_ringing(hfp_connection);
1008         hfp_connection->call_state = HFP_CALL_TRIGGER_AUDIO_CONNECTION;
1009 
1010         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1011         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1012 
1013         hfp_run_for_context(hfp_connection);
1014         break;  // only single
1015     }
1016 }
1017 
1018 static void hfp_ag_trigger_reject_call(void){
1019     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1020     btstack_linked_list_iterator_t it;
1021     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1022     while (btstack_linked_list_iterator_has_next(&it)){
1023         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1024         if (connection->call_state != HFP_CALL_RINGING &&
1025             connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING) continue;
1026         hfp_ag_hf_stop_ringing(connection);
1027         connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1028         connection->call_state = HFP_CALL_IDLE;
1029         hfp_run_for_context(connection);
1030     }
1031 }
1032 
1033 static void hfp_ag_trigger_terminate_call(void){
1034     int call_indicator_index = get_ag_indicator_index_for_name("call");
1035 
1036     btstack_linked_list_iterator_t it;
1037     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1038     while (btstack_linked_list_iterator_has_next(&it)){
1039         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1040         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
1041         if (hfp_connection->call_state == HFP_CALL_IDLE) continue;
1042         hfp_connection->call_state = HFP_CALL_IDLE;
1043         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1044         hfp_connection->release_audio_connection = 1;
1045         hfp_run_for_context(hfp_connection);
1046     }
1047     hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_CALL_TERMINATED);
1048 }
1049 
1050 static void hfp_ag_set_callsetup_indicator(void){
1051     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("callsetup");
1052     if (!indicator){
1053         log_error("hfp_ag_set_callsetup_indicator: callsetup indicator is missing");
1054         return;
1055     };
1056     indicator->status = hfp_gsm_callsetup_status();
1057 }
1058 
1059 static void hfp_ag_set_callheld_indicator(void){
1060     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("callheld");
1061     if (!indicator){
1062         log_error("hfp_ag_set_callheld_state: callheld indicator is missing");
1063         return;
1064     };
1065     indicator->status = hfp_gsm_callheld_status();
1066 }
1067 
1068 static void hfp_ag_set_call_indicator(void){
1069     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("call");
1070     if (!indicator){
1071         log_error("hfp_ag_set_call_state: call indicator is missing");
1072         return;
1073     };
1074     indicator->status = hfp_gsm_call_status();
1075 }
1076 
1077 static void hfp_ag_stop_ringing(void){
1078     btstack_linked_list_iterator_t it;
1079     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1080     while (btstack_linked_list_iterator_has_next(&it)){
1081         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1082         if (hfp_connection->call_state != HFP_CALL_RINGING &&
1083             hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING) continue;
1084         hfp_ag_hf_stop_ringing(hfp_connection);
1085     }
1086 }
1087 
1088 static hfp_connection_t * hfp_ag_connection_for_call_state(hfp_call_state_t call_state){
1089     btstack_linked_list_iterator_t it;
1090     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1091     while (btstack_linked_list_iterator_has_next(&it)){
1092         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1093         if (hfp_connection->call_state == call_state) return hfp_connection;
1094     }
1095     return NULL;
1096 }
1097 
1098 static void hfp_ag_send_response_and_hold_state(hfp_response_and_hold_state_t state){
1099     btstack_linked_list_iterator_t it;
1100     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1101     while (btstack_linked_list_iterator_has_next(&it)){
1102         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1103         hfp_connection->send_response_and_hold_status = state + 1;
1104     }
1105 }
1106 
1107 static int call_setup_state_machine(hfp_connection_t * hfp_connection){
1108     int indicator_index;
1109     switch (hfp_connection->call_state){
1110         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING:
1111             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1112             // we got event: audio hfp_connection established
1113             hfp_timeout_start(hfp_connection);
1114             hfp_connection->ag_ring = 1;
1115             hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
1116             hfp_connection->call_state = HFP_CALL_RINGING;
1117             hfp_connection->call_state = HFP_CALL_RINGING;
1118             hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_START_RINGINIG);
1119             break;
1120         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE:
1121             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1122             // we got event: audio hfp_connection established
1123             hfp_connection->call_state = HFP_CALL_ACTIVE;
1124             break;
1125         case HFP_CALL_W2_SEND_CALL_WAITING:
1126             hfp_connection->call_state = HFP_CALL_W4_CHLD;
1127             hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1128             indicator_index = get_ag_indicator_index_for_name("callsetup");
1129             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1130             break;
1131         default:
1132             break;
1133     }
1134     return 0;
1135 }
1136 // hfp_connection is used to identify originating HF
1137 static void hfp_ag_call_sm(hfp_ag_call_event_t event, hfp_connection_t * hfp_connection){
1138     int indicator_index;
1139     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1140     int callheld_indicator_index = get_ag_indicator_index_for_name("callheld");
1141     int call_indicator_index = get_ag_indicator_index_for_name("call");
1142 
1143     //printf("hfp_ag_call_sm event %d \n", event);
1144     switch (event){
1145         case HFP_AG_INCOMING_CALL:
1146             switch (hfp_gsm_call_status()){
1147                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1148                     switch (hfp_gsm_callsetup_status()){
1149                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1150                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL);
1151                             hfp_ag_set_callsetup_indicator();
1152                             hfp_ag_trigger_incoming_call();
1153                             log_info("AG rings");
1154                             break;
1155                         default:
1156                             break;
1157                     }
1158                     break;
1159                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1160                     switch (hfp_gsm_callsetup_status()){
1161                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1162                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL);
1163                             hfp_ag_set_callsetup_indicator();
1164                             hfp_ag_trigger_incoming_call();
1165                             log_info("AG call waiting");
1166                             break;
1167                         default:
1168                             break;
1169                     }
1170                     break;
1171             }
1172             break;
1173         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG:
1174             switch (hfp_gsm_call_status()){
1175                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1176                     switch (hfp_gsm_callsetup_status()){
1177                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1178                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG);
1179                             hfp_ag_set_call_indicator();
1180                             hfp_ag_set_callsetup_indicator();
1181                             hfp_ag_ag_accept_call();
1182                             log_info("AG answers call, accept call by GSM");
1183                             break;
1184                         default:
1185                             break;
1186                     }
1187                     break;
1188                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1189                     switch (hfp_gsm_callsetup_status()){
1190                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1191                             log_info("AG: current call is placed on hold, incoming call gets active");
1192                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG);
1193                             hfp_ag_set_callsetup_indicator();
1194                             hfp_ag_set_callheld_indicator();
1195                             hfp_ag_transfer_callsetup_state();
1196                             hfp_ag_transfer_callheld_state();
1197                             break;
1198                         default:
1199                             break;
1200                     }
1201                     break;
1202             }
1203             break;
1204 
1205         case HFP_AG_HELD_CALL_JOINED_BY_AG:
1206             switch (hfp_gsm_call_status()){
1207                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1208                     switch (hfp_gsm_callheld_status()){
1209                         case HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED:
1210                             log_info("AG: joining held call with active call");
1211                             hfp_gsm_handle_event(HFP_AG_HELD_CALL_JOINED_BY_AG);
1212                             hfp_ag_set_callheld_indicator();
1213                             hfp_ag_transfer_callheld_state();
1214                             hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_CONFERENCE_CALL);
1215                             break;
1216                         default:
1217                             break;
1218                     }
1219                     break;
1220                 default:
1221                     break;
1222             }
1223             break;
1224 
1225         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF:
1226             switch (hfp_gsm_call_status()){
1227                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1228                     switch (hfp_gsm_callsetup_status()){
1229                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1230                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF);
1231                             hfp_ag_set_callsetup_indicator();
1232                             hfp_ag_set_call_indicator();
1233                             hfp_ag_hf_accept_call(hfp_connection);
1234                             log_info("HF answers call, accept call by GSM");
1235                             hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_CALL_ANSWERED);
1236                             break;
1237                         default:
1238                             break;
1239                     }
1240                     break;
1241                 default:
1242                     break;
1243             }
1244             break;
1245 
1246         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG:
1247             switch (hfp_gsm_call_status()){
1248                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1249                     switch (hfp_gsm_callsetup_status()){
1250                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1251                             hfp_gsm_handle_event(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG);
1252                             hfp_ag_response_and_hold_active = 1;
1253                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1254                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1255                             // as with regualr call
1256                             hfp_ag_set_call_indicator();
1257                             hfp_ag_set_callsetup_indicator();
1258                             hfp_ag_ag_accept_call();
1259                             log_info("AG response and hold - hold by AG");
1260                             break;
1261                         default:
1262                             break;
1263                     }
1264                     break;
1265                 default:
1266                     break;
1267             }
1268             break;
1269 
1270         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF:
1271             switch (hfp_gsm_call_status()){
1272                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1273                     switch (hfp_gsm_callsetup_status()){
1274                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1275                             hfp_gsm_handle_event(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF);
1276                             hfp_ag_response_and_hold_active = 1;
1277                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1278                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1279                             // as with regualr call
1280                             hfp_ag_set_call_indicator();
1281                             hfp_ag_set_callsetup_indicator();
1282                             hfp_ag_hf_accept_call(hfp_connection);
1283                             log_info("AG response and hold - hold by HF");
1284                             break;
1285                         default:
1286                             break;
1287                     }
1288                     break;
1289                 default:
1290                     break;
1291             }
1292             break;
1293 
1294         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG:
1295         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF:
1296             if (!hfp_ag_response_and_hold_active) break;
1297             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1298             hfp_gsm_handle_event(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG);
1299             hfp_ag_response_and_hold_active = 0;
1300             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED;
1301             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1302             log_info("Held Call accepted and active");
1303             break;
1304 
1305         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG:
1306         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF:
1307             if (!hfp_ag_response_and_hold_active) break;
1308             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1309             hfp_gsm_handle_event(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG);
1310             hfp_ag_response_and_hold_active = 0;
1311             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1312             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1313             // from terminate by ag
1314             hfp_ag_set_call_indicator();
1315             hfp_ag_trigger_terminate_call();
1316             break;
1317 
1318         case HFP_AG_TERMINATE_CALL_BY_HF:
1319             switch (hfp_gsm_call_status()){
1320                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1321                     switch (hfp_gsm_callsetup_status()){
1322                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1323                             hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_HF);
1324                             hfp_ag_set_callsetup_indicator();
1325                             hfp_ag_transfer_callsetup_state();
1326                             hfp_ag_trigger_reject_call();
1327                             log_info("HF Rejected Incoming call, AG terminate call");
1328                             break;
1329                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1330                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1331                             hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_HF);
1332                             hfp_ag_set_callsetup_indicator();
1333                             hfp_ag_transfer_callsetup_state();
1334                             log_info("AG terminate outgoing call process");
1335                             break;
1336                         default:
1337                             break;
1338                     }
1339                     break;
1340                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1341                     hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_HF);
1342                     hfp_ag_set_call_indicator();
1343                     hfp_ag_transfer_call_state();
1344                     hfp_connection->call_state = HFP_CALL_IDLE;
1345                     log_info("AG terminate call");
1346                     break;
1347             }
1348             break;
1349 
1350         case HFP_AG_TERMINATE_CALL_BY_AG:
1351             switch (hfp_gsm_call_status()){
1352                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1353                     switch (hfp_gsm_callsetup_status()){
1354                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1355                             hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_AG);
1356                             hfp_ag_set_callsetup_indicator();
1357                             hfp_ag_trigger_reject_call();
1358                             log_info("AG Rejected Incoming call, AG terminate call");
1359                             break;
1360                         default:
1361                             break;
1362                     }
1363                     break;
1364                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1365                     hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_AG);
1366                     hfp_ag_set_callsetup_indicator();
1367                     hfp_ag_set_call_indicator();
1368                     hfp_ag_trigger_terminate_call();
1369                     log_info("AG terminate call");
1370                     break;
1371                 default:
1372                     break;
1373             }
1374             break;
1375         case HFP_AG_CALL_DROPPED:
1376             switch (hfp_gsm_call_status()){
1377                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1378                     switch (hfp_gsm_callsetup_status()){
1379                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1380                             hfp_ag_stop_ringing();
1381                             log_info("Incoming call interrupted");
1382                             break;
1383                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1384                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1385                             log_info("Outgoing call interrupted\n");
1386                             log_info("AG notify call dropped\n");
1387                             break;
1388                         default:
1389                             break;
1390                     }
1391                     hfp_gsm_handle_event(HFP_AG_CALL_DROPPED);
1392                     hfp_ag_set_callsetup_indicator();
1393                     hfp_ag_transfer_callsetup_state();
1394                     break;
1395                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1396                     if (hfp_ag_response_and_hold_active) {
1397                         hfp_gsm_handle_event(HFP_AG_CALL_DROPPED);
1398                         hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1399                         hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1400                     }
1401                     hfp_gsm_handle_event(HFP_AG_CALL_DROPPED);
1402                     hfp_ag_set_callsetup_indicator();
1403                     hfp_ag_set_call_indicator();
1404                     hfp_ag_trigger_terminate_call();
1405                     log_info("AG notify call dropped");
1406                     break;
1407                 default:
1408                     break;
1409             }
1410             break;
1411 
1412         case HFP_AG_OUTGOING_CALL_INITIATED:
1413             // directly reject call if number of free slots is exceeded
1414             if (!hfp_gsm_call_possible()){
1415                 hfp_connection->send_error = 1;
1416                 hfp_run_for_context(hfp_connection);
1417                 break;
1418             }
1419             hfp_gsm_handle_event_with_call_number(HFP_AG_OUTGOING_CALL_INITIATED, (const char *) &hfp_connection->line_buffer[3]);
1420 
1421             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1422 
1423             hfp_emit_string_event(hfp_callback, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, (const char *) &hfp_connection->line_buffer[3]);
1424             break;
1425 
1426         case HFP_AG_OUTGOING_REDIAL_INITIATED:{
1427             // directly reject call if number of free slots is exceeded
1428             if (!hfp_gsm_call_possible()){
1429                 hfp_connection->send_error = 1;
1430                 hfp_run_for_context(hfp_connection);
1431                 break;
1432             }
1433 
1434             hfp_gsm_handle_event(HFP_AG_OUTGOING_REDIAL_INITIATED);
1435             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1436 
1437             log_info("Redial last number");
1438             char * last_dialed_number = hfp_gsm_last_dialed_number();
1439 
1440             if (strlen(last_dialed_number) > 0){
1441                 log_info("Last number exists: accept call");
1442                 hfp_emit_string_event(hfp_callback, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, last_dialed_number);
1443             } else {
1444                 log_info("log_infoLast number missing: reject call");
1445                 hfp_ag_outgoing_call_rejected();
1446             }
1447             break;
1448         }
1449         case HFP_AG_OUTGOING_CALL_REJECTED:
1450             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1451             if (!hfp_connection){
1452                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1453                 break;
1454             }
1455 
1456             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_REJECTED);
1457             hfp_connection->call_state = HFP_CALL_IDLE;
1458             hfp_connection->send_error = 1;
1459             hfp_run_for_context(hfp_connection);
1460             break;
1461 
1462         case HFP_AG_OUTGOING_CALL_ACCEPTED:{
1463             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1464             if (!hfp_connection){
1465                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1466                 break;
1467             }
1468 
1469             hfp_connection->ok_pending = 1;
1470             hfp_connection->call_state = HFP_CALL_OUTGOING_DIALING;
1471 
1472             // trigger callsetup to be
1473             int put_call_on_hold = hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT;
1474             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_ACCEPTED);
1475 
1476             hfp_ag_set_callsetup_indicator();
1477             indicator_index = get_ag_indicator_index_for_name("callsetup");
1478             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1479 
1480             // put current call on hold if active
1481             if (put_call_on_hold){
1482                 log_info("AG putting current call on hold for new outgoing calllog_info");
1483                 hfp_ag_set_callheld_indicator();
1484                 indicator_index = get_ag_indicator_index_for_name("callheld");
1485                 hfp_ag_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[indicator_index]);
1486             }
1487 
1488             // start audio if needed
1489             hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
1490             break;
1491         }
1492         case HFP_AG_OUTGOING_CALL_RINGING:
1493             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1494             if (!hfp_connection){
1495                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in dialing state");
1496                 break;
1497             }
1498 
1499             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_RINGING);
1500             hfp_connection->call_state = HFP_CALL_OUTGOING_RINGING;
1501             hfp_ag_set_callsetup_indicator();
1502             hfp_ag_transfer_callsetup_state();
1503             break;
1504 
1505         case HFP_AG_OUTGOING_CALL_ESTABLISHED:{
1506             // get outgoing call
1507             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_RINGING);
1508             if (!hfp_connection){
1509                 hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1510             }
1511             if (!hfp_connection){
1512                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection");
1513                 break;
1514             }
1515 
1516             int CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS = hfp_gsm_callheld_status() == HFP_CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS;
1517             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_ESTABLISHED);
1518             hfp_connection->call_state = HFP_CALL_ACTIVE;
1519             hfp_ag_set_callsetup_indicator();
1520             hfp_ag_set_call_indicator();
1521             hfp_ag_transfer_call_state();
1522             hfp_ag_transfer_callsetup_state();
1523             if (CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS){
1524                 hfp_ag_set_callheld_indicator();
1525                 hfp_ag_transfer_callheld_state();
1526             }
1527             break;
1528         }
1529 
1530         case HFP_AG_CALL_HOLD_USER_BUSY:
1531             hfp_gsm_handle_event(HFP_AG_CALL_HOLD_USER_BUSY);
1532             hfp_ag_set_callsetup_indicator();
1533             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1534             hfp_connection->call_state = HFP_CALL_ACTIVE;
1535             log_info("AG: Call Waiting, User Busy");
1536             break;
1537 
1538         case HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1539             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1540             int call_held = hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1541 
1542             // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1543             if (call_held || call_setup_in_progress){
1544                 hfp_gsm_handle_event_with_call_index(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index);
1545 
1546             }
1547 
1548             if (call_setup_in_progress){
1549                 log_info("AG: Call Dropped, Accept new call");
1550                 hfp_ag_set_callsetup_indicator();
1551                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1552             } else {
1553                 log_info("AG: Call Dropped, Resume held call");
1554             }
1555             if (call_held){
1556                 hfp_ag_set_callheld_indicator();
1557                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1558             }
1559 
1560             hfp_connection->call_state = HFP_CALL_ACTIVE;
1561             break;
1562         }
1563 
1564         case HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1565             // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1566             // only update if callsetup changed
1567             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1568             hfp_gsm_handle_event_with_call_index(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index);
1569 
1570             if (call_setup_in_progress){
1571                 log_info("AG: Call on Hold, Accept new call");
1572                 hfp_ag_set_callsetup_indicator();
1573                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1574             } else {
1575                 log_info("AG: Swap calls");
1576             }
1577 
1578             hfp_ag_set_callheld_indicator();
1579             // hfp_ag_set_callheld_state(HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED);
1580             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1581             hfp_connection->call_state = HFP_CALL_ACTIVE;
1582             break;
1583         }
1584 
1585         case HFP_AG_CALL_HOLD_ADD_HELD_CALL:
1586             // Adds a held call to the conversation.
1587             if (hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD){
1588                 log_info("AG: Join 3-way-call");
1589                 hfp_gsm_handle_event(HFP_AG_CALL_HOLD_ADD_HELD_CALL);
1590                 hfp_ag_set_callheld_indicator();
1591                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1592                 hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_CONFERENCE_CALL);
1593             }
1594             hfp_connection->call_state = HFP_CALL_ACTIVE;
1595             break;
1596         case HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS:
1597             // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer)
1598             hfp_gsm_handle_event(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS);
1599             log_info("AG: Transfer call -> Connect two calls and disconnect");
1600             hfp_ag_set_call_indicator();
1601             hfp_ag_set_callheld_indicator();
1602             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1603             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1604             hfp_connection->call_state = HFP_CALL_IDLE;
1605             break;
1606 
1607         default:
1608             break;
1609     }
1610 
1611 
1612 }
1613 
1614 
1615 static void hfp_ag_send_call_status(hfp_connection_t * hfp_connection, int call_index){
1616     hfp_gsm_call_t * active_call = hfp_gsm_call(call_index);
1617     if (!active_call) return;
1618 
1619     int idx = active_call->index;
1620     hfp_enhanced_call_dir_t dir = active_call->direction;
1621     hfp_enhanced_call_status_t status = active_call->enhanced_status;
1622     hfp_enhanced_call_mode_t mode = active_call->mode;
1623     hfp_enhanced_call_mpty_t mpty = active_call->mpty;
1624     uint8_t type = active_call->clip_type;
1625     char * number = active_call->clip_number;
1626 
1627     char buffer[100];
1628     // TODO: check length of a buffer, to fit the MTU
1629     int offset = snprintf(buffer, sizeof(buffer), "\r\n%s: %d,%d,%d,%d,%d", HFP_LIST_CURRENT_CALLS, idx, dir, status, mode, mpty);
1630     if (number){
1631         offset += snprintf(buffer+offset, sizeof(buffer)-offset, ", \"%s\",%u", number, type);
1632     }
1633     snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n");
1634     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,
1635        mode, mpty, type, number);
1636     send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1637 }
1638 
1639 static void hfp_run_for_context(hfp_connection_t *hfp_connection){
1640 
1641     log_info("hfp_run_for_context %p", hfp_connection);
1642 
1643     if (!hfp_connection) return;
1644 
1645     if (!hfp_connection->rfcomm_cid) return;
1646 
1647     if (!rfcomm_can_send_packet_now(hfp_connection->rfcomm_cid)) {
1648         log_info("hfp_run_for_context: request can send for 0x%02x", hfp_connection->rfcomm_cid);
1649         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1650         return;
1651     }
1652 
1653     if (hfp_connection->send_status_of_current_calls){
1654         hfp_connection->ok_pending = 0;
1655         if (hfp_connection->next_call_index < hfp_gsm_get_number_of_calls()){
1656             hfp_connection->next_call_index++;
1657             hfp_ag_send_call_status(hfp_connection, hfp_connection->next_call_index);
1658         } else {
1659             hfp_connection->next_call_index = 0;
1660             hfp_connection->ok_pending = 1;
1661             hfp_connection->send_status_of_current_calls = 0;
1662         }
1663         return;
1664     }
1665 
1666     if (hfp_connection->ag_notify_incoming_call_waiting){
1667         hfp_connection->ag_notify_incoming_call_waiting = 0;
1668         hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1669         return;
1670     }
1671 
1672     if (hfp_connection->command == HFP_CMD_UNKNOWN){
1673         hfp_connection->ok_pending = 0;
1674         hfp_connection->send_error = 0;
1675         hfp_connection->command = HFP_CMD_NONE;
1676         hfp_ag_error(hfp_connection->rfcomm_cid);
1677         return;
1678     }
1679 
1680     if (hfp_connection->send_error){
1681         hfp_connection->send_error = 0;
1682         hfp_connection->command = HFP_CMD_NONE;
1683         hfp_ag_error(hfp_connection->rfcomm_cid);
1684         return;
1685     }
1686 
1687     // note: before update AG indicators and ok_pending
1688     if (hfp_connection->send_response_and_hold_status){
1689         int status = hfp_connection->send_response_and_hold_status - 1;
1690         hfp_connection->send_response_and_hold_status = 0;
1691         hfp_ag_set_response_and_hold(hfp_connection->rfcomm_cid, status);
1692         return;
1693     }
1694 
1695     if (hfp_connection->ok_pending){
1696         hfp_connection->ok_pending = 0;
1697         hfp_connection->command = HFP_CMD_NONE;
1698         hfp_ag_ok(hfp_connection->rfcomm_cid);
1699         return;
1700     }
1701 
1702     // update AG indicators
1703     if (hfp_connection->ag_indicators_status_update_bitmap){
1704         int i;
1705         for (i=0;i<hfp_connection->ag_indicators_nr;i++){
1706             if (get_bit(hfp_connection->ag_indicators_status_update_bitmap, i)){
1707                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, i, 0);
1708                 if (!hfp_connection->enable_status_update_for_ag_indicators) {
1709                     log_info("+CMER:3,0,0,0 - not sending update for '%s'", hfp_ag_indicators[i].name);
1710                     break;
1711                 }
1712                 hfp_ag_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[i]);
1713                 return;
1714             }
1715         }
1716     }
1717 
1718     if (hfp_connection->ag_ring){
1719         hfp_connection->ag_ring = 0;
1720         hfp_connection->command = HFP_CMD_NONE;
1721         hfp_ag_ring(hfp_connection->rfcomm_cid);
1722         return;
1723     }
1724 
1725     if (hfp_connection->ag_send_clip){
1726         hfp_connection->ag_send_clip = 0;
1727         hfp_connection->command = HFP_CMD_NONE;
1728         hfp_ag_send_clip(hfp_connection->rfcomm_cid);
1729         return;
1730     }
1731 
1732     if (hfp_connection->send_phone_number_for_voice_tag){
1733         hfp_connection->send_phone_number_for_voice_tag = 0;
1734         hfp_connection->command = HFP_CMD_NONE;
1735         hfp_connection->ok_pending = 1;
1736         hfp_ag_send_phone_number_for_voice_tag_cmd(hfp_connection->rfcomm_cid);
1737         return;
1738     }
1739 
1740     if (hfp_connection->send_subscriber_number){
1741         if (hfp_connection->next_subscriber_number_to_send < subscriber_numbers_count){
1742             hfp_phone_number_t phone = subscriber_numbers[hfp_connection->next_subscriber_number_to_send++];
1743             hfp_send_subscriber_number_cmd(hfp_connection->rfcomm_cid, phone.type, phone.number);
1744         } else {
1745             hfp_connection->send_subscriber_number = 0;
1746             hfp_connection->next_subscriber_number_to_send = 0;
1747             hfp_ag_ok(hfp_connection->rfcomm_cid);
1748         }
1749         hfp_connection->command = HFP_CMD_NONE;
1750     }
1751 
1752     if (hfp_connection->send_microphone_gain){
1753         hfp_connection->send_microphone_gain = 0;
1754         hfp_connection->command = HFP_CMD_NONE;
1755         hfp_ag_set_microphone_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->microphone_gain);
1756         return;
1757     }
1758 
1759     if (hfp_connection->send_speaker_gain){
1760         hfp_connection->send_speaker_gain = 0;
1761         hfp_connection->command = HFP_CMD_NONE;
1762         hfp_ag_set_speaker_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->speaker_gain);
1763         return;
1764     }
1765 
1766     if (hfp_connection->send_ag_status_indicators){
1767         hfp_connection->send_ag_status_indicators = 0;
1768         hfp_ag_retrieve_indicators_status_cmd(hfp_connection->rfcomm_cid);
1769         return;
1770     }
1771 
1772     int done = hfp_ag_run_for_context_service_level_connection(hfp_connection);
1773     if (!done){
1774         done = hfp_ag_run_for_context_service_level_connection_queries(hfp_connection);
1775     }
1776 
1777     if (!done){
1778         done = call_setup_state_machine(hfp_connection);
1779     }
1780 
1781     if (!done){
1782         done = hfp_ag_run_for_audio_connection(hfp_connection);
1783     }
1784 
1785     if (hfp_connection->command == HFP_CMD_NONE && !done){
1786         // log_info("hfp_connection->command == HFP_CMD_NONE");
1787         switch(hfp_connection->state){
1788             case HFP_W2_DISCONNECT_RFCOMM:
1789                 hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED;
1790                 rfcomm_disconnect(hfp_connection->rfcomm_cid);
1791                 break;
1792             default:
1793                 break;
1794         }
1795     }
1796     if (done){
1797         hfp_connection->command = HFP_CMD_NONE;
1798     }
1799     //
1800     if (done) {
1801         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1802     }
1803 }
1804 
1805 static hfp_generic_status_indicator_t *get_hf_indicator_by_number(int number){
1806     int i;
1807     for (i=0;i< hfp_generic_status_indicators_nr;i++){
1808         hfp_generic_status_indicator_t * indicator = &hfp_generic_status_indicators[i];
1809         if (indicator->uuid == number){
1810             return indicator;
1811         }
1812     }
1813     return NULL;
1814 }
1815 
1816 static void hfp_handle_rfcomm_data(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1817     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_rfcomm_cid(channel);
1818     if (!hfp_connection) return;
1819 
1820     char last_char = packet[size-1];
1821     packet[size-1] = 0;
1822     log_info("HFP_RX %s", packet);
1823     packet[size-1] = last_char;
1824 
1825     int pos;
1826     for (pos = 0; pos < size ; pos++){
1827         hfp_parse(hfp_connection, packet[pos], 0);
1828     }
1829     hfp_generic_status_indicator_t * indicator;
1830     int value;
1831     switch(hfp_connection->command){
1832         case HFP_CMD_RESPONSE_AND_HOLD_QUERY:
1833             if (hfp_ag_response_and_hold_active){
1834                 hfp_connection->send_response_and_hold_status = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD + 1;
1835             }
1836             hfp_connection->ok_pending = 1;
1837             break;
1838         case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1839             value = atoi((char *)&hfp_connection->line_buffer[0]);
1840             log_info("HF Response and Hold: %u", value);
1841             switch(value){
1842                 case HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD:
1843                     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, hfp_connection);
1844                     break;
1845                 case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED:
1846                     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF, hfp_connection);
1847                     break;
1848                 case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED:
1849                     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF, hfp_connection);
1850                     break;
1851                 default:
1852                     break;
1853             }
1854             hfp_connection->ok_pending = 1;
1855             break;
1856         case HFP_CMD_HF_INDICATOR_STATUS:
1857             hfp_connection->command = HFP_CMD_NONE;
1858             // find indicator by assigned number
1859             indicator = get_hf_indicator_by_number(hfp_connection->parser_indicator_index);
1860             if (!indicator){
1861                 hfp_connection->send_error = 1;
1862                 break;
1863             }
1864             value = atoi((char *)&hfp_connection->line_buffer[0]);
1865             switch (indicator->uuid){
1866                 case 1: // enhanced security
1867                     if (value > 1) {
1868                         hfp_connection->send_error = 1;
1869                         return;
1870                     }
1871                     log_info("HF Indicator 'enhanced security' set to %u", value);
1872                     break;
1873                 case 2: // battery level
1874                     if (value > 100){
1875                         hfp_connection->send_error = 1;
1876                         return;
1877                     }
1878                     log_info("HF Indicator 'battery' set to %u", value);
1879                     break;
1880                 default:
1881                     log_info("HF Indicator unknown set to %u", value);
1882                     break;
1883             }
1884             hfp_connection->ok_pending = 1;
1885             break;
1886         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1887             // expected by SLC state machine
1888             if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) break;
1889             hfp_connection->send_ag_indicators_segment = 0;
1890             hfp_connection->send_ag_status_indicators = 1;
1891             break;
1892         case HFP_CMD_LIST_CURRENT_CALLS:
1893             hfp_connection->command = HFP_CMD_NONE;
1894             hfp_connection->next_call_index = 0;
1895             hfp_connection->send_status_of_current_calls = 1;
1896             break;
1897         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1898             if (subscriber_numbers_count == 0){
1899                 hfp_ag_ok(hfp_connection->rfcomm_cid);
1900                 break;
1901             }
1902             hfp_connection->next_subscriber_number_to_send = 0;
1903             hfp_connection->send_subscriber_number = 1;
1904             break;
1905         case HFP_CMD_TRANSMIT_DTMF_CODES:
1906             hfp_connection->command = HFP_CMD_NONE;
1907             hfp_emit_string_event(hfp_callback, HFP_SUBEVENT_TRANSMIT_DTMF_CODES, (const char *) &hfp_connection->line_buffer[0]);
1908             break;
1909         case HFP_CMD_HF_REQUEST_PHONE_NUMBER:
1910             hfp_connection->command = HFP_CMD_NONE;
1911             hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_ATTACH_NUMBER_TO_VOICE_TAG);
1912             break;
1913         case HFP_CMD_TURN_OFF_EC_AND_NR:
1914             hfp_connection->command = HFP_CMD_NONE;
1915             if (get_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION)){
1916                 hfp_connection->ok_pending = 1;
1917                 hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION, hfp_connection->ag_echo_and_noise_reduction);
1918                 log_info("AG: EC/NR = %u", hfp_connection->ag_echo_and_noise_reduction);
1919             } else {
1920                 hfp_connection->send_error = 1;
1921             }
1922             break;
1923         case HFP_CMD_CALL_ANSWERED:
1924             hfp_connection->command = HFP_CMD_NONE;
1925             log_info("HFP: ATA");
1926             hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, hfp_connection);
1927             break;
1928         case HFP_CMD_HANG_UP_CALL:
1929             hfp_connection->command = HFP_CMD_NONE;
1930             hfp_connection->ok_pending = 1;
1931             hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_HF, hfp_connection);
1932             break;
1933         case HFP_CMD_CALL_HOLD: {
1934             // TODO: fully implement this
1935             log_error("HFP: unhandled call hold type %c", hfp_connection->line_buffer[0]);
1936             hfp_connection->command = HFP_CMD_NONE;
1937             hfp_connection->ok_pending = 1;
1938             hfp_connection->call_index = 0;
1939 
1940             if (hfp_connection->line_buffer[1] != '\0'){
1941                 hfp_connection->call_index = atoi((char *)&hfp_connection->line_buffer[1]);
1942             }
1943 
1944             switch (hfp_connection->line_buffer[0]){
1945                 case '0':
1946                     // Releases all held calls or sets User Determined User Busy (UDUB) for a waiting call.
1947                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_USER_BUSY, hfp_connection);
1948                     break;
1949                 case '1':
1950                     // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1951                     // Where both a held and a waiting call exist, the above procedures shall apply to the
1952                     // waiting call (i.e., not to the held call) in conflicting situation.
1953                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
1954                     break;
1955                 case '2':
1956                     // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1957                     // Where both a held and a waiting call exist, the above procedures shall apply to the
1958                     // waiting call (i.e., not to the held call) in conflicting situation.
1959                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
1960                     break;
1961                 case '3':
1962                     // Adds a held call to the conversation.
1963                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_ADD_HELD_CALL, hfp_connection);
1964                     break;
1965                 case '4':
1966                     // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer).
1967                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, hfp_connection);
1968                     break;
1969                 default:
1970                     break;
1971             }
1972             break;
1973         }
1974         case HFP_CMD_CALL_PHONE_NUMBER:
1975             hfp_connection->command = HFP_CMD_NONE;
1976             hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED, hfp_connection);
1977             break;
1978         case HFP_CMD_REDIAL_LAST_NUMBER:
1979             hfp_connection->command = HFP_CMD_NONE;
1980             hfp_ag_call_sm(HFP_AG_OUTGOING_REDIAL_INITIATED, hfp_connection);
1981             break;
1982         case HFP_CMD_ENABLE_CLIP:
1983             hfp_connection->command = HFP_CMD_NONE;
1984             hfp_connection->clip_enabled = hfp_connection->line_buffer[8] != '0';
1985             log_info("hfp: clip set, now: %u", hfp_connection->clip_enabled);
1986             hfp_connection->ok_pending = 1;
1987             break;
1988         case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1989             hfp_connection->command = HFP_CMD_NONE;
1990             hfp_connection->call_waiting_notification_enabled = hfp_connection->line_buffer[8] != '0';
1991             log_info("hfp: call waiting notification set, now: %u", hfp_connection->call_waiting_notification_enabled);
1992             hfp_connection->ok_pending = 1;
1993             break;
1994         case HFP_CMD_SET_SPEAKER_GAIN:
1995             hfp_connection->command = HFP_CMD_NONE;
1996             hfp_connection->ok_pending = 1;
1997             log_info("HF speaker gain = %u", hfp_connection->speaker_gain);
1998             break;
1999         case HFP_CMD_SET_MICROPHONE_GAIN:
2000             hfp_connection->command = HFP_CMD_NONE;
2001             hfp_connection->ok_pending = 1;
2002             log_info("HF microphone gain = %u", hfp_connection->microphone_gain);
2003             break;
2004         default:
2005             break;
2006     }
2007 }
2008 
2009 static void hfp_run(void){
2010     btstack_linked_list_iterator_t it;
2011     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2012     while (btstack_linked_list_iterator_has_next(&it)){
2013         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2014         hfp_run_for_context(hfp_connection);
2015     }
2016 }
2017 
2018 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2019     switch (packet_type){
2020         case RFCOMM_DATA_PACKET:
2021             hfp_handle_rfcomm_data(packet_type, channel, packet, size);
2022             break;
2023         case HCI_EVENT_PACKET:
2024             if (packet[0] == RFCOMM_EVENT_CAN_SEND_NOW){
2025                 uint16_t rfcomm_cid = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
2026                 hfp_run_for_context(get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid));
2027                 return;
2028             }
2029             hfp_handle_hci_event(packet_type, channel, packet, size);
2030             break;
2031         default:
2032             break;
2033     }
2034 
2035     hfp_run();
2036 }
2037 
2038 
2039 void hfp_ag_init_codecs(int codecs_nr, uint8_t * codecs){
2040     if (codecs_nr > HFP_MAX_NUM_CODECS){
2041         log_error("hfp_init: codecs_nr (%d) > HFP_MAX_NUM_CODECS (%d)", codecs_nr, HFP_MAX_NUM_CODECS);
2042         return;
2043     }
2044     int i;
2045     hfp_codecs_nr = codecs_nr;
2046     for (i=0; i < codecs_nr; i++){
2047         hfp_codecs[i] = codecs[i];
2048     }
2049 }
2050 
2051 void hfp_ag_init_supported_features(uint32_t supported_features){
2052     hfp_supported_features = supported_features;
2053 }
2054 
2055 void hfp_ag_init_ag_indicators(int ag_indicators_nr, hfp_ag_indicator_t * ag_indicators){
2056     hfp_ag_indicators_nr = ag_indicators_nr;
2057     memcpy(hfp_ag_indicators, ag_indicators, ag_indicators_nr * sizeof(hfp_ag_indicator_t));
2058 }
2059 
2060 void hfp_ag_init_hf_indicators(int hf_indicators_nr, hfp_generic_status_indicator_t * hf_indicators){
2061     if (hf_indicators_nr > HFP_MAX_NUM_HF_INDICATORS) return;
2062     hfp_generic_status_indicators_nr = hf_indicators_nr;
2063     memcpy(hfp_generic_status_indicators, hf_indicators, hf_indicators_nr * sizeof(hfp_generic_status_indicator_t));
2064 }
2065 
2066 void hfp_ag_init_call_hold_services(int call_hold_services_nr, const char * call_hold_services[]){
2067     hfp_ag_call_hold_services_nr = call_hold_services_nr;
2068     memcpy(hfp_ag_call_hold_services, call_hold_services, call_hold_services_nr * sizeof(char *));
2069 }
2070 
2071 
2072 void hfp_ag_init(uint16_t rfcomm_channel_nr){
2073     // register for HCI events
2074     hci_event_callback_registration.callback = &packet_handler;
2075     hci_add_event_handler(&hci_event_callback_registration);
2076 
2077     rfcomm_register_service(&packet_handler, rfcomm_channel_nr, 0xffff);
2078 
2079     hfp_ag_response_and_hold_active = 0;
2080     subscriber_numbers = NULL;
2081     subscriber_numbers_count = 0;
2082 
2083     hfp_set_packet_handler_for_rfcomm_connections(&packet_handler);
2084 
2085     hfp_gsm_init();
2086 }
2087 
2088 void hfp_ag_establish_service_level_connection(bd_addr_t bd_addr){
2089     hfp_establish_service_level_connection(bd_addr, SDP_Handsfree);
2090 }
2091 
2092 void hfp_ag_release_service_level_connection(hci_con_handle_t acl_handle){
2093     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2094     if (!hfp_connection){
2095         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2096         return;
2097     }
2098     hfp_release_service_level_connection(hfp_connection);
2099     hfp_run_for_context(hfp_connection);
2100 }
2101 
2102 void hfp_ag_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle, hfp_cme_error_t error){
2103     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2104     if (!hfp_connection){
2105         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2106         return;
2107     }
2108     hfp_connection->extended_audio_gateway_error = 0;
2109     if (!hfp_connection->enable_extended_audio_gateway_error_report){
2110         return;
2111     }
2112     hfp_connection->extended_audio_gateway_error = error;
2113     hfp_run_for_context(hfp_connection);
2114 }
2115 
2116 static void hfp_ag_setup_audio_connection(hfp_connection_t * hfp_connection){
2117     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return;
2118     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
2119 
2120     hfp_connection->establish_audio_connection = 1;
2121 
2122     if (!has_codec_negotiation_feature(hfp_connection)){
2123         log_info("hfp_ag_establish_audio_connection - no codec negotiation feature, using CVSD");
2124         hfp_connection->negotiated_codec = HFP_CODEC_CVSD;
2125         hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
2126         // now, pick link settings
2127         hfp_init_link_settings(hfp_connection);
2128     }
2129 
2130     switch (hfp_connection->codecs_state){
2131         case HFP_CODECS_IDLE:
2132         case HFP_CODECS_RECEIVED_LIST:
2133         case HFP_CODECS_AG_RESEND_COMMON_CODEC:
2134         case HFP_CODECS_ERROR:
2135             hfp_connection->command = HFP_CMD_AG_SEND_COMMON_CODEC;
2136             break;
2137         default:
2138             break;
2139     }
2140 }
2141 
2142 void hfp_ag_establish_audio_connection(hci_con_handle_t acl_handle){
2143     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2144     if (!hfp_connection){
2145         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2146         return;
2147     }
2148     hfp_connection->establish_audio_connection = 0;
2149     hfp_ag_setup_audio_connection(hfp_connection);
2150     hfp_run_for_context(hfp_connection);
2151 }
2152 
2153 void hfp_ag_release_audio_connection(hci_con_handle_t acl_handle){
2154     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2155     if (!hfp_connection){
2156         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2157         return;
2158     }
2159     hfp_release_audio_connection(hfp_connection);
2160     hfp_run_for_context(hfp_connection);
2161 }
2162 
2163 /**
2164  * @brief Enable in-band ring tone
2165  */
2166 void hfp_ag_set_use_in_band_ring_tone(int use_in_band_ring_tone){
2167     if (get_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE) == use_in_band_ring_tone){
2168         return;
2169     }
2170     hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE, use_in_band_ring_tone);
2171 
2172     btstack_linked_list_iterator_t it;
2173     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2174     while (btstack_linked_list_iterator_has_next(&it)){
2175         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2176         hfp_connection->command = HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING;
2177         hfp_run_for_context(hfp_connection);
2178     }
2179 }
2180 
2181 /**
2182  * @brief Called from GSM
2183  */
2184 void hfp_ag_incoming_call(void){
2185     hfp_ag_call_sm(HFP_AG_INCOMING_CALL, NULL);
2186 }
2187 
2188 /**
2189  * @brief number is stored.
2190  */
2191 void hfp_ag_set_clip(uint8_t type, const char * number){
2192     hfp_gsm_handle_event_with_clip(HFP_AG_SET_CLIP, type, number);
2193 }
2194 
2195 void hfp_ag_call_dropped(void){
2196     hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2197 }
2198 
2199 // call from AG UI
2200 void hfp_ag_answer_incoming_call(void){
2201     hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, NULL);
2202 }
2203 
2204 void hfp_ag_join_held_call(void){
2205     hfp_ag_call_sm(HFP_AG_HELD_CALL_JOINED_BY_AG, NULL);
2206 }
2207 
2208 void hfp_ag_terminate_call(void){
2209     hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_AG, NULL);
2210 }
2211 
2212 void hfp_ag_outgoing_call_ringing(void){
2213     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_RINGING, NULL);
2214 }
2215 
2216 void hfp_ag_outgoing_call_established(void){
2217     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ESTABLISHED, NULL);
2218 }
2219 
2220 void hfp_ag_outgoing_call_rejected(void){
2221     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_REJECTED, NULL);
2222 }
2223 
2224 void hfp_ag_outgoing_call_accepted(void){
2225     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ACCEPTED, NULL);
2226 }
2227 
2228 void hfp_ag_hold_incoming_call(void){
2229     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, NULL);
2230 }
2231 
2232 void hfp_ag_accept_held_incoming_call(void) {
2233     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, NULL);
2234 }
2235 
2236 void hfp_ag_reject_held_incoming_call(void){
2237     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, NULL);
2238 }
2239 
2240 static void hfp_ag_set_ag_indicator(const char * name, int value){
2241     int indicator_index = get_ag_indicator_index_for_name(name);
2242     if (indicator_index < 0) return;
2243     hfp_ag_indicators[indicator_index].status = value;
2244 
2245 
2246     btstack_linked_list_iterator_t it;
2247     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2248     while (btstack_linked_list_iterator_has_next(&it)){
2249         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2250         if (! hfp_connection->ag_indicators[indicator_index].enabled) {
2251             log_info("AG indicator '%s' changed to %u but not enabled", hfp_ag_indicators[indicator_index].name, value);
2252             continue;
2253         }
2254         log_info("AG indicator '%s' changed to %u, request transfer statur", hfp_ag_indicators[indicator_index].name, value);
2255         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
2256         hfp_run_for_context(hfp_connection);
2257     }
2258 }
2259 
2260 void hfp_ag_set_registration_status(int status){
2261     hfp_ag_set_ag_indicator("service", status);
2262 }
2263 
2264 void hfp_ag_set_signal_strength(int strength){
2265     hfp_ag_set_ag_indicator("signal", strength);
2266 }
2267 
2268 void hfp_ag_set_roaming_status(int status){
2269     hfp_ag_set_ag_indicator("roam", status);
2270 }
2271 
2272 void hfp_ag_set_battery_level(int level){
2273     hfp_ag_set_ag_indicator("battchg", level);
2274 }
2275 
2276 void hfp_ag_activate_voice_recognition(hci_con_handle_t acl_handle, int activate){
2277     if (!get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)) return;
2278     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2279     if (!hfp_connection){
2280         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2281         return;
2282     }
2283 
2284     if (!get_bit(hfp_connection->remote_supported_features, HFP_HFSF_VOICE_RECOGNITION_FUNCTION)) {
2285         log_info("AG cannot acivate voice recognition - not supported by HF");
2286         return;
2287     }
2288 
2289     if (activate){
2290         hfp_ag_establish_audio_connection(acl_handle);
2291     }
2292 
2293     hfp_connection->ag_activate_voice_recognition = activate;
2294     hfp_connection->command = HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
2295     hfp_run_for_context(hfp_connection);
2296 }
2297 
2298 void hfp_ag_set_microphone_gain(hci_con_handle_t acl_handle, int gain){
2299     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2300     if (!hfp_connection){
2301         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2302         return;
2303     }
2304     if (hfp_connection->microphone_gain != gain){
2305         hfp_connection->command = HFP_CMD_SET_MICROPHONE_GAIN;
2306         hfp_connection->microphone_gain = gain;
2307         hfp_connection->send_microphone_gain = 1;
2308     }
2309     hfp_run_for_context(hfp_connection);
2310 }
2311 
2312 void hfp_ag_set_speaker_gain(hci_con_handle_t acl_handle, int gain){
2313     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2314     if (!hfp_connection){
2315         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2316         return;
2317     }
2318     if (hfp_connection->speaker_gain != gain){
2319         hfp_connection->speaker_gain = gain;
2320         hfp_connection->send_speaker_gain = 1;
2321     }
2322     hfp_run_for_context(hfp_connection);
2323 }
2324 
2325 void hfp_ag_send_phone_number_for_voice_tag(hci_con_handle_t acl_handle, const char * number){
2326     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2327     if (!hfp_connection){
2328         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2329         return;
2330     }
2331     hfp_ag_set_clip(0, number);
2332     hfp_connection->send_phone_number_for_voice_tag = 1;
2333 }
2334 
2335 void hfp_ag_reject_phone_number_for_voice_tag(hci_con_handle_t acl_handle){
2336     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2337     if (!hfp_connection){
2338         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2339         return;
2340     }
2341     hfp_connection->send_error = 1;
2342 }
2343 
2344 void hfp_ag_send_dtmf_code_done(hci_con_handle_t acl_handle){
2345     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2346     if (!hfp_connection){
2347         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2348         return;
2349     }
2350     hfp_connection->ok_pending = 1;
2351 }
2352 
2353 void hfp_ag_set_subcriber_number_information(hfp_phone_number_t * numbers, int numbers_count){
2354     subscriber_numbers = numbers;
2355     subscriber_numbers_count = numbers_count;
2356 }
2357 
2358 void hfp_ag_clear_last_dialed_number(void){
2359     hfp_gsm_clear_last_dialed_number();
2360 }
2361 
2362 void hfp_ag_notify_incoming_call_waiting(hci_con_handle_t acl_handle){
2363     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2364     if (!hfp_connection){
2365         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2366         return;
2367     }
2368     if (!hfp_connection->call_waiting_notification_enabled) return;
2369 
2370     hfp_connection->ag_notify_incoming_call_waiting = 1;
2371     hfp_run_for_context(hfp_connection);
2372 }
2373 
2374