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