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