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