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