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