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