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