xref: /btstack/src/classic/hfp_ag.c (revision 9a00f11b52763b83d0b957aa841174fb10792657)
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 BLUEKITCHEN
24  * GMBH 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 #define BTSTACK_FILE__ "hfp_ag.c"
39 
40 // *****************************************************************************
41 //
42 // HFP Audio Gateway (AG) unit
43 //
44 // *****************************************************************************
45 
46 #include "btstack_config.h"
47 
48 #include <stdint.h>
49 #include <stdio.h>
50 #include <string.h>
51 
52 #include "hci_cmd.h"
53 #include "btstack_run_loop.h"
54 
55 #include "bluetooth_sdp.h"
56 #include "hci.h"
57 #include "btstack_memory.h"
58 #include "hci_dump.h"
59 #include "l2cap.h"
60 #include "btstack_debug.h"
61 #include "btstack_event.h"
62 #include "classic/core.h"
63 #include "classic/hfp.h"
64 #include "classic/hfp_ag.h"
65 #include "classic/hfp_gsm_model.h"
66 #include "classic/sdp_client_rfcomm.h"
67 #include "classic/sdp_server.h"
68 #include "classic/sdp_util.h"
69 
70 // private prototypes
71 static void hfp_ag_run_for_context(hfp_connection_t *hfp_connection);
72 static void hfp_ag_hf_start_ringing_incoming(hfp_connection_t * hfp_connection);
73 static void hfp_ag_hf_start_ringing_outgoing(hfp_connection_t * hfp_connection);
74 static uint8_t hfp_ag_setup_audio_connection(hfp_connection_t * hfp_connection);
75 
76 // public prototypes
77 hfp_generic_status_indicator_t * get_hfp_generic_status_indicators(void);
78 int get_hfp_generic_status_indicators_nr(void);
79 void set_hfp_generic_status_indicators(hfp_generic_status_indicator_t * indicators, int indicator_nr);
80 void set_hfp_ag_indicators(hfp_ag_indicator_t * indicators, int indicator_nr);
81 int get_hfp_ag_indicators_nr(hfp_connection_t * context);
82 hfp_ag_indicator_t * get_hfp_ag_indicators(hfp_connection_t * context);
83 
84 #define HFP_SUBEVENT_INVALID 0xFFFF
85 
86 // const
87 static const char hfp_ag_default_service_name[] = "Voice gateway";
88 
89 // globals
90 
91 // higher layer callbacks
92 static btstack_packet_handler_t hfp_ag_callback;
93 
94 static bool (*hfp_ag_custom_call_sm_handler)(hfp_ag_call_event_t event);
95 
96 static btstack_packet_callback_registration_t hfp_ag_hci_event_callback_registration;
97 
98 static uint16_t hfp_ag_supported_features;
99 
100 // codecs
101 static uint8_t hfp_ag_codecs_nr;
102 static uint8_t hfp_ag_codecs[HFP_MAX_NUM_CODECS];
103 
104 // AG indicators
105 static int                hfp_ag_indicators_nr;
106 static hfp_ag_indicator_t hfp_ag_indicators[HFP_MAX_NUM_INDICATORS];
107 
108 // generic status indicators
109 static int                            hfp_ag_generic_status_indicators_nr;
110 static hfp_generic_status_indicator_t hfp_ag_generic_status_indicators[HFP_MAX_NUM_INDICATORS];
111 
112 static int    hfp_ag_call_hold_services_nr;
113 static char * hfp_ag_call_hold_services[6];
114 
115 static hfp_response_and_hold_state_t hfp_ag_response_and_hold_state;
116 static bool hfp_ag_response_and_hold_active = false;
117 
118 // Subscriber information entries
119 static hfp_phone_number_t * hfp_ag_subscriber_numbers;
120 static int                  hfp_ag_subscriber_numbers_count;
121 
122 // call state
123 static btstack_timer_source_t hfp_ag_ring_timeout;
124 
125 // code
126 static int hfp_ag_get_ag_indicators_nr(hfp_connection_t * hfp_connection){
127     if (hfp_connection->ag_indicators_nr != hfp_ag_indicators_nr){
128         hfp_connection->ag_indicators_nr = hfp_ag_indicators_nr;
129         (void)memcpy(hfp_connection->ag_indicators, hfp_ag_indicators,
130                      hfp_ag_indicators_nr * sizeof(hfp_ag_indicator_t));
131     }
132     return hfp_connection->ag_indicators_nr;
133 }
134 
135 hfp_ag_indicator_t * hfp_ag_get_ag_indicators(hfp_connection_t * hfp_connection){
136     // TODO: save only value, and value changed in the hfp_connection?
137     if (hfp_connection->ag_indicators_nr != hfp_ag_indicators_nr){
138         hfp_connection->ag_indicators_nr = hfp_ag_indicators_nr;
139         (void)memcpy(hfp_connection->ag_indicators, hfp_ag_indicators,
140                      hfp_ag_indicators_nr * sizeof(hfp_ag_indicator_t));
141     }
142     return (hfp_ag_indicator_t *)&(hfp_connection->ag_indicators);
143 }
144 
145 static hfp_ag_indicator_t * get_ag_indicator_for_name(const char * name){
146     int i;
147     for (i = 0; i < hfp_ag_indicators_nr; i++){
148         if (strcmp(hfp_ag_indicators[i].name, name) == 0){
149             return &hfp_ag_indicators[i];
150         }
151     }
152     return NULL;
153 }
154 
155 static int get_ag_indicator_index_for_name(const char * name){
156     int i;
157     for (i = 0; i < hfp_ag_indicators_nr; i++){
158         if (strcmp(hfp_ag_indicators[i].name, name) == 0){
159             return i;
160         }
161     }
162     return -1;
163 }
164 
165 static hfp_connection_t * get_hfp_ag_connection_context_for_acl_handle(uint16_t handle){
166     btstack_linked_list_iterator_t it;
167     btstack_linked_list_iterator_init(&it, hfp_get_connections());
168     while (btstack_linked_list_iterator_has_next(&it)){
169         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
170         if (hfp_connection->acl_handle != handle)      continue;
171         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
172         return hfp_connection;
173     }
174     return NULL;
175 }
176 
177 static int use_in_band_tone(void){
178     return get_bit(hfp_ag_supported_features, HFP_AGSF_IN_BAND_RING_TONE);
179 }
180 
181 static int has_codec_negotiation_feature(hfp_connection_t * hfp_connection){
182     int hf = get_bit(hfp_connection->remote_supported_features, HFP_HFSF_CODEC_NEGOTIATION);
183     int ag = get_bit(hfp_ag_supported_features, HFP_AGSF_CODEC_NEGOTIATION);
184     return hf && ag;
185 }
186 
187 static int has_call_waiting_and_3way_calling_feature(hfp_connection_t * hfp_connection){
188     int hf = get_bit(hfp_connection->remote_supported_features, HFP_HFSF_THREE_WAY_CALLING);
189     int ag = get_bit(hfp_ag_supported_features, HFP_AGSF_THREE_WAY_CALLING);
190     return hf && ag;
191 }
192 
193 static int has_hf_indicators_feature(hfp_connection_t * hfp_connection){
194     int hf = get_bit(hfp_connection->remote_supported_features, HFP_HFSF_HF_INDICATORS);
195     int ag = get_bit(hfp_ag_supported_features, HFP_AGSF_HF_INDICATORS);
196     return hf && ag;
197 }
198 
199 /* unsolicited responses */
200 
201 static int hfp_ag_send_change_in_band_ring_tone_setting_cmd(uint16_t cid){
202     char buffer[20];
203     snprintf(buffer, sizeof(buffer), "\r\n%s: %d\r\n",
204              HFP_CHANGE_IN_BAND_RING_TONE_SETTING, use_in_band_tone());
205     buffer[sizeof(buffer) - 1] = 0;
206     return send_str_over_rfcomm(cid, buffer);
207 }
208 
209 static int hfp_ag_exchange_supported_features_cmd(uint16_t cid){
210     char buffer[40];
211     snprintf(buffer, sizeof(buffer), "\r\n%s:%d\r\n\r\nOK\r\n",
212              HFP_SUPPORTED_FEATURES, hfp_ag_supported_features);
213     buffer[sizeof(buffer) - 1] = 0;
214     return send_str_over_rfcomm(cid, buffer);
215 }
216 
217 static int hfp_ag_send_ok(uint16_t cid){
218     char buffer[10];
219     snprintf(buffer, sizeof(buffer), "\r\nOK\r\n");
220     buffer[sizeof(buffer) - 1] = 0;
221     return send_str_over_rfcomm(cid, buffer);
222 }
223 
224 static int hfp_ag_send_ring(uint16_t cid){
225     return send_str_over_rfcomm(cid, (char *) "\r\nRING\r\n");
226 }
227 
228 static int hfp_ag_send_no_carrier(uint16_t cid){
229     char buffer[15];
230     snprintf(buffer, sizeof(buffer), "\r\nNO CARRIER\r\n");
231     buffer[sizeof(buffer) - 1] = 0;
232     return send_str_over_rfcomm(cid, buffer);
233 }
234 
235 static int hfp_ag_send_clip(uint16_t cid){
236     char buffer[50];
237     snprintf(buffer, sizeof(buffer), "\r\n%s: \"%s\",%u\r\n", HFP_ENABLE_CLIP,
238              hfp_gsm_clip_number(), hfp_gsm_clip_type());
239     buffer[sizeof(buffer) - 1] = 0;
240     return send_str_over_rfcomm(cid, buffer);
241 }
242 
243 static int hfp_send_subscriber_number_cmd(uint16_t cid, uint8_t type, const char * number){
244     char buffer[50];
245     snprintf(buffer, sizeof(buffer), "\r\n%s: ,\"%s\",%u, , \r\n",
246              HFP_SUBSCRIBER_NUMBER_INFORMATION, number, type);
247     buffer[sizeof(buffer) - 1] = 0;
248     return send_str_over_rfcomm(cid, buffer);
249 }
250 
251 static int hfp_ag_send_phone_number_for_voice_tag_cmd(uint16_t cid){
252     char buffer[50];
253     snprintf(buffer, sizeof(buffer), "\r\n%s: %s\r\n",
254              HFP_PHONE_NUMBER_FOR_VOICE_TAG, hfp_gsm_clip_number());
255     buffer[sizeof(buffer) - 1] = 0;
256     return send_str_over_rfcomm(cid, buffer);
257 }
258 
259 static int hfp_ag_send_call_waiting_notification(uint16_t cid){
260     char buffer[50];
261     snprintf(buffer, sizeof(buffer), "\r\n%s: \"%s\",%u\r\n",
262              HFP_ENABLE_CALL_WAITING_NOTIFICATION, hfp_gsm_clip_number(),
263              hfp_gsm_clip_type());
264     buffer[sizeof(buffer) - 1] = 0;
265     return send_str_over_rfcomm(cid, buffer);
266 }
267 
268 static int hfp_ag_send_error(uint16_t cid){
269     char buffer[10];
270     snprintf(buffer, sizeof(buffer), "\r\nERROR\r\n");
271     buffer[sizeof(buffer) - 1] = 0;
272     return send_str_over_rfcomm(cid, buffer);
273 }
274 
275 static int hfp_ag_send_report_extended_audio_gateway_error(uint16_t cid, uint8_t error){
276     char buffer[20];
277     snprintf(buffer, sizeof(buffer), "\r\n%s=%d\r\n",
278              HFP_EXTENDED_AUDIO_GATEWAY_ERROR, error);
279     buffer[sizeof(buffer) - 1] = 0;
280     return send_str_over_rfcomm(cid, buffer);
281 }
282 
283 // get size for indicator string
284 static int hfp_ag_indicators_string_size(hfp_connection_t * hfp_connection, int i){
285     // template: ("$NAME",($MIN,$MAX))
286     return 8 + (int) strlen(hfp_ag_get_ag_indicators(hfp_connection)[i].name)
287          + string_len_for_uint32(hfp_ag_get_ag_indicators(hfp_connection)[i].min_range)
288          + string_len_for_uint32(hfp_ag_get_ag_indicators(hfp_connection)[i].min_range);
289 }
290 
291 // store indicator
292 static void hfp_ag_indicators_string_store(hfp_connection_t * hfp_connection, int i, uint8_t * buffer, uint16_t buffer_size){
293     snprintf((char *)buffer, buffer_size, "(\"%s\",(%d,%d)),",
294              hfp_ag_get_ag_indicators(hfp_connection)[i].name,
295              hfp_ag_get_ag_indicators(hfp_connection)[i].min_range,
296              hfp_ag_get_ag_indicators(hfp_connection)[i].max_range);
297     ((char *)buffer)[buffer_size - 1] = 0;
298 }
299 
300 // structure: header [indicator [comma indicator]] footer
301 static int hfp_ag_indicators_cmd_generator_num_segments(hfp_connection_t * hfp_connection){
302     int num_indicators = hfp_ag_get_ag_indicators_nr(hfp_connection);
303     if (!num_indicators) return 2;
304     return 3 + ((num_indicators-1) * 2);
305 }
306 
307 // get size of individual segment for hfp_ag_retrieve_indicators_cmd
308 static int hfp_ag_indicators_cmd_generator_get_segment_len(hfp_connection_t * hfp_connection, int index){
309     if (index == 0) {
310         return strlen(HFP_INDICATOR) + 3;   // "\n\r%s:""
311     }
312     index--;
313     int num_indicators = hfp_ag_get_ag_indicators_nr(hfp_connection);
314     int indicator_index = index >> 1;
315     if ((index & 1) == 0){
316         return hfp_ag_indicators_string_size(hfp_connection, indicator_index);
317     }
318     if (indicator_index == (num_indicators - 1)){
319         return 8; // "\r\n\r\nOK\r\n"
320     }
321     return 1; // comma
322 }
323 
324 static void hfp_ag_indicators_cmd_generator_store_segment(hfp_connection_t * hfp_connection, int index, uint8_t * buffer, uint16_t buffer_size){
325     if (index == 0){
326         *buffer++ = '\r';
327         *buffer++ = '\n';
328         int len = strlen(HFP_INDICATOR);
329         (void)memcpy(buffer, HFP_INDICATOR, len);
330         buffer += len;
331         *buffer++ = ':';
332         return;
333     }
334     index--;
335     int num_indicators = hfp_ag_get_ag_indicators_nr(hfp_connection);
336     int indicator_index = index >> 1;
337     if ((index & 1) == 0){
338         hfp_ag_indicators_string_store(hfp_connection, indicator_index, buffer, buffer_size);
339         return;
340     }
341     if (indicator_index == (num_indicators-1)){
342         (void)memcpy(buffer, "\r\n\r\nOK\r\n", 8);
343         return;
344     }
345     *buffer = ',';
346 }
347 
348 static int hfp_ag_generic_indicators_join(char * buffer, int buffer_size){
349     if (buffer_size < (hfp_ag_indicators_nr * 3)) return 0;
350     int i;
351     int offset = 0;
352     for (i = 0; i < (hfp_ag_generic_status_indicators_nr - 1); i++) {
353         offset += snprintf(buffer+offset, buffer_size-offset, "%d,", hfp_ag_generic_status_indicators[i].uuid);
354     }
355     if (i < hfp_ag_generic_status_indicators_nr){
356         offset += snprintf(buffer+offset, buffer_size-offset, "%d", hfp_ag_generic_status_indicators[i].uuid);
357     }
358     return offset;
359 }
360 
361 static int hfp_ag_generic_indicators_initial_status_join(char * buffer, int buffer_size){
362     if (buffer_size < (hfp_ag_generic_status_indicators_nr * 3)) return 0;
363     int i;
364     int offset = 0;
365     for (i = 0; i < hfp_ag_generic_status_indicators_nr; i++) {
366         offset += snprintf(buffer+offset, buffer_size-offset, "\r\n%s:%d,%d\r\n", HFP_GENERIC_STATUS_INDICATOR, hfp_ag_generic_status_indicators[i].uuid, hfp_ag_generic_status_indicators[i].state);
367     }
368     return offset;
369 }
370 
371 static int hfp_ag_indicators_status_join(char * buffer, int buffer_size){
372     if (buffer_size < (hfp_ag_indicators_nr * 3)) return 0;
373     int i;
374     int offset = 0;
375     for (i = 0; i < (hfp_ag_indicators_nr-1); i++) {
376         offset += snprintf(buffer+offset, buffer_size-offset, "%d,", hfp_ag_indicators[i].status);
377     }
378     if (i<hfp_ag_indicators_nr){
379         offset += snprintf(buffer+offset, buffer_size-offset, "%d", hfp_ag_indicators[i].status);
380     }
381     return offset;
382 }
383 
384 static int hfp_ag_call_services_join(char * buffer, int buffer_size){
385     if (buffer_size < (hfp_ag_call_hold_services_nr * 3)) return 0;
386     int i;
387     int offset = snprintf(buffer, buffer_size, "(");
388     for (i = 0; i < (hfp_ag_call_hold_services_nr-1); i++) {
389         offset += snprintf(buffer+offset, buffer_size-offset, "%s,", hfp_ag_call_hold_services[i]);
390     }
391     if (i<hfp_ag_call_hold_services_nr){
392         offset += snprintf(buffer+offset, buffer_size-offset, "%s)", hfp_ag_call_hold_services[i]);
393     }
394     return offset;
395 }
396 
397 static int hfp_ag_send_cmd_via_generator(uint16_t cid, hfp_connection_t * hfp_connection,
398     int start_segment, int num_segments,
399     int (*get_segment_len)(hfp_connection_t * hfp_connection, int segment),
400     void (*store_segment) (hfp_connection_t * hfp_connection, int segment, uint8_t * buffer, uint16_t buffer_size)){
401 
402     // assumes: can send now == true
403     // assumes: num segments > 0
404     // assumes: individual segments are smaller than MTU
405     rfcomm_reserve_packet_buffer();
406     int mtu = rfcomm_get_max_frame_size(cid);
407     uint8_t * data = rfcomm_get_outgoing_buffer();
408     int offset = 0;
409     int segment = start_segment;
410     while (segment < num_segments){
411         int segment_len = get_segment_len(hfp_connection, segment);
412         if ((offset + segment_len + 1) > mtu) break;
413         // append segment. As it appends a '\0', we provide a buffer one byte larger
414         store_segment(hfp_connection, segment, data+offset, segment_len + 1);
415         offset += segment_len;
416         segment++;
417     }
418     rfcomm_send_prepared(cid, offset);
419 #ifdef ENABLE_HFP_AT_MESSAGES
420     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_SENT, (char *) data);
421 #endif
422     return segment;
423 }
424 
425 // returns next segment to store
426 static int hfp_ag_send_retrieve_indicators_cmd_via_generator(uint16_t cid, hfp_connection_t * hfp_connection, int start_segment){
427     int num_segments = hfp_ag_indicators_cmd_generator_num_segments(hfp_connection);
428     return hfp_ag_send_cmd_via_generator(cid, hfp_connection, start_segment, num_segments,
429                                          hfp_ag_indicators_cmd_generator_get_segment_len,
430                                          hfp_ag_indicators_cmd_generator_store_segment);
431 }
432 
433 static int hfp_ag_send_retrieve_indicators_status_cmd(uint16_t cid){
434     char buffer[40];
435     const int size = sizeof(buffer);
436     int offset = snprintf(buffer, size, "\r\n%s:", HFP_INDICATOR);
437     offset += hfp_ag_indicators_status_join(buffer+offset, size-offset-9);
438     offset += snprintf(buffer+offset, size-offset, "\r\n\r\nOK\r\n");
439     return send_str_over_rfcomm(cid, buffer);
440 }
441 
442 static int hfp_ag_send_retrieve_can_hold_call_cmd(uint16_t cid){
443     char buffer[40];
444     const int size = sizeof(buffer);
445     int offset = snprintf(buffer, size, "\r\n%s:", HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES);
446     offset += hfp_ag_call_services_join(buffer+offset, size-offset-9);
447     offset += snprintf(buffer+offset, size-offset, "\r\n\r\nOK\r\n");
448     return send_str_over_rfcomm(cid, buffer);
449 }
450 
451 
452 static int hfp_ag_send_list_supported_generic_status_indicators_cmd(uint16_t cid){
453     return hfp_ag_send_ok(cid);
454 }
455 
456 static int hfp_ag_send_retrieve_supported_generic_status_indicators_cmd(uint16_t cid){
457     char buffer[40];
458     const int size = sizeof(buffer);
459     int offset = snprintf(buffer, size, "\r\n%s:(", HFP_GENERIC_STATUS_INDICATOR);
460     offset += hfp_ag_generic_indicators_join(buffer + offset, size - offset - 10);
461     offset += snprintf(buffer+offset, size-offset, ")\r\n\r\nOK\r\n");
462     return send_str_over_rfcomm(cid, buffer);
463 }
464 
465 static int hfp_ag_send_retrieve_initital_supported_generic_status_indicators_cmd(uint16_t cid){
466     char buffer[40];
467     int offset = hfp_ag_generic_indicators_initial_status_join(buffer, sizeof(buffer) - 7);
468     snprintf(buffer+offset, sizeof(buffer)-offset, "\r\nOK\r\n");
469     return send_str_over_rfcomm(cid, buffer);
470 }
471 
472 static int hfp_ag_send_transfer_ag_indicators_status_cmd(uint16_t cid, hfp_ag_indicator_t * indicator){
473     char buffer[20];
474     snprintf(buffer, sizeof(buffer), "\r\n%s:%d,%d\r\n",
475              HFP_TRANSFER_AG_INDICATOR_STATUS, indicator->index,
476              indicator->status);
477     buffer[sizeof(buffer) - 1] = 0;
478     return send_str_over_rfcomm(cid, buffer);
479 }
480 
481 static int hfp_ag_send_report_network_operator_name_cmd(uint16_t cid, hfp_network_opearator_t op){
482     char buffer[41];
483     if (strlen(op.name) == 0){
484         snprintf(buffer, sizeof(buffer), "\r\n%s:%d,,\r\n\r\nOK\r\n", HFP_QUERY_OPERATOR_SELECTION, op.mode);
485     } else {
486         int offset = snprintf(buffer,  sizeof(buffer), "\r\n%s:%d,%d,", HFP_QUERY_OPERATOR_SELECTION, op.mode, op.format);
487         offset += snprintf(buffer+offset, 16, "%s", op.name);
488         snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n\r\nOK\r\n");
489     }
490     return send_str_over_rfcomm(cid, buffer);
491 }
492 
493 static inline int hfp_ag_send_cmd_with_space_and_int(uint16_t cid, const char * cmd, uint8_t value){
494     char buffer[30];
495     snprintf(buffer, sizeof(buffer), "\r\n%s: %d\r\n", cmd, value);
496     return send_str_over_rfcomm(cid, buffer);
497 }
498 
499 
500 static inline int hfp_ag_send_cmd_with_int(uint16_t cid, const char * cmd, uint8_t value){
501     char buffer[30];
502     snprintf(buffer, sizeof(buffer), "\r\n%s:%d\r\n", cmd, value);
503     return send_str_over_rfcomm(cid, buffer);
504 }
505 
506 static int hfp_ag_send_suggest_codec_cmd(uint16_t cid, uint8_t codec){
507     return hfp_ag_send_cmd_with_int(cid, HFP_CONFIRM_COMMON_CODEC, codec);
508 }
509 
510 static int hfp_ag_send_set_speaker_gain_cmd(uint16_t cid, uint8_t gain){
511     return hfp_ag_send_cmd_with_int(cid, HFP_SET_SPEAKER_GAIN, gain);
512 }
513 
514 static int hfp_ag_send_set_microphone_gain_cmd(uint16_t cid, uint8_t gain){
515     return hfp_ag_send_cmd_with_int(cid, HFP_SET_MICROPHONE_GAIN, gain);
516 }
517 
518 static int hfp_ag_send_set_response_and_hold(uint16_t cid, int state){
519     return hfp_ag_send_cmd_with_space_and_int(cid, HFP_RESPONSE_AND_HOLD, state);
520 }
521 
522 static int hfp_ag_send_enhanced_voice_recognition_state_cmd(hfp_connection_t * hfp_connection){
523     char buffer[30];
524     uint8_t evra_enabled = hfp_connection->enhanced_voice_recognition_enabled ? 1 : 0;
525     snprintf(buffer, sizeof(buffer), "\r\n%s: %d,%d\r\n", HFP_ACTIVATE_VOICE_RECOGNITION, evra_enabled, hfp_connection->ag_vra_state);
526     return send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
527 }
528 
529 static int hfp_ag_send_voice_recognition_cmd(hfp_connection_t * hfp_connection, uint8_t activate_voice_recognition){
530     char buffer[30];
531     if (hfp_connection->enhanced_voice_recognition_enabled){
532         snprintf(buffer, sizeof(buffer), "\r\n%s: %d,%d\r\n", HFP_ACTIVATE_VOICE_RECOGNITION, activate_voice_recognition, hfp_connection->ag_vra_state);
533     } else {
534         snprintf(buffer, sizeof(buffer), "\r\n%s: %d\r\n", HFP_ACTIVATE_VOICE_RECOGNITION, activate_voice_recognition);
535     }
536     return send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
537 }
538 
539 static int hfp_ag_send_enhanced_voice_recognition_msg_cmd(hfp_connection_t * hfp_connection){
540     char buffer[HFP_VR_TEXT_HEADER_SIZE + HFP_MAX_VR_TEXT_SIZE];
541     snprintf(buffer, sizeof(buffer), "\r\n%s: 1,%d,%X,%d,%d,\"%s\"\r\n", HFP_ACTIVATE_VOICE_RECOGNITION,
542         hfp_connection->ag_vra_state,
543         hfp_connection->ag_msg.text_id,
544         hfp_connection->ag_msg.text_type,
545         hfp_connection->ag_msg.text_operation,
546         hfp_connection->ag_msg.text);
547     return send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
548 }
549 
550 static uint8_t hfp_ag_suggest_codec(hfp_connection_t *hfp_connection){
551     if (hfp_connection->sco_for_msbc_failed) return HFP_CODEC_CVSD;
552 
553     if (hfp_supports_codec(HFP_CODEC_MSBC, hfp_ag_codecs_nr, hfp_ag_codecs)){
554         if (hfp_supports_codec(HFP_CODEC_MSBC, hfp_connection->remote_codecs_nr, hfp_connection->remote_codecs)){
555             return HFP_CODEC_MSBC;
556         }
557     }
558     return HFP_CODEC_CVSD;
559 }
560 
561 /* state machines */
562 
563 static uint8_t hfp_ag_esco_s4_supported(hfp_connection_t * hfp_connection){
564     return (hfp_connection->remote_supported_features & (1<<HFP_HFSF_ESCO_S4)) &&  (hfp_ag_supported_features & (1 << HFP_AGSF_ESCO_S4));
565 }
566 
567 static int codecs_exchange_state_machine(hfp_connection_t * hfp_connection){
568     /* events ( == commands):
569         HFP_CMD_AVAILABLE_CODECS == received AT+BAC with list of codecs
570         HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP:
571             hf_trigger_codec_connection_setup == received BCC
572             ag_trigger_codec_connection_setup == received from AG to send BCS
573         HFP_CMD_HF_CONFIRMED_CODEC == received AT+BCS
574     */
575     switch (hfp_connection->codecs_state){
576         case HFP_CODECS_EXCHANGED:
577             if (hfp_connection->command == HFP_CMD_AVAILABLE_CODECS){
578                 hfp_ag_send_ok(hfp_connection->rfcomm_cid);
579                 return 1;
580             }
581             break;
582 
583         case HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE:
584         case HFP_CODECS_AG_RESEND_COMMON_CODEC:
585             hfp_connection->ag_send_common_codec = true;
586             break;
587         default:
588             break;
589     }
590 
591     if (hfp_connection->ag_send_common_codec){
592         hfp_connection->ag_send_common_codec = false;
593         hfp_connection->codecs_state = HFP_CODECS_AG_SENT_COMMON_CODEC;
594         hfp_connection->suggested_codec = hfp_ag_suggest_codec(hfp_connection);
595         hfp_ag_send_suggest_codec_cmd(hfp_connection->rfcomm_cid, hfp_connection->suggested_codec);
596         return 1;
597     }
598 
599     switch (hfp_connection->command){
600         case HFP_CMD_AVAILABLE_CODECS:
601             if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
602                 hfp_connection->codecs_state = HFP_CODECS_RECEIVED_LIST;
603                 hfp_ag_send_ok(hfp_connection->rfcomm_cid);
604                 return 1;
605             }
606 
607             switch (hfp_connection->codecs_state){
608                 case HFP_CODECS_AG_SENT_COMMON_CODEC:
609                     hfp_connection->codecs_state = HFP_CODECS_AG_RESEND_COMMON_CODEC;
610                     break;
611                 default:
612                     break;
613             }
614             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
615             return 1;
616 
617         case HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP:
618             hfp_connection->codecs_state = HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE;
619             hfp_connection->establish_audio_connection = 1;
620             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
621             return 1;
622 
623         case HFP_CMD_HF_CONFIRMED_CODEC:
624             if (hfp_connection->codec_confirmed != hfp_connection->suggested_codec){
625                 hfp_connection->codecs_state = HFP_CODECS_ERROR;
626                 hfp_ag_send_error(hfp_connection->rfcomm_cid);
627                 return 1;
628             }
629             hfp_connection->negotiated_codec = hfp_connection->codec_confirmed;
630             hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
631             log_info("hfp: codec confirmed: %s", (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? "mSBC" : "CVSD");
632             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
633             // now, pick link settings
634             hfp_init_link_settings(hfp_connection, hfp_ag_esco_s4_supported(hfp_connection));
635 #ifdef ENABLE_CC256X_ASSISTED_HFP
636             hfp_cc256x_prepare_for_sco(hfp_connection);
637 #endif
638 #ifdef ENABLE_RTK_PCM_WBS
639             hfp_connection->rtk_send_sco_config = true;
640 #endif
641             return 1;
642         default:
643             break;
644     }
645     return 0;
646 }
647 
648 static void hfp_ag_slc_established(hfp_connection_t * hfp_connection){
649     hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
650     hfp_emit_slc_connection_event(hfp_connection, 0, hfp_connection->acl_handle, hfp_connection->remote_addr);
651 
652     // if active call exist, set per-hfp_connection state active, too (when audio is on)
653     if (hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT){
654         hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE;
655     }
656     // if AG is ringing, also start ringing on the HF
657     if (hfp_gsm_call_status() == HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS){
658         switch (hfp_gsm_callsetup_status()){
659             case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
660                 hfp_ag_hf_start_ringing_incoming(hfp_connection);
661                 break;
662             case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
663                 hfp_ag_hf_start_ringing_outgoing(hfp_connection);
664                 break;
665             default:
666                 break;
667         }
668     }
669 }
670 
671 static int hfp_ag_run_for_context_service_level_connection(hfp_connection_t * hfp_connection){
672     // log_info("hfp_ag_run_for_context_service_level_connection state %u, command %u", hfp_connection->state, hfp_connection->command);
673     if (hfp_connection->state >= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) return 0;
674     int sent = 0;
675     switch(hfp_connection->command){
676         case HFP_CMD_SUPPORTED_FEATURES:
677             switch(hfp_connection->state){
678                 case HFP_W4_EXCHANGE_SUPPORTED_FEATURES:
679                 case HFP_EXCHANGE_SUPPORTED_FEATURES:
680                     hfp_hf_drop_mSBC_if_eSCO_not_supported(hfp_ag_codecs, &hfp_ag_codecs_nr);
681                     if (has_codec_negotiation_feature(hfp_connection)){
682                         hfp_connection->state = HFP_W4_NOTIFY_ON_CODECS;
683                     } else {
684                         hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS;
685                     }
686                     hfp_ag_exchange_supported_features_cmd(hfp_connection->rfcomm_cid);
687                     return 1;
688                 default:
689                     break;
690             }
691             break;
692         case HFP_CMD_AVAILABLE_CODECS:
693             sent = codecs_exchange_state_machine(hfp_connection);
694             if (hfp_connection->codecs_state == HFP_CODECS_RECEIVED_LIST){
695                 hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS;
696             }
697             return sent;
698 
699         case HFP_CMD_RETRIEVE_AG_INDICATORS:
700             if (hfp_connection->state == HFP_W4_RETRIEVE_INDICATORS) {
701                 // HF requested AG Indicators and we did expect it
702                 hfp_connection->send_ag_indicators_segment = 0;
703                 hfp_connection->state = HFP_RETRIEVE_INDICATORS;
704                 // continue below in state switch
705             }
706             break;
707 
708         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
709             if (hfp_connection->state != HFP_W4_RETRIEVE_INDICATORS_STATUS) break;
710             hfp_connection->state = HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE;
711             hfp_ag_send_retrieve_indicators_status_cmd(hfp_connection->rfcomm_cid);
712             return 1;
713 
714         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
715             if (hfp_connection->state != HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE) break;
716             if (has_call_waiting_and_3way_calling_feature(hfp_connection)){
717                 hfp_connection->state = HFP_W4_RETRIEVE_CAN_HOLD_CALL;
718             } else if (has_hf_indicators_feature(hfp_connection)){
719                 hfp_connection->state = HFP_W4_LIST_GENERIC_STATUS_INDICATORS;
720             } else {
721                 hfp_ag_slc_established(hfp_connection);
722             }
723             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
724             return 1;
725 
726         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
727             if (hfp_connection->state != HFP_W4_RETRIEVE_CAN_HOLD_CALL) break;
728             if (has_hf_indicators_feature(hfp_connection)){
729                 hfp_connection->state = HFP_W4_LIST_GENERIC_STATUS_INDICATORS;
730             }
731             hfp_ag_send_retrieve_can_hold_call_cmd(hfp_connection->rfcomm_cid);
732             if (!has_hf_indicators_feature(hfp_connection)){
733                 hfp_ag_slc_established(hfp_connection);
734             }
735             return 1;
736 
737         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
738             if (hfp_connection->state != HFP_W4_LIST_GENERIC_STATUS_INDICATORS) break;
739             hfp_connection->state = HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS;
740             hfp_ag_send_list_supported_generic_status_indicators_cmd(hfp_connection->rfcomm_cid);
741             return 1;
742 
743         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
744             if (hfp_connection->state != HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS) break;
745             hfp_connection->state = HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS;
746             hfp_ag_send_retrieve_supported_generic_status_indicators_cmd(hfp_connection->rfcomm_cid);
747             return 1;
748 
749         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
750             if (hfp_connection->state != HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS) break;
751             hfp_ag_slc_established(hfp_connection);
752             hfp_ag_send_retrieve_initital_supported_generic_status_indicators_cmd(hfp_connection->rfcomm_cid);
753             return 1;
754         default:
755             break;
756     }
757 
758     switch (hfp_connection->state){
759         case HFP_RETRIEVE_INDICATORS: {
760             int next_segment = hfp_ag_send_retrieve_indicators_cmd_via_generator(hfp_connection->rfcomm_cid, hfp_connection, hfp_connection->send_ag_indicators_segment);
761             int num_segments = hfp_ag_indicators_cmd_generator_num_segments(hfp_connection);
762             log_info("HFP_CMD_RETRIEVE_AG_INDICATORS next segment %u, num_segments %u", next_segment, num_segments);
763             if (next_segment < num_segments){
764                 // prepare sending of next segment
765                 hfp_connection->send_ag_indicators_segment = next_segment;
766                 log_info("HFP_CMD_RETRIEVE_AG_INDICATORS more. command %u, next seg %u", hfp_connection->command, next_segment);
767             } else {
768                 // done, go to next state
769                 hfp_connection->send_ag_indicators_segment = 0;
770                 hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS_STATUS;
771             }
772             return 1;
773         }
774         default:
775             break;
776     }
777     return 0;
778 }
779 
780 static bool hfp_ag_vra_flag_supported(hfp_connection_t * hfp_connection){
781     int ag = get_bit(hfp_ag_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION);
782     int hf = get_bit(hfp_connection->remote_supported_features, HFP_HFSF_VOICE_RECOGNITION_FUNCTION);
783     return hf && ag;
784 }
785 
786 static bool hfp_ag_enhanced_vra_flag_supported(hfp_connection_t * hfp_connection){
787     int ag = get_bit(hfp_ag_supported_features, HFP_AGSF_ENHANCED_VOICE_RECOGNITION_STATUS);
788     int hf = get_bit(hfp_connection->remote_supported_features, HFP_HFSF_ENHANCED_VOICE_RECOGNITION_STATUS);
789     return hf && ag;
790 }
791 
792 static bool hfp_ag_can_send_enhanced_vra_message_flag_supported(hfp_connection_t * hfp_connection){
793     int ag = get_bit(hfp_ag_supported_features, HFP_AGSF_VOICE_RECOGNITION_TEXT);
794     int hf = get_bit(hfp_connection->remote_supported_features, HFP_HFSF_VOICE_RECOGNITION_TEXT);
795     return hf && ag;
796 }
797 
798 static bool hfp_ag_can_activate_voice_recognition(hfp_connection_t * hfp_connection){
799     if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED || hfp_connection->state > HFP_AUDIO_CONNECTION_ESTABLISHED){
800         return false;
801     }
802     if (hfp_connection->vra_state != HFP_VRA_VOICE_RECOGNITION_OFF){
803         return false;
804     }
805     if (hfp_connection->ag_vra_send_command){
806         return false;
807     }
808     return true;
809 }
810 
811 static bool hfp_ag_voice_recognition_session_active(hfp_connection_t * hfp_connection){
812     if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED || hfp_connection->state > HFP_AUDIO_CONNECTION_ESTABLISHED){
813         return false;
814     }
815     if (hfp_connection->vra_state != HFP_VRA_VOICE_RECOGNITION_ACTIVATED){
816         if (hfp_connection->vra_state == HFP_VRA_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO){
817             return true;
818         }
819         return false;
820     }
821     return true;
822 }
823 
824 static bool hfp_ag_is_audio_connection_active(hfp_connection_t * hfp_connection){
825     switch (hfp_connection->state){
826         case HFP_W2_CONNECT_SCO:
827         case HFP_W4_SCO_CONNECTED:
828         case HFP_AUDIO_CONNECTION_ESTABLISHED:
829             return true;
830         default:
831             return false;
832     }
833 }
834 
835 static void hfp_ag_emit_enhanced_voice_recognition_msg_sent_event(hfp_connection_t * hfp_connection, uint8_t status){
836     hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID;
837 
838     uint8_t event[6];
839     event[0] = HCI_EVENT_HFP_META;
840     event[1] = sizeof(event) - 2;
841     event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_AG_MESSAGE_SENT;
842     little_endian_store_16(event, 3, acl_handle);
843     event[5] = status;
844     (*hfp_ag_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
845 }
846 
847 
848 static void hfp_ag_emit_hf_indicator_value(hfp_connection_t * hfp_connection, uint16_t uuid, uint8_t value){
849     hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID;
850 
851     uint8_t event[8];
852     event[0] = HCI_EVENT_HFP_META;
853     event[1] = sizeof(event) - 2;
854     event[2] = HFP_SUBEVENT_HF_INDICATOR;
855     little_endian_store_16(event, 3, acl_handle);
856     little_endian_store_16(event, 5, uuid);
857     event[7] = value;
858     (*hfp_ag_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
859 }
860 
861 static void hfp_ag_emit_general_simple_event(uint8_t event_subtype){
862     if (!hfp_ag_callback) return;
863 
864     uint8_t event[5];
865     event[0] = HCI_EVENT_HFP_META;
866     event[1] = sizeof(event) - 2;
867     event[2] = event_subtype;
868     little_endian_store_16(event, 3, HCI_CON_HANDLE_INVALID);
869     (*hfp_ag_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
870 }
871 
872 // @return status
873 static uint8_t hfp_ag_vra_state_machine_two(hfp_connection_t * hfp_connection){
874     uint8_t status = ERROR_CODE_SUCCESS;
875     switch (hfp_connection->vra_state_requested){
876         case HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO:
877             if (!hfp_ag_is_audio_connection_active(hfp_connection)){
878                 status = hfp_ag_setup_audio_connection(hfp_connection);
879                 if (status != ERROR_CODE_SUCCESS){
880                     hfp_connection->vra_state_requested = hfp_connection->vra_state;
881                     hfp_emit_voice_recognition_enabled(hfp_connection, status);
882                     break;
883                 }
884             }
885             hfp_connection->enhanced_voice_recognition_enabled = true;
886             hfp_connection->vra_state = HFP_VRA_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO;
887             hfp_connection->vra_state_requested = hfp_connection->vra_state;
888             hfp_emit_enhanced_voice_recognition_hf_ready_for_audio_event(hfp_connection, ERROR_CODE_SUCCESS);
889             break;
890 
891         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF:
892             hfp_connection->vra_state = HFP_VRA_VOICE_RECOGNITION_OFF;
893             hfp_connection->vra_state_requested = hfp_connection->vra_state;
894 
895             // release audio connection only if it was opened after audio VR activated
896             if (hfp_ag_is_audio_connection_active(hfp_connection) && !hfp_connection->ag_audio_connection_opened_before_vra){
897                 hfp_trigger_release_audio_connection(hfp_connection);
898             }
899 
900             hfp_emit_voice_recognition_disabled(hfp_connection, ERROR_CODE_SUCCESS);
901             break;
902 
903         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED:
904             // open only if audio connection does not already exist
905             if (!hfp_ag_is_audio_connection_active(hfp_connection)){
906                 status = hfp_ag_setup_audio_connection(hfp_connection);
907                 if (status != ERROR_CODE_SUCCESS){
908                     hfp_connection->vra_state_requested = hfp_connection->vra_state;
909                     hfp_emit_voice_recognition_enabled(hfp_connection, status);
910                     break;
911                 }
912             }
913 
914             hfp_connection->vra_state = HFP_VRA_VOICE_RECOGNITION_ACTIVATED;
915             hfp_connection->vra_state_requested = hfp_connection->vra_state;
916             hfp_connection->enhanced_voice_recognition_enabled = hfp_ag_enhanced_vra_flag_supported(hfp_connection);
917 
918             if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
919                 hfp_emit_voice_recognition_enabled(hfp_connection, ERROR_CODE_SUCCESS);
920             } else {
921                 hfp_connection->emit_vra_enabled_after_audio_established = true;
922             }
923             break;
924 
925         default:
926             break;
927     }
928     return status;
929 }
930 
931 static uint8_t hfp_ag_vra_send_command(hfp_connection_t * hfp_connection){
932     uint8_t done = 0;
933     uint8_t status;
934 
935     switch (hfp_connection->vra_state_requested){
936         case HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_MSG:
937             done = hfp_ag_send_enhanced_voice_recognition_msg_cmd(hfp_connection);
938             if (done == 0){
939                 hfp_ag_emit_enhanced_voice_recognition_msg_sent_event(hfp_connection, ERROR_CODE_UNSPECIFIED_ERROR);
940             } else {
941                 hfp_ag_emit_enhanced_voice_recognition_msg_sent_event(hfp_connection, ERROR_CODE_SUCCESS);
942             }
943             hfp_connection->vra_state_requested = hfp_connection->vra_state;
944             return done;
945 
946         case HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_STATUS:
947             done = hfp_ag_send_enhanced_voice_recognition_state_cmd(hfp_connection);
948             if (done == 0){
949                 hfp_emit_enhanced_voice_recognition_state_event(hfp_connection, ERROR_CODE_UNSPECIFIED_ERROR);
950             } else {
951                 hfp_emit_enhanced_voice_recognition_state_event(hfp_connection, ERROR_CODE_SUCCESS);
952             }
953             hfp_connection->vra_state_requested = hfp_connection->vra_state;
954             return done;
955 
956         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED:
957         case HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF:
958             done = hfp_ag_send_voice_recognition_cmd(hfp_connection, hfp_connection->ag_activate_voice_recognition_value);
959             if (done == 0){
960                 hfp_connection->vra_state_requested = hfp_connection->vra_state;
961 
962                 if (hfp_connection->ag_activate_voice_recognition_value == 1){
963                     hfp_emit_voice_recognition_enabled(hfp_connection, done);
964                 } else {
965                     hfp_emit_voice_recognition_disabled(hfp_connection, done);
966                 }
967                 return 0;
968             }
969             status = hfp_ag_vra_state_machine_two(hfp_connection);
970             return (status == ERROR_CODE_SUCCESS) ? 1 : 0;
971 
972         default:
973             log_error("state %u", hfp_connection->vra_state_requested);
974             btstack_assert(false);
975             return 0;
976     }
977 }
978 
979 static int hfp_ag_voice_recognition_state_machine(hfp_connection_t * hfp_connection){
980     if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) {
981         return 0;
982     }
983     int done = 0;
984     uint8_t status;
985 
986     // VRA action initiated by AG
987     if (hfp_connection->ag_vra_send_command){
988         hfp_connection->ag_vra_send_command = false;
989         return hfp_ag_vra_send_command(hfp_connection);
990     }
991 
992     if (hfp_connection->ag_vra_requested_by_hf){
993         hfp_connection->ag_vra_requested_by_hf = false;
994 
995         // HF initiatied voice recognition, parser extracted activation value
996         switch (hfp_connection->ag_activate_voice_recognition_value){
997             case 0:
998                 if (hfp_ag_voice_recognition_session_active(hfp_connection)){
999                     hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF;
1000                     done = hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1001                 }
1002                 break;
1003 
1004                 case 1:
1005                     if (hfp_ag_can_activate_voice_recognition(hfp_connection)){
1006                         hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED;
1007                         done = hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1008                     }
1009                     break;
1010 
1011                     case 2:
1012                         if (hfp_ag_voice_recognition_session_active(hfp_connection)){
1013                             hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO;
1014                             done = hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1015                         }
1016                         break;
1017                         default:
1018                             break;
1019         }
1020         if (done == 0){
1021             hfp_connection->vra_state_requested = hfp_connection->vra_state;
1022             done = hfp_ag_send_error(hfp_connection->rfcomm_cid);
1023             return 1;
1024         }
1025 
1026         status = hfp_ag_vra_state_machine_two(hfp_connection);
1027         return (status == ERROR_CODE_SUCCESS) ? 1 : 0;
1028     }
1029 
1030     return 0;
1031 }
1032 
1033 static int hfp_ag_run_for_context_service_level_connection_queries(hfp_connection_t * hfp_connection){
1034     int sent = codecs_exchange_state_machine(hfp_connection);
1035     if (sent) return 1;
1036 
1037     if (hfp_connection->ag_send_in_band_ring_tone_setting){
1038         hfp_connection->ag_send_in_band_ring_tone_setting = false;
1039         hfp_ag_send_change_in_band_ring_tone_setting_cmd(hfp_connection->rfcomm_cid);
1040         return 1;
1041     }
1042 
1043     switch(hfp_connection->command){
1044         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1045             hfp_ag_send_report_network_operator_name_cmd(hfp_connection->rfcomm_cid, hfp_connection->network_operator);
1046             return 1;
1047         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1048             if (hfp_connection->network_operator.format != 0){
1049                 hfp_ag_send_error(hfp_connection->rfcomm_cid);
1050             } else {
1051                 hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1052             }
1053             return 1;
1054         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1055             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1056             return 1;
1057         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1058             if (hfp_connection->extended_audio_gateway_error){
1059                 hfp_connection->extended_audio_gateway_error = 0;
1060                 hfp_ag_send_report_extended_audio_gateway_error(hfp_connection->rfcomm_cid, hfp_connection->extended_audio_gateway_error_value);
1061                 return 1;
1062             }
1063             break;
1064         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1065             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1066             return 1;
1067         default:
1068             break;
1069     }
1070     return 0;
1071 }
1072 
1073 static int hfp_ag_run_for_audio_connection(hfp_connection_t * hfp_connection){
1074     if ((hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) ||
1075         (hfp_connection->state > HFP_W2_DISCONNECT_SCO)) return 0;
1076 
1077     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1078 
1079     if (hfp_connection->release_audio_connection){
1080         hfp_connection->state = HFP_W4_SCO_DISCONNECTED;
1081         hfp_connection->release_audio_connection = 0;
1082         gap_disconnect(hfp_connection->sco_handle);
1083         return 1;
1084     }
1085 
1086     // accept incoming audio connection (codec negotiation is not used)
1087     if (hfp_connection->accept_sco){
1088         // notify about codec selection if not done already
1089         if (hfp_connection->negotiated_codec == 0){
1090             hfp_connection->negotiated_codec = HFP_CODEC_CVSD;
1091         }
1092         //
1093         bool incoming_eSCO = hfp_connection->accept_sco == 2;
1094         hfp_connection->accept_sco = 0;
1095         hfp_connection->state = HFP_W4_SCO_CONNECTED;
1096         hfp_accept_synchronous_connection(hfp_connection, incoming_eSCO);
1097         return 1;
1098     }
1099 
1100     // run codecs exchange
1101     int sent = codecs_exchange_state_machine(hfp_connection);
1102     if (sent) return 1;
1103 
1104     if (hfp_connection->codecs_state != HFP_CODECS_EXCHANGED) return 0;
1105     if (hfp_connection->establish_audio_connection){
1106         hfp_connection->state = HFP_W4_SCO_CONNECTED;
1107         hfp_connection->establish_audio_connection = 0;
1108         hfp_setup_synchronous_connection(hfp_connection);
1109         return 1;
1110     }
1111     return 0;
1112 }
1113 
1114 static void hfp_ag_set_callsetup_indicator(void){
1115     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("callsetup");
1116     if (!indicator){
1117         log_error("hfp_ag_set_callsetup_indicator: callsetup indicator is missing");
1118         return;
1119     };
1120     indicator->status = hfp_gsm_callsetup_status();
1121 }
1122 
1123 static void hfp_ag_set_callheld_indicator(void){
1124     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("callheld");
1125     if (!indicator){
1126         log_error("hfp_ag_set_callheld_state: callheld indicator is missing");
1127         return;
1128     };
1129     indicator->status = hfp_gsm_callheld_status();
1130 }
1131 
1132 //
1133 // transition implementations for hfp_ag_call_state_machine
1134 //
1135 
1136 static void hfp_ag_hf_start_ringing_incoming(hfp_connection_t * hfp_connection){
1137     if (use_in_band_tone()){
1138         hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING;
1139         hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
1140     } else {
1141         hfp_connection->call_state = HFP_CALL_INCOMING_RINGING;
1142     }
1143 }
1144 
1145 static void hfp_ag_hf_start_ringing_outgoing(hfp_connection_t * hfp_connection){
1146     hfp_connection->call_state = HFP_CALL_OUTGOING_RINGING;
1147 }
1148 
1149 static void hfp_ag_hf_stop_ringing(hfp_connection_t * hfp_connection){
1150     hfp_connection->ag_ring = 0;
1151     hfp_connection->ag_send_clip = 0;
1152 }
1153 
1154 
1155 static void hfp_ag_trigger_incoming_call_during_active_one(void){
1156     btstack_linked_list_iterator_t it;
1157     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1158     while (btstack_linked_list_iterator_has_next(&it)){
1159         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1160         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1161         if (hfp_connection->call_state != HFP_CALL_ACTIVE) continue;
1162 
1163         hfp_connection->call_state = HFP_CALL_W2_SEND_CALL_WAITING;
1164         hfp_ag_run_for_context(hfp_connection);
1165     }
1166 }
1167 
1168 static void hfp_ag_trigger_ring_and_clip(void) {
1169     btstack_linked_list_iterator_t it;
1170     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1171     while (btstack_linked_list_iterator_has_next(&it)){
1172         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1173         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1174         switch (hfp_connection->call_state){
1175             case HFP_CALL_INCOMING_RINGING:
1176             case HFP_CALL_OUTGOING_RINGING:
1177             case HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING:
1178                 // Queue RING on this connection
1179                 hfp_connection->ag_ring = 1;
1180 
1181                 // HFP v1.8, 4.23 Calling Line Identification (CLI) Notification
1182                 // "If the calling subscriber number information is available from the network, the AG shall issue the
1183                 // +CLIP unsolicited result code just after every RING indication when the HF is alerted in an incoming call."
1184                 hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
1185 
1186                 // trigger next message
1187                 rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1188                 break;
1189             default:
1190                 break;
1191         }
1192     }
1193 }
1194 
1195 // trigger RING and CLIP messages on connections that are ringing
1196 static void hfp_ag_ring_timeout_handler(btstack_timer_source_t * timer){
1197     hfp_ag_trigger_ring_and_clip();
1198 
1199     btstack_run_loop_set_timer(timer, HFP_RING_PERIOD_MS); // 2 seconds timeout
1200     btstack_run_loop_add_timer(timer);
1201 }
1202 
1203 static void hfp_ag_ring_timeout_stop(void){
1204     btstack_run_loop_remove_timer(&hfp_ag_ring_timeout);
1205 }
1206 
1207 static void hfp_ag_start_ringing(void){
1208     // setup ring timer
1209     btstack_run_loop_remove_timer(&hfp_ag_ring_timeout);
1210     btstack_run_loop_set_timer_handler(&hfp_ag_ring_timeout, hfp_ag_ring_timeout_handler);
1211     btstack_run_loop_set_timer(&hfp_ag_ring_timeout, HFP_RING_PERIOD_MS); // 2 seconds timeout
1212     btstack_run_loop_add_timer(&hfp_ag_ring_timeout);
1213 
1214     // emit start ringing
1215     hfp_ag_emit_general_simple_event(HFP_SUBEVENT_START_RINGING);
1216 
1217     // send initial RING + CLIP
1218     hfp_ag_trigger_ring_and_clip();
1219 }
1220 
1221 static void hfp_ag_stop_ringing(void){
1222     hfp_ag_ring_timeout_stop();
1223     hfp_ag_emit_general_simple_event(HFP_SUBEVENT_STOP_RINGING);
1224 
1225     btstack_linked_list_iterator_t it;
1226     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1227     while (btstack_linked_list_iterator_has_next(&it)){
1228         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1229         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1230         if ((hfp_connection->call_state != HFP_CALL_INCOMING_RINGING) &&
1231             (hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
1232         hfp_ag_hf_stop_ringing(hfp_connection);
1233     }
1234 }
1235 
1236 static void hfp_ag_trigger_incoming_call_idle(void){
1237     int indicator_index = get_ag_indicator_index_for_name("callsetup");
1238     if (indicator_index < 0) return;
1239 
1240     // update callsetup state in connections
1241     btstack_linked_list_iterator_t it;
1242     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1243     while (btstack_linked_list_iterator_has_next(&it)){
1244         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1245         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1246         if (hfp_connection->call_state != HFP_CALL_IDLE) continue;
1247 
1248         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1249 
1250         hfp_ag_hf_start_ringing_incoming(hfp_connection);
1251 
1252         hfp_ag_run_for_context(hfp_connection);
1253     }
1254 
1255     // start local ringing - started after connection state has been updated
1256     hfp_ag_start_ringing();
1257 }
1258 
1259 static void hfp_ag_trigger_outgoing_call(void){
1260     btstack_linked_list_iterator_t it;
1261     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1262     while (btstack_linked_list_iterator_has_next(&it)){
1263         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1264         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1265         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
1266         if (hfp_connection->call_state == HFP_CALL_IDLE){
1267             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1268         }
1269     }
1270 }
1271 
1272 static void hfp_ag_handle_outgoing_call_accepted(hfp_connection_t * hfp_connection){
1273     hfp_connection->call_state = HFP_CALL_OUTGOING_DIALING;
1274 
1275     // trigger callsetup to be
1276     int put_call_on_hold = hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT;
1277     hfp_gsm_handler(HFP_AG_OUTGOING_CALL_ACCEPTED, 0, 0, NULL);
1278 
1279     int indicator_index ;
1280 
1281     hfp_ag_set_callsetup_indicator();
1282     indicator_index = get_ag_indicator_index_for_name("callsetup");
1283     hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1284 
1285     // put current call on hold if active
1286     if (put_call_on_hold){
1287         log_info("AG putting current call on hold for new outgoing call");
1288         hfp_ag_set_callheld_indicator();
1289         indicator_index = get_ag_indicator_index_for_name("callheld");
1290         hfp_ag_send_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[indicator_index]);
1291     }
1292 
1293     // start audio if needed
1294     hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
1295 }
1296 
1297 static void hfp_ag_transfer_indicator(const char * name){
1298     int indicator_index = get_ag_indicator_index_for_name(name);
1299     if (indicator_index < 0) return;
1300 
1301     btstack_linked_list_iterator_t it;
1302     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1303     while (btstack_linked_list_iterator_has_next(&it)){
1304         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1305         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1306         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
1307         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1308         hfp_ag_run_for_context(hfp_connection);
1309     }
1310 }
1311 
1312 static void hfp_ag_transfer_callsetup_state(void){
1313     hfp_ag_transfer_indicator("callsetup");
1314 }
1315 
1316 static void hfp_ag_transfer_call_state(void){
1317     hfp_ag_transfer_indicator("call");
1318 }
1319 
1320 static void hfp_ag_transfer_callheld_state(void){
1321     hfp_ag_transfer_indicator("callheld");
1322 }
1323 
1324 static void hfp_ag_hf_accept_call(hfp_connection_t * source){
1325     int call_indicator_index = get_ag_indicator_index_for_name("call");
1326     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1327 
1328     hfp_ag_stop_ringing();
1329 
1330     btstack_linked_list_iterator_t it;
1331     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1332     while (btstack_linked_list_iterator_has_next(&it)){
1333         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1334         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1335         if ((hfp_connection->call_state != HFP_CALL_INCOMING_RINGING) &&
1336             (hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
1337 
1338         if (hfp_connection == source){
1339 
1340             if (use_in_band_tone()){
1341                 hfp_connection->call_state = HFP_CALL_ACTIVE;
1342             } else {
1343                 hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE;
1344                 hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
1345             }
1346 
1347             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1348             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1349 
1350         } else {
1351             hfp_connection->call_state = HFP_CALL_IDLE;
1352         }
1353         hfp_ag_run_for_context(hfp_connection);
1354     }
1355 }
1356 
1357 static void hfp_ag_ag_accept_call(void){
1358     int call_indicator_index = get_ag_indicator_index_for_name("call");
1359     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1360 
1361     hfp_ag_stop_ringing();
1362 
1363     btstack_linked_list_iterator_t it;
1364     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1365     while (btstack_linked_list_iterator_has_next(&it)){
1366         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1367         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1368         if ((hfp_connection->call_state != HFP_CALL_INCOMING_RINGING) &&
1369             (hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
1370 
1371         hfp_connection->call_state = HFP_CALL_TRIGGER_AUDIO_CONNECTION;
1372 
1373         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1374         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1375 
1376         hfp_ag_run_for_context(hfp_connection);
1377         break;  // only single
1378     }
1379 }
1380 
1381 static void hfp_ag_trigger_reject_call(void){
1382     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1383 
1384     hfp_ag_stop_ringing();
1385 
1386     btstack_linked_list_iterator_t it;
1387     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1388     while (btstack_linked_list_iterator_has_next(&it)){
1389         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1390         if (connection->local_role != HFP_ROLE_AG) continue;
1391         if ((connection->call_state != HFP_CALL_INCOMING_RINGING) &&
1392             (connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
1393 
1394         connection->call_state = HFP_CALL_IDLE;
1395         connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1396 
1397         if (connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
1398             connection->release_audio_connection = 1;
1399         }
1400         hfp_emit_simple_event(connection, HFP_SUBEVENT_CALL_TERMINATED);
1401         hfp_ag_run_for_context(connection);
1402         rfcomm_request_can_send_now_event(connection->rfcomm_cid);
1403     }
1404 }
1405 
1406 static void hfp_ag_trigger_terminate_call(void){
1407     int call_indicator_index = get_ag_indicator_index_for_name("call");
1408 
1409     // no ringing during call
1410 
1411     btstack_linked_list_iterator_t it;
1412     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1413     while (btstack_linked_list_iterator_has_next(&it)){
1414         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1415         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1416         if (hfp_connection->call_state == HFP_CALL_IDLE) continue;
1417 
1418         hfp_connection->call_state = HFP_CALL_IDLE;
1419         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1420 
1421         if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
1422             hfp_connection->release_audio_connection = 1;
1423         }
1424 
1425         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_TERMINATED);
1426         hfp_ag_run_for_context(hfp_connection);
1427         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1428     }
1429 }
1430 
1431 static void hfp_ag_set_call_indicator(void){
1432     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("call");
1433     if (!indicator){
1434         log_error("hfp_ag_set_call_state: call indicator is missing");
1435         return;
1436     };
1437     indicator->status = hfp_gsm_call_status();
1438 }
1439 
1440 static hfp_connection_t * hfp_ag_connection_for_call_state(hfp_call_state_t call_state){
1441     btstack_linked_list_iterator_t it;
1442     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1443     while (btstack_linked_list_iterator_has_next(&it)){
1444         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1445         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1446         if (hfp_connection->call_state == call_state) return hfp_connection;
1447     }
1448     return NULL;
1449 }
1450 
1451 static void hfp_ag_send_response_and_hold_state(hfp_response_and_hold_state_t state){
1452     btstack_linked_list_iterator_t it;
1453     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1454     while (btstack_linked_list_iterator_has_next(&it)){
1455         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1456         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1457         hfp_connection->send_response_and_hold_status = state + 1;
1458     }
1459 }
1460 
1461 static int call_setup_state_machine(hfp_connection_t * hfp_connection){
1462     int indicator_index;
1463     switch (hfp_connection->call_state){
1464         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING:
1465             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1466             // we got event: audio hfp_connection established
1467             hfp_connection->call_state = HFP_CALL_INCOMING_RINGING;
1468             break;
1469         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE:
1470             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1471             // we got event: audio hfp_connection established
1472             hfp_connection->call_state = HFP_CALL_ACTIVE;
1473             break;
1474         case HFP_CALL_W2_SEND_CALL_WAITING:
1475             hfp_connection->call_state = HFP_CALL_W4_CHLD;
1476             hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1477             indicator_index = get_ag_indicator_index_for_name("callsetup");
1478             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1479             break;
1480         default:
1481             break;
1482     }
1483     return 0;
1484 }
1485 
1486 // functions extracted from hfp_ag_call_sm below
1487 static void hfp_ag_handle_reject_outgoing_call(void){
1488     hfp_connection_t * hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1489     if (!hfp_connection){
1490         log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1491         return;
1492     }
1493 
1494     hfp_gsm_handler(HFP_AG_OUTGOING_CALL_REJECTED, 0, 0, NULL);
1495     hfp_connection->call_state = HFP_CALL_IDLE;
1496     hfp_connection->send_error = 1;
1497     hfp_ag_run_for_context(hfp_connection);
1498 }
1499 
1500 // hfp_connection is used to identify originating HF
1501 static void hfp_ag_call_sm(hfp_ag_call_event_t event, hfp_connection_t * hfp_connection){
1502 
1503     // allow to intercept call statemachine events
1504     if (hfp_ag_custom_call_sm_handler != NULL){
1505         bool handle_event = (*hfp_ag_custom_call_sm_handler)(event);
1506         if (!handle_event) return;
1507     }
1508 
1509     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1510     int callheld_indicator_index = get_ag_indicator_index_for_name("callheld");
1511     int call_indicator_index = get_ag_indicator_index_for_name("call");
1512 
1513     switch (event){
1514         case HFP_AG_INCOMING_CALL:
1515             switch (hfp_gsm_call_status()){
1516                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1517                     switch (hfp_gsm_callsetup_status()){
1518                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1519                             hfp_gsm_handler(HFP_AG_INCOMING_CALL, 0, 0, NULL);
1520                             hfp_ag_set_callsetup_indicator();
1521                             hfp_ag_trigger_incoming_call_idle();
1522                             log_info("AG rings");
1523                             break;
1524                         default:
1525                             break;
1526                     }
1527                     break;
1528                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1529                     switch (hfp_gsm_callsetup_status()){
1530                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1531                             hfp_gsm_handler(HFP_AG_INCOMING_CALL, 0, 0, NULL);
1532                             hfp_ag_set_callsetup_indicator();
1533                             hfp_ag_trigger_incoming_call_during_active_one();
1534                             log_info("AG call waiting");
1535                             break;
1536                         default:
1537                             break;
1538                     }
1539                     break;
1540                 default:
1541                     break;
1542             }
1543             break;
1544         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG:
1545             switch (hfp_gsm_call_status()){
1546                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1547                     switch (hfp_gsm_callsetup_status()){
1548                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1549                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, 0, 0, NULL);
1550                             hfp_ag_set_call_indicator();
1551                             hfp_ag_set_callsetup_indicator();
1552                             hfp_ag_ag_accept_call();
1553                             log_info("AG answers call, accept call by GSM");
1554                             break;
1555                         default:
1556                             break;
1557                     }
1558                     break;
1559                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1560                     switch (hfp_gsm_callsetup_status()){
1561                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1562                             log_info("AG: current call is placed on hold, incoming call gets active");
1563                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, 0, 0, NULL);
1564                             hfp_ag_set_callsetup_indicator();
1565                             hfp_ag_set_callheld_indicator();
1566                             hfp_ag_transfer_callsetup_state();
1567                             hfp_ag_transfer_callheld_state();
1568                             break;
1569                         default:
1570                             break;
1571                     }
1572                     break;
1573                 default:
1574                     break;
1575             }
1576             break;
1577 
1578         case HFP_AG_HELD_CALL_JOINED_BY_AG:
1579             switch (hfp_gsm_call_status()){
1580                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1581                     switch (hfp_gsm_callheld_status()){
1582                         case HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED:
1583                             log_info("AG: joining held call with active call");
1584                             hfp_gsm_handler(HFP_AG_HELD_CALL_JOINED_BY_AG, 0, 0, NULL);
1585                             hfp_ag_set_callheld_indicator();
1586                             hfp_ag_transfer_callheld_state();
1587                             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CONFERENCE_CALL);
1588                             break;
1589                         default:
1590                             break;
1591                     }
1592                     break;
1593                 default:
1594                     break;
1595             }
1596             break;
1597 
1598         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF:
1599             switch (hfp_gsm_call_status()){
1600                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1601                     switch (hfp_gsm_callsetup_status()){
1602                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1603                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, 0, 0, NULL);
1604                             hfp_ag_set_callsetup_indicator();
1605                             hfp_ag_set_call_indicator();
1606                             hfp_ag_hf_accept_call(hfp_connection);
1607                             hfp_connection->ok_pending = 1;
1608                             log_info("HF answers call, accept call by GSM");
1609                             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_ANSWERED);
1610                             break;
1611                         default:
1612                             break;
1613                     }
1614                     break;
1615                 default:
1616                     break;
1617             }
1618             break;
1619 
1620         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG:
1621             switch (hfp_gsm_call_status()){
1622                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1623                     switch (hfp_gsm_callsetup_status()){
1624                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1625                             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, 0, 0, NULL);
1626                             hfp_ag_response_and_hold_active = true;
1627                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1628                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1629                             // as with regular call
1630                             hfp_ag_set_call_indicator();
1631                             hfp_ag_set_callsetup_indicator();
1632                             hfp_ag_ag_accept_call();
1633                             log_info("AG response and hold - hold by AG");
1634                             break;
1635                         default:
1636                             break;
1637                     }
1638                     break;
1639                 default:
1640                     break;
1641             }
1642             break;
1643 
1644         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF:
1645             switch (hfp_gsm_call_status()){
1646                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1647                     switch (hfp_gsm_callsetup_status()){
1648                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1649                             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, 0, 0, NULL);
1650                             hfp_ag_response_and_hold_active = true;
1651                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1652                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1653                             // as with regular call
1654                             hfp_ag_set_call_indicator();
1655                             hfp_ag_set_callsetup_indicator();
1656                             hfp_ag_hf_accept_call(hfp_connection);
1657                             log_info("AG response and hold - hold by HF");
1658                             break;
1659                         default:
1660                             break;
1661                     }
1662                     break;
1663                 default:
1664                     break;
1665             }
1666             break;
1667 
1668         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG:
1669         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF:
1670             if (!hfp_ag_response_and_hold_active) break;
1671             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1672             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, 0, 0, NULL);
1673             hfp_ag_response_and_hold_active = false;
1674             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED;
1675             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1676             log_info("Held Call accepted and active");
1677             break;
1678 
1679         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG:
1680         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF:
1681             if (!hfp_ag_response_and_hold_active) break;
1682             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1683             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, 0, 0, NULL);
1684             hfp_ag_response_and_hold_active = false;
1685             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1686             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1687             // from terminate by ag
1688             hfp_ag_set_call_indicator();
1689             hfp_ag_trigger_terminate_call();
1690             break;
1691 
1692         case HFP_AG_TERMINATE_CALL_BY_HF:
1693             switch (hfp_gsm_call_status()){
1694                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1695                     switch (hfp_gsm_callsetup_status()){
1696                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1697                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1698                             hfp_ag_set_callsetup_indicator();
1699                             hfp_ag_transfer_callsetup_state();
1700                             hfp_ag_trigger_reject_call();
1701                             log_info("HF Rejected Incoming call, AG terminate call");
1702                             break;
1703                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1704                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1705                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1706                             hfp_ag_set_callsetup_indicator();
1707                             hfp_ag_transfer_callsetup_state();
1708                             log_info("AG terminate outgoing call process");
1709                             break;
1710                         default:
1711                             break;
1712                     }
1713                     break;
1714                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1715                     hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1716                     hfp_ag_set_callsetup_indicator();
1717                     hfp_ag_set_call_indicator();
1718                     hfp_ag_trigger_terminate_call();
1719                     log_info("AG terminate call");
1720                     break;
1721                 default:
1722                     break;
1723             }
1724             break;
1725 
1726         case HFP_AG_TERMINATE_CALL_BY_AG:
1727             switch (hfp_gsm_call_status()){
1728                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1729                     switch (hfp_gsm_callsetup_status()){
1730                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1731                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_AG, 0, 0, NULL);
1732                             hfp_ag_set_callsetup_indicator();
1733                             hfp_ag_trigger_reject_call();
1734                             log_info("AG Rejected Incoming call, AG terminate call");
1735                             break;
1736                         default:
1737                             break;
1738                     }
1739                     break;
1740                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1741                     hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_AG, 0, 0, NULL);
1742                     hfp_ag_set_callsetup_indicator();
1743                     hfp_ag_set_call_indicator();
1744                     hfp_ag_trigger_terminate_call();
1745                     log_info("AG terminate call");
1746                     break;
1747                 default:
1748                     break;
1749             }
1750             break;
1751         case HFP_AG_CALL_DROPPED:
1752             switch (hfp_gsm_call_status()){
1753                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1754                     switch (hfp_gsm_callsetup_status()){
1755                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1756                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1757                             hfp_ag_stop_ringing();
1758                             break;
1759                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1760                             log_info("Outgoing call interrupted\n");
1761                             break;
1762                         default:
1763                             break;
1764                     }
1765                     hfp_gsm_handler(HFP_AG_CALL_DROPPED, 0, 0, NULL);
1766                     hfp_ag_set_callsetup_indicator();
1767                     hfp_ag_transfer_callsetup_state();
1768                     hfp_ag_trigger_terminate_call();
1769                     break;
1770                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1771                     if (hfp_ag_response_and_hold_active) {
1772                         hfp_gsm_handler(HFP_AG_CALL_DROPPED, 0, 0, NULL);
1773                         hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1774                         hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1775                     }
1776                     hfp_gsm_handler(HFP_AG_CALL_DROPPED, 0, 0, NULL);
1777                     hfp_ag_set_callsetup_indicator();
1778                     hfp_ag_set_call_indicator();
1779                     hfp_ag_trigger_terminate_call();
1780                     log_info("AG notify call dropped");
1781                     break;
1782                 default:
1783                     break;
1784             }
1785             break;
1786 
1787         case HFP_AG_OUTGOING_CALL_INITIATED_BY_HF:
1788             // directly reject call if number of free slots is exceeded
1789             if (!hfp_gsm_call_possible()){
1790                 hfp_connection->send_error = 1;
1791                 hfp_ag_run_for_context(hfp_connection);
1792                 break;
1793             }
1794 
1795             // note: number not used currently
1796             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_INITIATED_BY_HF, 0, 0, (const char *) &hfp_connection->line_buffer[3]);
1797 
1798             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1799 
1800             hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, (const char *) &hfp_connection->line_buffer[3]);
1801             break;
1802 
1803         case HFP_AG_OUTGOING_CALL_INITIATED_BY_AG:
1804             // directly reject call if number of free slots is exceeded
1805             if (!hfp_gsm_call_possible()) {
1806                 // TODO: no error for user
1807                 break;
1808             }
1809             switch (hfp_gsm_call_status()) {
1810                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1811                     switch (hfp_gsm_callsetup_status()) {
1812                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1813                             // note: number not used currently
1814                             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_INITIATED_BY_AG, 0, 0, "1234567");
1815                             // init call state for all connections
1816                             hfp_ag_trigger_outgoing_call();
1817                             // get first one and accept call
1818                             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1819                             if (hfp_connection) {
1820                                 hfp_ag_handle_outgoing_call_accepted(hfp_connection);
1821                             }
1822                             break;
1823                         default:
1824                             // TODO: no error for user
1825                             break;
1826                     }
1827                     break;
1828                 default:
1829                     // TODO: no error for user
1830                     break;
1831             }
1832             break;
1833         case HFP_AG_OUTGOING_REDIAL_INITIATED:{
1834             // directly reject call if number of free slots is exceeded
1835             if (!hfp_gsm_call_possible()){
1836                 hfp_connection->send_error = 1;
1837                 hfp_ag_run_for_context(hfp_connection);
1838                 break;
1839             }
1840 
1841             hfp_gsm_handler(HFP_AG_OUTGOING_REDIAL_INITIATED, 0, 0, NULL);
1842             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1843 
1844             log_info("Redial last number");
1845             char * last_dialed_number = hfp_gsm_last_dialed_number();
1846 
1847             if (strlen(last_dialed_number) > 0){
1848                 log_info("Last number exists: accept call");
1849                 hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, last_dialed_number);
1850             } else {
1851                 log_info("log_infoLast number missing: reject call");
1852                 hfp_ag_handle_reject_outgoing_call();
1853             }
1854             break;
1855         }
1856         case HFP_AG_OUTGOING_CALL_REJECTED:
1857             hfp_ag_handle_reject_outgoing_call();
1858             break;
1859 
1860         case HFP_AG_OUTGOING_CALL_ACCEPTED:{
1861             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1862             if (!hfp_connection){
1863                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1864                 break;
1865             }
1866 
1867             hfp_connection->ok_pending = 1;
1868             hfp_ag_handle_outgoing_call_accepted(hfp_connection);
1869             break;
1870         }
1871         case HFP_AG_OUTGOING_CALL_RINGING:
1872             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1873             if (!hfp_connection){
1874                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in dialing state");
1875                 break;
1876             }
1877 
1878             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_RINGING, 0, 0, NULL);
1879             hfp_connection->call_state = HFP_CALL_OUTGOING_RINGING;
1880             hfp_ag_set_callsetup_indicator();
1881             hfp_ag_transfer_callsetup_state();
1882             hfp_ag_hf_start_ringing_outgoing(hfp_connection);
1883             break;
1884 
1885         case HFP_AG_OUTGOING_CALL_ESTABLISHED:{
1886             // get outgoing call
1887             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_RINGING);
1888             if (!hfp_connection){
1889                 hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1890             }
1891             if (!hfp_connection){
1892                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection");
1893                 break;
1894             }
1895 
1896             bool callheld_status_call_on_hold_and_no_active_calls = hfp_gsm_callheld_status() == HFP_CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS;
1897             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_ESTABLISHED, 0, 0, NULL);
1898             hfp_connection->call_state = HFP_CALL_ACTIVE;
1899             hfp_ag_set_callsetup_indicator();
1900             hfp_ag_set_call_indicator();
1901             hfp_ag_transfer_call_state();
1902             hfp_ag_transfer_callsetup_state();
1903             if (callheld_status_call_on_hold_and_no_active_calls){
1904                 hfp_ag_set_callheld_indicator();
1905                 hfp_ag_transfer_callheld_state();
1906             }
1907             hfp_ag_hf_stop_ringing(hfp_connection);
1908             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_ANSWERED);
1909             break;
1910         }
1911 
1912         case HFP_AG_CALL_HOLD_USER_BUSY:
1913             hfp_gsm_handler(HFP_AG_CALL_HOLD_USER_BUSY, 0, 0, NULL);
1914             hfp_ag_set_callsetup_indicator();
1915             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1916             hfp_connection->call_state = HFP_CALL_ACTIVE;
1917             log_info("AG: Call Waiting, User Busy");
1918             break;
1919 
1920         case HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1921             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1922             int call_held = hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1923 
1924             // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1925             if (call_held || call_setup_in_progress){
1926                 hfp_gsm_handler(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index,
1927                                 0, NULL);
1928 
1929             }
1930 
1931             if (call_setup_in_progress){
1932                 log_info("AG: Call Dropped, Accept new call");
1933                 hfp_ag_set_callsetup_indicator();
1934                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1935             } else {
1936                 log_info("AG: Call Dropped, Resume held call");
1937             }
1938             if (call_held){
1939                 hfp_ag_set_callheld_indicator();
1940                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1941             }
1942 
1943             hfp_connection->call_state = HFP_CALL_ACTIVE;
1944             break;
1945         }
1946 
1947         case HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1948             // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1949             // only update if callsetup changed
1950             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1951             hfp_gsm_handler(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index, 0,
1952                             NULL);
1953 
1954             if (call_setup_in_progress){
1955                 log_info("AG: Call on Hold, Accept new call");
1956                 hfp_ag_set_callsetup_indicator();
1957                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1958             } else {
1959                 log_info("AG: Swap calls");
1960             }
1961 
1962             hfp_ag_set_callheld_indicator();
1963             // hfp_ag_set_callheld_state(HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED);
1964             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1965             hfp_connection->call_state = HFP_CALL_ACTIVE;
1966             break;
1967         }
1968 
1969         case HFP_AG_CALL_HOLD_ADD_HELD_CALL:
1970             // Adds a held call to the conversation.
1971             if (hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD){
1972                 log_info("AG: Join 3-way-call");
1973                 hfp_gsm_handler(HFP_AG_CALL_HOLD_ADD_HELD_CALL, 0, 0, NULL);
1974                 hfp_ag_set_callheld_indicator();
1975                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1976                 hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CONFERENCE_CALL);
1977             }
1978             hfp_connection->call_state = HFP_CALL_ACTIVE;
1979             break;
1980         case HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS:
1981             // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer)
1982             hfp_gsm_handler(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, 0, 0, NULL);
1983             log_info("AG: Transfer call -> Connect two calls and disconnect");
1984             hfp_ag_set_call_indicator();
1985             hfp_ag_set_callheld_indicator();
1986             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1987             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1988             hfp_connection->call_state = HFP_CALL_IDLE;
1989             break;
1990 
1991         default:
1992             break;
1993     }
1994 
1995 
1996 }
1997 
1998 
1999 static void hfp_ag_send_call_status(hfp_connection_t * hfp_connection, int call_index){
2000     hfp_gsm_call_t * active_call = hfp_gsm_call(call_index);
2001     if (!active_call) return;
2002 
2003     int idx = active_call->index;
2004     hfp_enhanced_call_dir_t dir = active_call->direction;
2005     hfp_enhanced_call_status_t status = active_call->enhanced_status;
2006     hfp_enhanced_call_mode_t mode = active_call->mode;
2007     hfp_enhanced_call_mpty_t mpty = active_call->mpty;
2008     uint8_t type = active_call->clip_type;
2009     char * number = active_call->clip_number;
2010 
2011     char buffer[100];
2012     // TODO: check length of a buffer, to fit the MTU
2013     int offset = snprintf(buffer, sizeof(buffer), "\r\n%s: %d,%d,%d,%d,%d", HFP_LIST_CURRENT_CALLS, idx, dir, status, mode, mpty);
2014     if (number){
2015         offset += snprintf(buffer+offset, sizeof(buffer)-offset-3, ", \"%s\",%u", number, type);
2016     }
2017     snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n");
2018     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,
2019        mode, mpty, type, number);
2020     send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
2021 }
2022 
2023 // sends pending command, returns if command was sent
2024 static int hfp_ag_send_commands(hfp_connection_t *hfp_connection){
2025     if (hfp_connection->send_status_of_current_calls){
2026         hfp_connection->ok_pending = 0;
2027         if (hfp_connection->next_call_index < hfp_gsm_get_number_of_calls()){
2028             hfp_connection->next_call_index++;
2029             hfp_ag_send_call_status(hfp_connection, hfp_connection->next_call_index);
2030             return 1;
2031         } else {
2032             // TODO: this code should be removed. check a) before setting send_status_of_current_calls, or b) right before hfp_ag_send_call_status above
2033             hfp_connection->next_call_index = 0;
2034             hfp_connection->ok_pending = 1;
2035             hfp_connection->send_status_of_current_calls = 0;
2036         }
2037     }
2038 
2039     if (hfp_connection->ag_notify_incoming_call_waiting){
2040         hfp_connection->ag_notify_incoming_call_waiting = 0;
2041         hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
2042         return 1;
2043     }
2044 
2045     if (hfp_connection->send_error){
2046         hfp_connection->send_error = 0;
2047         hfp_connection->command = HFP_CMD_NONE;
2048         hfp_ag_send_error(hfp_connection->rfcomm_cid);
2049         return 1;
2050     }
2051 
2052     // note: before update AG indicators and ok_pending
2053     if (hfp_connection->send_response_and_hold_status){
2054         int status = hfp_connection->send_response_and_hold_status - 1;
2055         hfp_connection->send_response_and_hold_status = 0;
2056         hfp_ag_send_set_response_and_hold(hfp_connection->rfcomm_cid, status);
2057         return 1;
2058     }
2059 
2060     if (hfp_connection->ok_pending){
2061         hfp_connection->ok_pending = 0;
2062         hfp_connection->command = HFP_CMD_NONE;
2063         hfp_ag_send_ok(hfp_connection->rfcomm_cid);
2064         return 1;
2065     }
2066 
2067     // update AG indicators
2068     if (hfp_connection->ag_indicators_status_update_bitmap){
2069         int i;
2070         for (i=0;i<hfp_connection->ag_indicators_nr;i++){
2071             if (get_bit(hfp_connection->ag_indicators_status_update_bitmap, i)){
2072                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, i, 0);
2073                 if (!hfp_connection->enable_status_update_for_ag_indicators) {
2074                     log_info("+CMER:3,0,0,0 - not sending update for '%s'", hfp_ag_indicators[i].name);
2075                     break;
2076                 }
2077                 hfp_ag_send_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[i]);
2078                 return 1;
2079             }
2080         }
2081     }
2082 
2083     if (hfp_connection->ag_send_no_carrier){
2084         hfp_connection->ag_send_no_carrier = false;
2085         hfp_ag_send_no_carrier(hfp_connection->rfcomm_cid);
2086         return 1;
2087     }
2088 
2089     if (hfp_connection->send_phone_number_for_voice_tag){
2090         hfp_connection->send_phone_number_for_voice_tag = 0;
2091         hfp_connection->command = HFP_CMD_NONE;
2092         hfp_connection->ok_pending = 1;
2093         hfp_ag_send_phone_number_for_voice_tag_cmd(hfp_connection->rfcomm_cid);
2094         return 1;
2095     }
2096 
2097     if (hfp_connection->send_subscriber_number){
2098         if (hfp_connection->next_subscriber_number_to_send < hfp_ag_subscriber_numbers_count){
2099             hfp_phone_number_t phone = hfp_ag_subscriber_numbers[hfp_connection->next_subscriber_number_to_send++];
2100             hfp_send_subscriber_number_cmd(hfp_connection->rfcomm_cid, phone.type, phone.number);
2101         } else {
2102             hfp_connection->send_subscriber_number = 0;
2103             hfp_connection->next_subscriber_number_to_send = 0;
2104             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
2105         }
2106         hfp_connection->command = HFP_CMD_NONE;
2107         return 1;
2108     }
2109 
2110     if (hfp_connection->send_microphone_gain){
2111         hfp_connection->send_microphone_gain = 0;
2112         hfp_connection->command = HFP_CMD_NONE;
2113         hfp_ag_send_set_microphone_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->microphone_gain);
2114         return 1;
2115     }
2116 
2117     if (hfp_connection->send_speaker_gain){
2118         hfp_connection->send_speaker_gain = 0;
2119         hfp_connection->command = HFP_CMD_NONE;
2120         hfp_ag_send_set_speaker_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->speaker_gain);
2121         return 1;
2122     }
2123 
2124     if (hfp_connection->send_ag_status_indicators){
2125         hfp_connection->send_ag_status_indicators = 0;
2126         hfp_ag_send_retrieve_indicators_status_cmd(hfp_connection->rfcomm_cid);
2127         return 1;
2128     }
2129 
2130     return 0;
2131 }
2132 
2133 // sends pending command, returns if command was sent
2134 static int hfp_ag_run_ring_and_clip(hfp_connection_t *hfp_connection){
2135     // delay RING/CLIP until audio connection has been established for incoming calls
2136     // hfp_ag_hf_trigger_ring_and_clip is called in call_setup_state_machine
2137     if (hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING){
2138         if (hfp_connection->ag_ring){
2139             hfp_connection->ag_ring = 0;
2140             hfp_connection->command = HFP_CMD_NONE;
2141             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_RING);
2142             hfp_ag_send_ring(hfp_connection->rfcomm_cid);
2143             return 1;
2144         }
2145 
2146         if (hfp_connection->ag_send_clip){
2147             hfp_connection->ag_send_clip = 0;
2148             hfp_connection->command = HFP_CMD_NONE;
2149             hfp_ag_send_clip(hfp_connection->rfcomm_cid);
2150             return 1;
2151         }
2152     }
2153     return 0;
2154 }
2155 
2156 static void hfp_ag_run_for_context(hfp_connection_t *hfp_connection){
2157 
2158 	btstack_assert(hfp_connection != NULL);
2159 	btstack_assert(hfp_connection->local_role == HFP_ROLE_AG);
2160 
2161 	// during SDP query, RFCOMM CID is not set
2162 	if (hfp_connection->rfcomm_cid == 0) return;
2163 
2164     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED && hfp_connection->emit_vra_enabled_after_audio_established){
2165         hfp_connection->emit_vra_enabled_after_audio_established = false;
2166         hfp_emit_voice_recognition_enabled(hfp_connection, ERROR_CODE_SUCCESS);
2167     }
2168 
2169     if ((hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) && hfp_connection->release_audio_connection){
2170         hfp_connection->state = HFP_W4_SCO_DISCONNECTED;
2171         hfp_connection->release_audio_connection = 0;
2172         gap_disconnect(hfp_connection->sco_handle);
2173         return;
2174     }
2175 
2176     // configure NBS/WBS if needed using vendor-specific HCI commands
2177     if (hci_can_send_command_packet_now()) {
2178 #ifdef ENABLE_CC256X_ASSISTED_HFP
2179         // WBS Disassociate
2180         if (hfp_connection->cc256x_send_wbs_disassociate){
2181             hfp_connection->cc256x_send_wbs_disassociate = false;
2182             hci_send_cmd(&hci_ti_wbs_disassociate);
2183             return;
2184         }
2185         // Write Codec Config
2186         if (hfp_connection->cc256x_send_write_codec_config){
2187             hfp_connection->cc256x_send_write_codec_config = false;
2188             hfp_cc256x_write_codec_config(hfp_connection);
2189             return;
2190         }
2191         // WBS Associate
2192         if (hfp_connection->cc256x_send_wbs_associate){
2193             hfp_connection->cc256x_send_wbs_associate = false;
2194             hci_send_cmd(&hci_ti_wbs_associate, hfp_connection->acl_handle);
2195             return;
2196         }
2197 #endif
2198 #ifdef ENABLE_BCM_PCM_WBS
2199         // Enable WBS
2200         if (hfp_connection->bcm_send_enable_wbs){
2201             hfp_connection->bcm_send_enable_wbs = false;
2202             hci_send_cmd(&hci_bcm_enable_wbs, 1, 2);
2203             return;
2204         }
2205         // Write I2S/PCM params
2206         if (hfp_connection->bcm_send_write_i2spcm_interface_param){
2207             hfp_connection->bcm_send_write_i2spcm_interface_param = false;
2208             hfp_bcm_write_i2spcm_interface_param(hfp_connection);
2209             return;
2210         }
2211         // Disable WBS
2212         if (hfp_connection->bcm_send_disable_wbs){
2213             hfp_connection->bcm_send_disable_wbs = false;
2214             hci_send_cmd(&hci_bcm_enable_wbs, 0, 2);
2215             return;
2216         }
2217 #endif
2218 #ifdef ENABLE_RTK_PCM_WBS
2219         // Configure CVSD vs. mSBC
2220         if (hfp_connection->rtk_send_sco_config){
2221             hfp_connection->rtk_send_sco_config = false;
2222             if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
2223                 log_info("RTK SCO: 16k + mSBC");
2224                 hci_send_cmd(&hci_rtk_configure_sco_routing, 0x81, 0x90, 0x00, 0x00, 0x1a, 0x0c, 0x00, 0x00, 0x41);
2225             } else {
2226                 log_info("RTK SCO: 16k + CVSD");
2227                 hci_send_cmd(&hci_rtk_configure_sco_routing, 0x81, 0x90, 0x00, 0x00, 0x1a, 0x0c, 0x0c, 0x00, 0x01);
2228             }
2229             return;
2230         }
2231 #endif
2232     }
2233 
2234 #if defined (ENABLE_CC256X_ASSISTED_HFP) || defined (ENABLE_BCM_PCM_WBS)
2235     if (hfp_connection->state == HFP_W4_WBS_SHUTDOWN){
2236         hfp_finalize_connection_context(hfp_connection);
2237         return;
2238     }
2239 #endif
2240 
2241     if (!rfcomm_can_send_packet_now(hfp_connection->rfcomm_cid)) {
2242         log_info("hfp_ag_run_for_context: request can send for 0x%02x", hfp_connection->rfcomm_cid);
2243         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
2244         return;
2245     }
2246 
2247     int cmd_sent = hfp_ag_send_commands(hfp_connection);
2248 
2249     if (!cmd_sent){
2250         cmd_sent = hfp_ag_run_for_context_service_level_connection(hfp_connection);
2251     }
2252 
2253     if (!cmd_sent){
2254         cmd_sent = hfp_ag_run_for_context_service_level_connection_queries(hfp_connection);
2255     }
2256 
2257     if (!cmd_sent){
2258         cmd_sent = call_setup_state_machine(hfp_connection);
2259     }
2260 
2261     if (!cmd_sent){
2262         cmd_sent = hfp_ag_run_for_audio_connection(hfp_connection);
2263     }
2264 
2265     if (!cmd_sent){
2266         cmd_sent = hfp_ag_run_ring_and_clip(hfp_connection);
2267     }
2268 
2269     if (!cmd_sent){
2270         cmd_sent = hfp_ag_voice_recognition_state_machine(hfp_connection);
2271     }
2272 
2273     // disconnect
2274     if (!cmd_sent && (hfp_connection->command == HFP_CMD_NONE) && (hfp_connection->state == HFP_W2_DISCONNECT_RFCOMM)){
2275         hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED;
2276         rfcomm_disconnect(hfp_connection->rfcomm_cid);
2277     }
2278 
2279     if (cmd_sent){
2280         hfp_connection->command = HFP_CMD_NONE;
2281         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
2282     }
2283 }
2284 
2285 static int hfp_parser_is_end_of_line(uint8_t byte){
2286     return (byte == '\n') || (byte == '\r');
2287 }
2288 
2289 static void hfp_ag_handle_rfcomm_data(hfp_connection_t * hfp_connection, uint8_t *packet, uint16_t size){
2290     // assertion: size >= 1 as rfcomm.c does not deliver empty packets
2291     if (size < 1) return;
2292     uint8_t status = ERROR_CODE_SUCCESS;
2293 
2294     hfp_log_rfcomm_message("HFP_AG_RX", packet, size);
2295 #ifdef ENABLE_HFP_AT_MESSAGES
2296     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_RECEIVED, (char *) packet);
2297 #endif
2298 
2299     // process messages byte-wise
2300     int pos;
2301     for (pos = 0; pos < size ; pos++){
2302         hfp_parse(hfp_connection, packet[pos], 0);
2303 
2304         // parse until end of line
2305         if (!hfp_parser_is_end_of_line(packet[pos])) continue;
2306 
2307         hfp_generic_status_indicator_t * indicator;
2308         switch(hfp_connection->command){
2309             case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
2310                 hfp_connection->command = HFP_CMD_NONE;
2311                 hfp_connection->ag_vra_requested_by_hf = true;
2312                 break;
2313             case HFP_CMD_RESPONSE_AND_HOLD_QUERY:
2314                 hfp_connection->command = HFP_CMD_NONE;
2315                 if (hfp_ag_response_and_hold_active){
2316                     hfp_connection->send_response_and_hold_status = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD + 1;
2317                 }
2318                 hfp_connection->ok_pending = 1;
2319                 break;
2320             case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
2321                 hfp_connection->command = HFP_CMD_NONE;
2322                 switch(hfp_connection->ag_response_and_hold_action){
2323                     case HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD:
2324                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, hfp_connection);
2325                         break;
2326                     case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED:
2327                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF, hfp_connection);
2328                         break;
2329                     case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED:
2330                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF, hfp_connection);
2331                         break;
2332                     default:
2333                         break;
2334                 }
2335                 hfp_connection->ok_pending = 1;
2336                 break;
2337             case HFP_CMD_HF_INDICATOR_STATUS:
2338                 hfp_connection->command = HFP_CMD_NONE;
2339 
2340                 if (hfp_connection->parser_indicator_index < hfp_ag_generic_status_indicators_nr){
2341                     indicator = &hfp_ag_generic_status_indicators[hfp_connection->parser_indicator_index];
2342                     switch (indicator->uuid){
2343                         case HFP_HF_INDICATOR_UUID_ENHANCED_SAFETY:
2344                             if (hfp_connection->parser_indicator_value > 1) {
2345                                 hfp_connection->send_error = 1;
2346                                 break;
2347                             }
2348                             hfp_connection->ok_pending = 1;
2349                             hfp_ag_emit_hf_indicator_value(hfp_connection, indicator->uuid, hfp_connection->parser_indicator_value);
2350                             break;
2351                         case HFP_HF_INDICATOR_UUID_BATTERY_LEVEL:
2352                             if (hfp_connection->parser_indicator_value > 100){
2353                                 hfp_connection->send_error = 1;
2354                                 break;
2355                             }
2356                             hfp_connection->ok_pending = 1;
2357                             hfp_ag_emit_hf_indicator_value(hfp_connection, indicator->uuid, hfp_connection->parser_indicator_value);
2358                             break;
2359                         default:
2360                             hfp_connection->send_error = 1;
2361                             break;
2362                     }
2363                 } else {
2364                     hfp_connection->send_error = 1;
2365                 }
2366                 break;
2367             case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
2368                 // expected by SLC state machine
2369                 if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) break;
2370                 hfp_connection->send_ag_indicators_segment = 0;
2371                 hfp_connection->send_ag_status_indicators = 1;
2372                 break;
2373             case HFP_CMD_LIST_CURRENT_CALLS:
2374                 hfp_connection->command = HFP_CMD_NONE;
2375                 hfp_connection->next_call_index = 0;
2376                 hfp_connection->send_status_of_current_calls = 1;
2377                 break;
2378             case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
2379                 hfp_connection->command = HFP_CMD_NONE;
2380                 if (hfp_ag_subscriber_numbers_count == 0){
2381                     hfp_ag_send_ok(hfp_connection->rfcomm_cid);
2382                     break;
2383                 }
2384                 hfp_connection->next_subscriber_number_to_send = 0;
2385                 hfp_connection->send_subscriber_number = 1;
2386                 break;
2387             case HFP_CMD_TRANSMIT_DTMF_CODES:
2388             {
2389                 hfp_connection->command = HFP_CMD_NONE;
2390                 char buffer[2];
2391                 buffer[0] = (char) hfp_connection->ag_dtmf_code;
2392                 buffer[1] = 0;
2393                 hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_TRANSMIT_DTMF_CODES, buffer);
2394                 break;
2395             }
2396             case HFP_CMD_HF_REQUEST_PHONE_NUMBER:
2397                 hfp_connection->command = HFP_CMD_NONE;
2398                 hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_ATTACH_NUMBER_TO_VOICE_TAG);
2399                 break;
2400             case HFP_CMD_TURN_OFF_EC_AND_NR:
2401                 hfp_connection->command = HFP_CMD_NONE;
2402 
2403                 if (get_bit(hfp_ag_supported_features, HFP_AGSF_EC_NR_FUNCTION)){
2404                     hfp_connection->ok_pending = 1;
2405                     hfp_ag_supported_features = store_bit(hfp_ag_supported_features, HFP_AGSF_EC_NR_FUNCTION, hfp_connection->ag_echo_and_noise_reduction);
2406                     status = ERROR_CODE_SUCCESS;
2407                 } else {
2408                     hfp_connection->send_error = 1;
2409                     status = ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
2410                 }
2411                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_ECHO_CANCELING_AND_NOISE_REDUCTION_DEACTIVATE, status);
2412                 break;
2413             case HFP_CMD_CALL_ANSWERED:
2414                 hfp_connection->command = HFP_CMD_NONE;
2415                 log_info("HFP: ATA");
2416                 hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, hfp_connection);
2417                 break;
2418             case HFP_CMD_HANG_UP_CALL:
2419                 hfp_connection->command = HFP_CMD_NONE;
2420                 hfp_connection->ok_pending = 1;
2421                 hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_HF, hfp_connection);
2422                 break;
2423             case HFP_CMD_CALL_HOLD: {
2424                 hfp_connection->command = HFP_CMD_NONE;
2425                 hfp_connection->ok_pending = 1;
2426 
2427                 switch (hfp_connection->ag_call_hold_action){
2428                     case 0:
2429                         // Releases all held calls or sets User Determined User Busy (UDUB) for a waiting call.
2430                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_USER_BUSY, hfp_connection);
2431                         break;
2432                     case 1:
2433                         // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
2434                         // Where both a held and a waiting call exist, the above procedures shall apply to the
2435                         // waiting call (i.e., not to the held call) in conflicting situation.
2436                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
2437                         break;
2438                     case 2:
2439                         // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
2440                         // Where both a held and a waiting call exist, the above procedures shall apply to the
2441                         // waiting call (i.e., not to the held call) in conflicting situation.
2442                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
2443                         break;
2444                     case 3:
2445                         // Adds a held call to the conversation.
2446                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_ADD_HELD_CALL, hfp_connection);
2447                         break;
2448                     case 4:
2449                         // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer).
2450                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, hfp_connection);
2451                         break;
2452                     default:
2453                         break;
2454                 }
2455 				hfp_connection->call_index = 0;
2456                 break;
2457             }
2458             case HFP_CMD_CALL_PHONE_NUMBER:
2459                 hfp_connection->command = HFP_CMD_NONE;
2460                 hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED_BY_HF, hfp_connection);
2461                 break;
2462             case HFP_CMD_REDIAL_LAST_NUMBER:
2463                 hfp_connection->command = HFP_CMD_NONE;
2464                 hfp_ag_call_sm(HFP_AG_OUTGOING_REDIAL_INITIATED, hfp_connection);
2465                 break;
2466             case HFP_CMD_ENABLE_CLIP:
2467                 hfp_connection->command = HFP_CMD_NONE;
2468                 log_info("hfp: clip set, now: %u", hfp_connection->clip_enabled);
2469                 hfp_connection->ok_pending = 1;
2470                 break;
2471             case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
2472                 hfp_connection->command = HFP_CMD_NONE;
2473                 log_info("hfp: call waiting notification set, now: %u", hfp_connection->call_waiting_notification_enabled);
2474                 hfp_connection->ok_pending = 1;
2475                 break;
2476             case HFP_CMD_SET_SPEAKER_GAIN:
2477                 hfp_connection->command = HFP_CMD_NONE;
2478                 hfp_connection->ok_pending = 1;
2479                 log_info("HF speaker gain = %u", hfp_connection->speaker_gain);
2480                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_SPEAKER_VOLUME, hfp_connection->speaker_gain);
2481                 break;
2482             case HFP_CMD_SET_MICROPHONE_GAIN:
2483                 hfp_connection->command = HFP_CMD_NONE;
2484                 hfp_connection->ok_pending = 1;
2485                 log_info("HF microphone gain = %u", hfp_connection->microphone_gain);
2486                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_MICROPHONE_VOLUME, hfp_connection->microphone_gain);
2487                 break;
2488             case HFP_CMD_UNKNOWN:
2489                 hfp_connection->command = HFP_CMD_NONE;
2490                 hfp_connection->send_error = 1;
2491                 break;
2492             default:
2493                 break;
2494         }
2495     }
2496 }
2497 
2498 static void hfp_ag_run(void){
2499     btstack_linked_list_iterator_t it;
2500     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2501     while (btstack_linked_list_iterator_has_next(&it)){
2502         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2503         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2504         hfp_ag_run_for_context(hfp_connection);
2505     }
2506 }
2507 
2508 static void hfp_ag_rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2509     hfp_connection_t * hfp_connection = NULL;
2510     switch (packet_type){
2511         case RFCOMM_DATA_PACKET:
2512             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(channel);
2513             btstack_assert(hfp_connection != NULL);
2514 
2515             hfp_ag_handle_rfcomm_data(hfp_connection, packet, size);
2516             hfp_ag_run_for_context(hfp_connection);
2517             return;
2518         case HCI_EVENT_PACKET:
2519             if (packet[0] == RFCOMM_EVENT_CAN_SEND_NOW){
2520                 uint16_t rfcomm_cid = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
2521                 hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
2522                 btstack_assert(hfp_connection != NULL);
2523 
2524                 hfp_ag_run_for_context(hfp_connection);
2525                 return;
2526             }
2527             hfp_handle_rfcomm_event(packet_type, channel, packet, size, HFP_ROLE_AG);
2528             break;
2529         default:
2530             break;
2531     }
2532 
2533     hfp_ag_run();
2534 }
2535 
2536 static void hfp_ag_hci_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2537     hfp_handle_hci_event(packet_type, channel, packet, size, HFP_ROLE_AG);
2538     hfp_ag_run();
2539 }
2540 
2541 void hfp_ag_init_codecs(int codecs_nr, const uint8_t * codecs){
2542     if (codecs_nr > HFP_MAX_NUM_CODECS){
2543         log_error("hfp_init: codecs_nr (%d) > HFP_MAX_NUM_CODECS (%d)", codecs_nr, HFP_MAX_NUM_CODECS);
2544         return;
2545     }
2546     int i;
2547     hfp_ag_codecs_nr = codecs_nr;
2548     for (i=0; i < codecs_nr; i++){
2549         hfp_ag_codecs[i] = codecs[i];
2550     }
2551 }
2552 
2553 void hfp_ag_init_supported_features(uint32_t supported_features){
2554     hfp_ag_supported_features = supported_features;
2555 }
2556 
2557 void hfp_ag_init_ag_indicators(int ag_indicators_nr, const hfp_ag_indicator_t * ag_indicators){
2558     hfp_ag_indicators_nr = ag_indicators_nr;
2559     (void)memcpy(hfp_ag_indicators, ag_indicators,
2560                  ag_indicators_nr * sizeof(hfp_ag_indicator_t));
2561 }
2562 
2563 void hfp_ag_init_hf_indicators(int hf_indicators_nr, const hfp_generic_status_indicator_t * hf_indicators){
2564     if (hf_indicators_nr > HFP_MAX_NUM_INDICATORS) return;
2565     hfp_ag_generic_status_indicators_nr = hf_indicators_nr;
2566     (void)memcpy(hfp_ag_generic_status_indicators, hf_indicators,
2567                  hf_indicators_nr * sizeof(hfp_generic_status_indicator_t));
2568 }
2569 
2570 void hfp_ag_init_call_hold_services(int call_hold_services_nr, const char * call_hold_services[]){
2571     hfp_ag_call_hold_services_nr = call_hold_services_nr;
2572     (void)memcpy(hfp_ag_call_hold_services, call_hold_services,
2573                  call_hold_services_nr * sizeof(char *));
2574 }
2575 
2576 
2577 void hfp_ag_init(uint16_t rfcomm_channel_nr){
2578 
2579     hfp_init();
2580     hfp_ag_call_hold_services_nr = 0;
2581     hfp_ag_response_and_hold_active = false;
2582     hfp_ag_indicators_nr = 0;
2583     hfp_ag_codecs_nr = 0;
2584     hfp_ag_supported_features = HFP_DEFAULT_AG_SUPPORTED_FEATURES;
2585     hfp_ag_subscriber_numbers = NULL;
2586     hfp_ag_subscriber_numbers_count = 0;
2587 
2588     hfp_ag_hci_event_callback_registration.callback = &hfp_ag_hci_event_packet_handler;
2589     hci_add_event_handler(&hfp_ag_hci_event_callback_registration);
2590 
2591     rfcomm_register_service(&hfp_ag_rfcomm_packet_handler, rfcomm_channel_nr, 0xffff);
2592 
2593     // used to set packet handler for outgoing rfcomm connections - could be handled by emitting an event to us
2594     hfp_set_ag_rfcomm_packet_handler(&hfp_ag_rfcomm_packet_handler);
2595 
2596     hfp_gsm_init();
2597 }
2598 
2599 void hfp_ag_deinit(void){
2600     hfp_deinit();
2601     hfp_gsm_deinit();
2602 
2603     hfp_ag_callback = NULL;
2604     hfp_ag_supported_features = 0;
2605     hfp_ag_codecs_nr = 0;
2606     hfp_ag_indicators_nr = 0;
2607     hfp_ag_call_hold_services_nr = 0;
2608     (void) memset(&hfp_ag_call_hold_services, 0, sizeof(hfp_ag_call_hold_services));
2609     hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
2610     (void) memset(&hfp_ag_response_and_hold_state, 0, sizeof(hfp_response_and_hold_state_t));
2611     hfp_ag_subscriber_numbers = NULL;
2612     (void) memset(&hfp_ag_hci_event_callback_registration, 0, sizeof(btstack_packet_callback_registration_t));
2613     hfp_ag_custom_call_sm_handler = NULL;
2614 }
2615 
2616 uint8_t hfp_ag_establish_service_level_connection(bd_addr_t bd_addr){
2617     return hfp_establish_service_level_connection(bd_addr, BLUETOOTH_SERVICE_CLASS_HANDSFREE, HFP_ROLE_AG);
2618 }
2619 
2620 uint8_t hfp_ag_release_service_level_connection(hci_con_handle_t acl_handle){
2621     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2622     if (!hfp_connection){
2623         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2624     }
2625 
2626     hfp_trigger_release_service_level_connection(hfp_connection);
2627     hfp_ag_run_for_context(hfp_connection);
2628     return ERROR_CODE_SUCCESS;
2629 }
2630 
2631 uint8_t hfp_ag_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle, hfp_cme_error_t error){
2632     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2633     if (!hfp_connection){
2634         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2635     }
2636 
2637     hfp_connection->extended_audio_gateway_error = 0;
2638     if (!hfp_connection->enable_extended_audio_gateway_error_report){
2639         return ERROR_CODE_COMMAND_DISALLOWED;
2640     }
2641 
2642     hfp_connection->extended_audio_gateway_error = error;
2643     hfp_ag_run_for_context(hfp_connection);
2644     return ERROR_CODE_SUCCESS;
2645 }
2646 
2647 static uint8_t hfp_ag_setup_audio_connection(hfp_connection_t * hfp_connection){
2648     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
2649         return ERROR_CODE_COMMAND_DISALLOWED;
2650     }
2651     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO){
2652         return ERROR_CODE_COMMAND_DISALLOWED;
2653     }
2654 
2655     hfp_connection->establish_audio_connection = 1;
2656     if (!has_codec_negotiation_feature(hfp_connection)){
2657         log_info("hfp_ag_establish_audio_connection - no codec negotiation feature, using CVSD");
2658         hfp_connection->negotiated_codec = HFP_CODEC_CVSD;
2659         hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
2660         // now, pick link settings
2661         hfp_init_link_settings(hfp_connection, hfp_ag_esco_s4_supported(hfp_connection));
2662 #ifdef ENABLE_CC256X_ASSISTED_HFP
2663         hfp_cc256x_prepare_for_sco(hfp_connection);
2664 #endif
2665         return ERROR_CODE_SUCCESS;
2666     }
2667 
2668     uint8_t i;
2669     bool codec_was_in_use = false;
2670     bool better_codec_can_be_used = false;
2671 
2672     for (i = 0; i<hfp_connection->remote_codecs_nr; i++){
2673         if (hfp_connection->negotiated_codec == hfp_connection->remote_codecs[i]){
2674             codec_was_in_use = true;
2675         } else if (hfp_connection->negotiated_codec < hfp_connection->remote_codecs[i]){
2676             better_codec_can_be_used = true;
2677         }
2678     }
2679 
2680     if (!codec_was_in_use || better_codec_can_be_used){
2681         hfp_connection->ag_send_common_codec = true;
2682         hfp_connection->codecs_state = HFP_CODECS_IDLE;
2683     }
2684     return ERROR_CODE_SUCCESS;
2685 }
2686 
2687 uint8_t hfp_ag_establish_audio_connection(hci_con_handle_t acl_handle){
2688     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2689     if (!hfp_connection){
2690         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2691     }
2692     uint8_t status = hfp_ag_setup_audio_connection(hfp_connection);
2693     if (status != ERROR_CODE_SUCCESS){
2694         return status;
2695     }
2696     hfp_ag_run_for_context(hfp_connection);
2697     return ERROR_CODE_SUCCESS;
2698 }
2699 
2700 uint8_t hfp_ag_release_audio_connection(hci_con_handle_t acl_handle){
2701     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2702     if (!hfp_connection){
2703         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2704     }
2705 
2706     if (hfp_connection->vra_state == HFP_VRA_VOICE_RECOGNITION_ACTIVATED){
2707         return ERROR_CODE_COMMAND_DISALLOWED;
2708     }
2709 
2710     uint8_t status = hfp_trigger_release_audio_connection(hfp_connection);
2711     if (status == ERROR_CODE_SUCCESS){
2712         hfp_ag_run_for_context(hfp_connection);
2713     }
2714     return status;
2715 }
2716 
2717 /**
2718  * @brief Enable in-band ring tone
2719  */
2720 void hfp_ag_set_use_in_band_ring_tone(int use_in_band_ring_tone){
2721     if (get_bit(hfp_ag_supported_features, HFP_AGSF_IN_BAND_RING_TONE) == use_in_band_ring_tone){
2722         return;
2723     }
2724 
2725     hfp_ag_supported_features = store_bit(hfp_ag_supported_features, HFP_AGSF_IN_BAND_RING_TONE, use_in_band_ring_tone);
2726 
2727     btstack_linked_list_iterator_t it;
2728     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2729     while (btstack_linked_list_iterator_has_next(&it)){
2730         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2731         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2732         hfp_connection->ag_send_in_band_ring_tone_setting = true;
2733         hfp_ag_run_for_context(hfp_connection);
2734     }
2735 }
2736 
2737 /**
2738  * @brief Called from GSM
2739  */
2740 void hfp_ag_incoming_call(void){
2741     hfp_ag_call_sm(HFP_AG_INCOMING_CALL, NULL);
2742 }
2743 
2744 void hfp_ag_outgoing_call_initiated(const char * number) {
2745     UNUSED(number);
2746     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED_BY_AG, NULL);
2747 }
2748 
2749 /**
2750  * @brief number is stored.
2751  */
2752 void hfp_ag_set_clip(uint8_t type, const char * number){
2753     hfp_gsm_handler(HFP_AG_SET_CLIP, 0, type, number);
2754 }
2755 
2756 void hfp_ag_call_dropped(void){
2757     hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2758 }
2759 
2760 // call from AG UI
2761 void hfp_ag_answer_incoming_call(void){
2762     hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, NULL);
2763 }
2764 
2765 void hfp_ag_join_held_call(void){
2766     hfp_ag_call_sm(HFP_AG_HELD_CALL_JOINED_BY_AG, NULL);
2767 }
2768 
2769 void hfp_ag_terminate_call(void){
2770     hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_AG, NULL);
2771 }
2772 
2773 void hfp_ag_outgoing_call_ringing(void){
2774     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_RINGING, NULL);
2775 }
2776 
2777 void hfp_ag_outgoing_call_established(void){
2778     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ESTABLISHED, NULL);
2779 }
2780 
2781 void hfp_ag_outgoing_call_rejected(void){
2782     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_REJECTED, NULL);
2783 }
2784 
2785 void hfp_ag_outgoing_call_accepted(void){
2786     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ACCEPTED, NULL);
2787 }
2788 
2789 void hfp_ag_hold_incoming_call(void){
2790     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, NULL);
2791 }
2792 
2793 void hfp_ag_accept_held_incoming_call(void) {
2794     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, NULL);
2795 }
2796 
2797 void hfp_ag_reject_held_incoming_call(void){
2798     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, NULL);
2799 }
2800 
2801 static void hfp_ag_set_ag_indicator(const char * name, int value){
2802     int indicator_index = get_ag_indicator_index_for_name(name);
2803     if (indicator_index < 0) return;
2804     hfp_ag_indicators[indicator_index].status = value;
2805 
2806     btstack_linked_list_iterator_t it;
2807     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2808     while (btstack_linked_list_iterator_has_next(&it)){
2809         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2810         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2811         if (!hfp_connection->ag_indicators[indicator_index].enabled) {
2812             log_info("Requested AG indicator '%s' update to %u, but it is not enabled", hfp_ag_indicators[indicator_index].name, value);
2813             continue;
2814         }
2815         log_info("AG indicator '%s' changed to %u, request transfer status", hfp_ag_indicators[indicator_index].name, value);
2816         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
2817         hfp_ag_run_for_context(hfp_connection);
2818     }
2819 }
2820 
2821 uint8_t hfp_ag_set_registration_status(int registration_status){
2822     if ((registration_status < 0) || (registration_status > 1)){
2823         return ERROR_CODE_COMMAND_DISALLOWED;
2824     }
2825 
2826     if ( (registration_status == 0) && (hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
2827 
2828         // if network goes away wihle a call is active:
2829         // - the  call gets dropped
2830         // - we send NO CARRIER
2831         // NOTE: the CALL=0 has to be sent before NO CARRIER
2832 
2833         hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2834 
2835         btstack_linked_list_iterator_t it;
2836         btstack_linked_list_iterator_init(&it, hfp_get_connections());
2837         while (btstack_linked_list_iterator_has_next(&it)){
2838             hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2839             hfp_connection->ag_send_no_carrier = true;
2840         }
2841     }
2842     hfp_ag_set_ag_indicator("service", registration_status);
2843     return ERROR_CODE_SUCCESS;
2844 }
2845 
2846 uint8_t hfp_ag_set_signal_strength(int signal_strength){
2847     if ((signal_strength < 0) || (signal_strength > 5)){
2848         return ERROR_CODE_COMMAND_DISALLOWED;
2849     }
2850 
2851     hfp_ag_set_ag_indicator("signal", signal_strength);
2852     return ERROR_CODE_SUCCESS;
2853 }
2854 
2855 uint8_t hfp_ag_set_roaming_status(int roaming_status){
2856     if ((roaming_status < 0) || (roaming_status > 1)){
2857         return ERROR_CODE_COMMAND_DISALLOWED;
2858     }
2859 
2860     hfp_ag_set_ag_indicator("roam", roaming_status);
2861     return ERROR_CODE_SUCCESS;
2862 }
2863 
2864 uint8_t hfp_ag_set_battery_level(int battery_level){
2865     if ((battery_level < 0) || (battery_level > 5)){
2866         return ERROR_CODE_COMMAND_DISALLOWED;
2867     }
2868     hfp_ag_set_ag_indicator("battchg", battery_level);
2869     return ERROR_CODE_SUCCESS;
2870 }
2871 
2872 uint8_t hfp_ag_activate_voice_recognition(hci_con_handle_t acl_handle){
2873     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2874     if (!hfp_connection){
2875         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2876     }
2877 
2878     if (hfp_connection->emit_vra_enabled_after_audio_established){
2879         return ERROR_CODE_COMMAND_DISALLOWED;
2880     }
2881 
2882     bool enhanced_vra_supported = hfp_ag_enhanced_vra_flag_supported(hfp_connection);
2883     bool legacy_vra_supported   = hfp_ag_vra_flag_supported(hfp_connection);
2884     if (!enhanced_vra_supported && !legacy_vra_supported){
2885         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
2886     }
2887 
2888     if (!hfp_ag_can_activate_voice_recognition(hfp_connection)){
2889         return ERROR_CODE_COMMAND_DISALLOWED;
2890     }
2891 
2892     hfp_connection->ag_activate_voice_recognition_value = 1;
2893     hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED;
2894     hfp_connection->enhanced_voice_recognition_enabled = enhanced_vra_supported;
2895     hfp_connection->ag_audio_connection_opened_before_vra = hfp_ag_is_audio_connection_active(hfp_connection);
2896     hfp_connection->ag_vra_state = HFP_VOICE_RECOGNITION_STATE_AG_READY;
2897     hfp_connection->ag_vra_send_command = true;
2898     hfp_ag_run_for_context(hfp_connection);
2899     return ERROR_CODE_SUCCESS;
2900 }
2901 
2902 uint8_t hfp_ag_deactivate_voice_recognition(hci_con_handle_t acl_handle){
2903     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2904     if (!hfp_connection){
2905         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2906     }
2907 
2908     if (hfp_connection->emit_vra_enabled_after_audio_established){
2909         return ERROR_CODE_COMMAND_DISALLOWED;
2910     }
2911 
2912     bool enhanced_vra_supported = hfp_ag_enhanced_vra_flag_supported(hfp_connection);
2913     bool legacy_vra_supported = hfp_ag_vra_flag_supported(hfp_connection);
2914 
2915     if (!enhanced_vra_supported && !legacy_vra_supported){
2916         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
2917     }
2918 
2919     if (!hfp_ag_voice_recognition_session_active(hfp_connection)){
2920         return ERROR_CODE_COMMAND_DISALLOWED;
2921     }
2922 
2923     hfp_connection->ag_activate_voice_recognition_value = 0;
2924     hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF;
2925     hfp_connection->ag_vra_state = HFP_VOICE_RECOGNITION_STATE_AG_READY;
2926     hfp_connection->ag_vra_send_command = true;
2927     hfp_ag_run_for_context(hfp_connection);
2928     return ERROR_CODE_SUCCESS;
2929 }
2930 
2931 static uint8_t hfp_ag_enhanced_voice_recognition_send_state(hci_con_handle_t acl_handle, hfp_voice_recognition_state_t state){
2932     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2933     if (!hfp_connection){
2934         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2935     }
2936 
2937     if (hfp_connection->emit_vra_enabled_after_audio_established){
2938         return ERROR_CODE_COMMAND_DISALLOWED;
2939     }
2940 
2941     if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED){
2942         return ERROR_CODE_COMMAND_DISALLOWED;
2943     }
2944 
2945     if (hfp_connection->vra_state != HFP_VRA_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO){
2946         return ERROR_CODE_COMMAND_DISALLOWED;
2947     }
2948 
2949     bool enhanced_vra_supported = hfp_ag_enhanced_vra_flag_supported(hfp_connection);
2950     if (!enhanced_vra_supported ){
2951         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
2952     }
2953 
2954 
2955     hfp_connection->ag_vra_state = state;
2956     hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_STATUS;
2957     hfp_connection->ag_vra_send_command = true;
2958     hfp_ag_run_for_context(hfp_connection);
2959     return ERROR_CODE_SUCCESS;
2960 }
2961 
2962 uint8_t hfp_ag_enhanced_voice_recognition_report_sending_audio(hci_con_handle_t acl_handle){
2963     return hfp_ag_enhanced_voice_recognition_send_state(acl_handle, HFP_VOICE_RECOGNITION_STATE_AG_IS_STARTING_SOUND);
2964 }
2965 uint8_t hfp_ag_enhanced_voice_recognition_report_ready_for_audio(hci_con_handle_t acl_handle){
2966     return hfp_ag_enhanced_voice_recognition_send_state(acl_handle, HFP_VOICE_RECOGNITION_STATE_AG_READY_TO_ACCEPT_AUDIO_INPUT);
2967 }
2968 uint8_t hfp_ag_enhanced_voice_recognition_report_processing_input(hci_con_handle_t acl_handle){
2969     return hfp_ag_enhanced_voice_recognition_send_state(acl_handle, HFP_VOICE_RECOGNITION_STATE_AG_IS_PROCESSING_AUDIO_INPUT);
2970 }
2971 
2972 
2973 uint8_t hfp_ag_enhanced_voice_recognition_send_message(hci_con_handle_t acl_handle, hfp_voice_recognition_state_t state, hfp_voice_recognition_message_t msg){
2974     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2975     if (!hfp_connection){
2976         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2977     }
2978 
2979     if (hfp_connection->emit_vra_enabled_after_audio_established){
2980         return ERROR_CODE_COMMAND_DISALLOWED;
2981     }
2982 
2983     if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED){
2984         return ERROR_CODE_COMMAND_DISALLOWED;
2985     }
2986 
2987     if (hfp_connection->vra_state != HFP_VRA_ENHANCED_VOICE_RECOGNITION_READY_FOR_AUDIO){
2988         return ERROR_CODE_COMMAND_DISALLOWED;
2989     }
2990 
2991     bool enhanced_vra_supported = hfp_ag_enhanced_vra_flag_supported(hfp_connection);
2992     if (!enhanced_vra_supported ){
2993         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
2994     }
2995 
2996     bool enhanced_vra_msg_supported = hfp_ag_can_send_enhanced_vra_message_flag_supported(hfp_connection);
2997     if (!enhanced_vra_msg_supported ){
2998         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
2999     }
3000 
3001     uint16_t message_len = strlen(msg.text);
3002 
3003     if (message_len > HFP_MAX_VR_TEXT_SIZE){
3004         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
3005     }
3006 
3007     if ((HFP_VR_TEXT_HEADER_SIZE + message_len) > hfp_connection->rfcomm_mtu){
3008         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
3009     }
3010 
3011     hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_MSG;
3012     hfp_connection->ag_msg = msg;
3013     hfp_connection->ag_vra_state = state;
3014     hfp_connection->ag_vra_send_command = true;
3015     hfp_ag_run_for_context(hfp_connection);
3016 
3017     return ERROR_CODE_SUCCESS;
3018 }
3019 
3020 
3021 uint8_t hfp_ag_set_microphone_gain(hci_con_handle_t acl_handle, int gain){
3022     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
3023     if (!hfp_connection){
3024         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3025     }
3026 
3027     if ((gain < 0) || (gain > 15)){
3028         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
3029         return ERROR_CODE_COMMAND_DISALLOWED;
3030     }
3031 
3032     if (hfp_connection->microphone_gain != gain){
3033         hfp_connection->microphone_gain = gain;
3034         hfp_connection->send_microphone_gain = 1;
3035     }
3036     hfp_ag_run_for_context(hfp_connection);
3037     return ERROR_CODE_SUCCESS;
3038 }
3039 
3040 uint8_t hfp_ag_set_speaker_gain(hci_con_handle_t acl_handle, int gain){
3041     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
3042     if (!hfp_connection){
3043         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3044     }
3045 
3046     if ((gain < 0) || (gain > 15)){
3047         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
3048         return ERROR_CODE_COMMAND_DISALLOWED;
3049     }
3050 
3051     if (hfp_connection->speaker_gain != gain){
3052         hfp_connection->speaker_gain = gain;
3053         hfp_connection->send_speaker_gain = 1;
3054     }
3055     hfp_ag_run_for_context(hfp_connection);
3056     return ERROR_CODE_SUCCESS;
3057 }
3058 
3059 uint8_t hfp_ag_send_phone_number_for_voice_tag(hci_con_handle_t acl_handle, const char * number){
3060     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
3061     if (!hfp_connection){
3062         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3063     }
3064 
3065     hfp_ag_set_clip(0, number);
3066     hfp_connection->send_phone_number_for_voice_tag = 1;
3067     return ERROR_CODE_SUCCESS;
3068 }
3069 
3070 uint8_t hfp_ag_reject_phone_number_for_voice_tag(hci_con_handle_t acl_handle){
3071     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
3072     if (!hfp_connection){
3073         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3074     }
3075 
3076     hfp_connection->send_error = 1;
3077     return ERROR_CODE_SUCCESS;
3078 }
3079 
3080 uint8_t hfp_ag_send_dtmf_code_done(hci_con_handle_t acl_handle){
3081     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
3082     if (!hfp_connection){
3083         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3084     }
3085 
3086     hfp_connection->ok_pending = 1;
3087     return ERROR_CODE_SUCCESS;
3088 }
3089 
3090 void hfp_ag_set_subcriber_number_information(hfp_phone_number_t * numbers, int numbers_count){
3091     hfp_ag_subscriber_numbers = numbers;
3092     hfp_ag_subscriber_numbers_count = numbers_count;
3093 }
3094 
3095 void hfp_ag_clear_last_dialed_number(void){
3096     hfp_gsm_clear_last_dialed_number();
3097 }
3098 
3099 void hfp_ag_set_last_dialed_number(const char * number){
3100     hfp_gsm_set_last_dialed_number(number);
3101 }
3102 
3103 uint8_t hfp_ag_notify_incoming_call_waiting(hci_con_handle_t acl_handle){
3104     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
3105     if (!hfp_connection){
3106         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3107     }
3108 
3109     if (!hfp_connection->call_waiting_notification_enabled){
3110         return ERROR_CODE_COMMAND_DISALLOWED;
3111     }
3112 
3113     hfp_connection->ag_notify_incoming_call_waiting = 1;
3114     hfp_ag_run_for_context(hfp_connection);
3115     return ERROR_CODE_SUCCESS;
3116 }
3117 
3118 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){
3119 	if (!name){
3120 		name = hfp_ag_default_service_name;
3121 	}
3122 	hfp_create_sdp_record(service, service_record_handle, BLUETOOTH_SERVICE_CLASS_HANDSFREE_AUDIO_GATEWAY, rfcomm_channel_nr, name);
3123 
3124 	/*
3125 	 * 0x01 – Ability to reject a call
3126 	 * 0x00 – No ability to reject a call
3127 	 */
3128 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0301);    // Hands-Free Profile - Network
3129 	de_add_number(service, DE_UINT, DE_SIZE_8, ability_to_reject_call);
3130 
3131 	// Construct SupportedFeatures for SDP bitmap:
3132 	//
3133 	// "The values of the “SupportedFeatures” bitmap given in Table 5.4 shall be the same as the values
3134 	//  of the Bits 0 to 4 of the unsolicited result code +BRSF"
3135 	//
3136 	// Wide band speech (bit 5) requires Codec negotiation
3137 	//
3138 	uint16_t sdp_features = supported_features & 0x1f;
3139 	if ( (wide_band_speech == 1) && (supported_features & (1 << HFP_AGSF_CODEC_NEGOTIATION))){
3140 		sdp_features |= 1 << 5;
3141 	}
3142 
3143     if (supported_features & (1 << HFP_AGSF_ENHANCED_VOICE_RECOGNITION_STATUS)){
3144         sdp_features |= 1 << 6;
3145     }
3146 
3147     if (supported_features & (1 << HFP_AGSF_VOICE_RECOGNITION_TEXT)){
3148         sdp_features |= 1 << 7;
3149     }
3150 
3151 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);    // Hands-Free Profile - SupportedFeatures
3152 	de_add_number(service, DE_UINT, DE_SIZE_16, sdp_features);
3153 }
3154 
3155 void hfp_ag_register_packet_handler(btstack_packet_handler_t callback){
3156 	btstack_assert(callback != NULL);
3157 
3158 	hfp_ag_callback = callback;
3159 	hfp_set_ag_callback(callback);
3160 }
3161 
3162 void hfp_ag_register_custom_call_sm_handler(bool (*handler)(hfp_ag_call_event_t event)){
3163     hfp_ag_custom_call_sm_handler = handler;
3164 }
3165