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