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