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