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