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