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