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