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