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