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