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