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