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