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