xref: /btstack/src/classic/hfp_ag.c (revision fb75b4837d503b49a86932e1653b6a867dd74b40)
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     }
1332 }
1333 
1334 static void hfp_ag_set_call_indicator(void){
1335     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("call");
1336     if (!indicator){
1337         log_error("hfp_ag_set_call_state: call indicator is missing");
1338         return;
1339     };
1340     indicator->status = hfp_gsm_call_status();
1341 }
1342 
1343 static void hfp_ag_stop_ringing(void){
1344     btstack_linked_list_iterator_t it;
1345     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1346     while (btstack_linked_list_iterator_has_next(&it)){
1347         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1348         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1349         if ((hfp_connection->call_state != HFP_CALL_INCOMING_RINGING) &&
1350             (hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
1351         hfp_ag_hf_stop_ringing(hfp_connection);
1352     }
1353 }
1354 
1355 static hfp_connection_t * hfp_ag_connection_for_call_state(hfp_call_state_t call_state){
1356     btstack_linked_list_iterator_t it;
1357     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1358     while (btstack_linked_list_iterator_has_next(&it)){
1359         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1360         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1361         if (hfp_connection->call_state == call_state) return hfp_connection;
1362     }
1363     return NULL;
1364 }
1365 
1366 static void hfp_ag_send_response_and_hold_state(hfp_response_and_hold_state_t state){
1367     btstack_linked_list_iterator_t it;
1368     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1369     while (btstack_linked_list_iterator_has_next(&it)){
1370         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1371         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1372         hfp_connection->send_response_and_hold_status = state + 1;
1373     }
1374 }
1375 
1376 static int call_setup_state_machine(hfp_connection_t * hfp_connection){
1377     int indicator_index;
1378     switch (hfp_connection->call_state){
1379         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING:
1380             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1381             // we got event: audio hfp_connection established
1382             hfp_timeout_start(hfp_connection);
1383             hfp_connection->ag_ring = 1;
1384             hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
1385             hfp_connection->call_state = HFP_CALL_INCOMING_RINGING;
1386             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_START_RINGING);
1387             break;
1388         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE:
1389             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1390             // we got event: audio hfp_connection established
1391             hfp_connection->call_state = HFP_CALL_ACTIVE;
1392             break;
1393         case HFP_CALL_W2_SEND_CALL_WAITING:
1394             hfp_connection->call_state = HFP_CALL_W4_CHLD;
1395             hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1396             indicator_index = get_ag_indicator_index_for_name("callsetup");
1397             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1398             break;
1399         default:
1400             break;
1401     }
1402     return 0;
1403 }
1404 
1405 // functions extracted from hfp_ag_call_sm below
1406 static void hfp_ag_handle_reject_outgoing_call(void){
1407     hfp_connection_t * hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1408     if (!hfp_connection){
1409         log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1410         return;
1411     }
1412 
1413     hfp_gsm_handler(HFP_AG_OUTGOING_CALL_REJECTED, 0, 0, NULL);
1414     hfp_connection->call_state = HFP_CALL_IDLE;
1415     hfp_connection->send_error = 1;
1416     hfp_ag_run_for_context(hfp_connection);
1417 }
1418 
1419 // hfp_connection is used to identify originating HF
1420 static void hfp_ag_call_sm(hfp_ag_call_event_t event, hfp_connection_t * hfp_connection){
1421     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1422     int callheld_indicator_index = get_ag_indicator_index_for_name("callheld");
1423     int call_indicator_index = get_ag_indicator_index_for_name("call");
1424 
1425     switch (event){
1426         case HFP_AG_INCOMING_CALL:
1427             switch (hfp_gsm_call_status()){
1428                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1429                     switch (hfp_gsm_callsetup_status()){
1430                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1431                             hfp_gsm_handler(HFP_AG_INCOMING_CALL, 0, 0, NULL);
1432                             hfp_ag_set_callsetup_indicator();
1433                             hfp_ag_trigger_incoming_call();
1434                             log_info("AG rings");
1435                             break;
1436                         default:
1437                             break;
1438                     }
1439                     break;
1440                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1441                     switch (hfp_gsm_callsetup_status()){
1442                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1443                             hfp_gsm_handler(HFP_AG_INCOMING_CALL, 0, 0, NULL);
1444                             hfp_ag_set_callsetup_indicator();
1445                             hfp_ag_trigger_incoming_call();
1446                             log_info("AG call waiting");
1447                             break;
1448                         default:
1449                             break;
1450                     }
1451                     break;
1452                 default:
1453                     break;
1454             }
1455             break;
1456         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG:
1457             switch (hfp_gsm_call_status()){
1458                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1459                     switch (hfp_gsm_callsetup_status()){
1460                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1461                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, 0, 0, NULL);
1462                             hfp_ag_set_call_indicator();
1463                             hfp_ag_set_callsetup_indicator();
1464                             hfp_ag_ag_accept_call();
1465                             log_info("AG answers call, accept call by GSM");
1466                             break;
1467                         default:
1468                             break;
1469                     }
1470                     break;
1471                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1472                     switch (hfp_gsm_callsetup_status()){
1473                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1474                             log_info("AG: current call is placed on hold, incoming call gets active");
1475                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, 0, 0, NULL);
1476                             hfp_ag_set_callsetup_indicator();
1477                             hfp_ag_set_callheld_indicator();
1478                             hfp_ag_transfer_callsetup_state();
1479                             hfp_ag_transfer_callheld_state();
1480                             break;
1481                         default:
1482                             break;
1483                     }
1484                     break;
1485                 default:
1486                     break;
1487             }
1488             break;
1489 
1490         case HFP_AG_HELD_CALL_JOINED_BY_AG:
1491             switch (hfp_gsm_call_status()){
1492                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1493                     switch (hfp_gsm_callheld_status()){
1494                         case HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED:
1495                             log_info("AG: joining held call with active call");
1496                             hfp_gsm_handler(HFP_AG_HELD_CALL_JOINED_BY_AG, 0, 0, NULL);
1497                             hfp_ag_set_callheld_indicator();
1498                             hfp_ag_transfer_callheld_state();
1499                             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CONFERENCE_CALL);
1500                             break;
1501                         default:
1502                             break;
1503                     }
1504                     break;
1505                 default:
1506                     break;
1507             }
1508             break;
1509 
1510         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF:
1511             switch (hfp_gsm_call_status()){
1512                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1513                     switch (hfp_gsm_callsetup_status()){
1514                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1515                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, 0, 0, NULL);
1516                             hfp_ag_set_callsetup_indicator();
1517                             hfp_ag_set_call_indicator();
1518                             hfp_ag_hf_accept_call(hfp_connection);
1519                             hfp_connection->ok_pending = 1;
1520                             log_info("HF answers call, accept call by GSM");
1521                             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_ANSWERED);
1522                             break;
1523                         default:
1524                             break;
1525                     }
1526                     break;
1527                 default:
1528                     break;
1529             }
1530             break;
1531 
1532         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG:
1533             switch (hfp_gsm_call_status()){
1534                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1535                     switch (hfp_gsm_callsetup_status()){
1536                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1537                             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, 0, 0, NULL);
1538                             hfp_ag_response_and_hold_active = 1;
1539                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1540                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1541                             // as with regular call
1542                             hfp_ag_set_call_indicator();
1543                             hfp_ag_set_callsetup_indicator();
1544                             hfp_ag_ag_accept_call();
1545                             log_info("AG response and hold - hold by AG");
1546                             break;
1547                         default:
1548                             break;
1549                     }
1550                     break;
1551                 default:
1552                     break;
1553             }
1554             break;
1555 
1556         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF:
1557             switch (hfp_gsm_call_status()){
1558                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1559                     switch (hfp_gsm_callsetup_status()){
1560                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1561                             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, 0, 0, NULL);
1562                             hfp_ag_response_and_hold_active = 1;
1563                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1564                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1565                             // as with regular call
1566                             hfp_ag_set_call_indicator();
1567                             hfp_ag_set_callsetup_indicator();
1568                             hfp_ag_hf_accept_call(hfp_connection);
1569                             log_info("AG response and hold - hold by HF");
1570                             break;
1571                         default:
1572                             break;
1573                     }
1574                     break;
1575                 default:
1576                     break;
1577             }
1578             break;
1579 
1580         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG:
1581         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF:
1582             if (!hfp_ag_response_and_hold_active) break;
1583             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1584             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, 0, 0, NULL);
1585             hfp_ag_response_and_hold_active = 0;
1586             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED;
1587             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1588             log_info("Held Call accepted and active");
1589             break;
1590 
1591         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG:
1592         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF:
1593             if (!hfp_ag_response_and_hold_active) break;
1594             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1595             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, 0, 0, NULL);
1596             hfp_ag_response_and_hold_active = 0;
1597             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1598             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1599             // from terminate by ag
1600             hfp_ag_set_call_indicator();
1601             hfp_ag_trigger_terminate_call();
1602             break;
1603 
1604         case HFP_AG_TERMINATE_CALL_BY_HF:
1605             switch (hfp_gsm_call_status()){
1606                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1607                     switch (hfp_gsm_callsetup_status()){
1608                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1609                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1610                             hfp_ag_set_callsetup_indicator();
1611                             hfp_ag_transfer_callsetup_state();
1612                             hfp_ag_trigger_reject_call();
1613                             log_info("HF Rejected Incoming call, AG terminate call");
1614                             break;
1615                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1616                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1617                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1618                             hfp_ag_set_callsetup_indicator();
1619                             hfp_ag_transfer_callsetup_state();
1620                             log_info("AG terminate outgoing call process");
1621                             break;
1622                         default:
1623                             break;
1624                     }
1625                     break;
1626                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1627                     hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1628                     hfp_ag_set_callsetup_indicator();
1629                     hfp_ag_set_call_indicator();
1630                     hfp_ag_trigger_terminate_call();
1631                     log_info("AG terminate call");
1632                     break;
1633                 default:
1634                     break;
1635             }
1636             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_TERMINATED);
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             break;
1826         }
1827 
1828         case HFP_AG_CALL_HOLD_USER_BUSY:
1829             hfp_gsm_handler(HFP_AG_CALL_HOLD_USER_BUSY, 0, 0, NULL);
1830             hfp_ag_set_callsetup_indicator();
1831             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1832             hfp_connection->call_state = HFP_CALL_ACTIVE;
1833             log_info("AG: Call Waiting, User Busy");
1834             break;
1835 
1836         case HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1837             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1838             int call_held = hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1839 
1840             // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1841             if (call_held || call_setup_in_progress){
1842                 hfp_gsm_handler(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index,
1843                                 0, NULL);
1844 
1845             }
1846 
1847             if (call_setup_in_progress){
1848                 log_info("AG: Call Dropped, Accept new call");
1849                 hfp_ag_set_callsetup_indicator();
1850                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1851             } else {
1852                 log_info("AG: Call Dropped, Resume held call");
1853             }
1854             if (call_held){
1855                 hfp_ag_set_callheld_indicator();
1856                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1857             }
1858 
1859             hfp_connection->call_state = HFP_CALL_ACTIVE;
1860             break;
1861         }
1862 
1863         case HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1864             // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1865             // only update if callsetup changed
1866             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1867             hfp_gsm_handler(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index, 0,
1868                             NULL);
1869 
1870             if (call_setup_in_progress){
1871                 log_info("AG: Call on Hold, Accept new call");
1872                 hfp_ag_set_callsetup_indicator();
1873                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1874             } else {
1875                 log_info("AG: Swap calls");
1876             }
1877 
1878             hfp_ag_set_callheld_indicator();
1879             // hfp_ag_set_callheld_state(HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED);
1880             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1881             hfp_connection->call_state = HFP_CALL_ACTIVE;
1882             break;
1883         }
1884 
1885         case HFP_AG_CALL_HOLD_ADD_HELD_CALL:
1886             // Adds a held call to the conversation.
1887             if (hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD){
1888                 log_info("AG: Join 3-way-call");
1889                 hfp_gsm_handler(HFP_AG_CALL_HOLD_ADD_HELD_CALL, 0, 0, NULL);
1890                 hfp_ag_set_callheld_indicator();
1891                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1892                 hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CONFERENCE_CALL);
1893             }
1894             hfp_connection->call_state = HFP_CALL_ACTIVE;
1895             break;
1896         case HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS:
1897             // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer)
1898             hfp_gsm_handler(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, 0, 0, NULL);
1899             log_info("AG: Transfer call -> Connect two calls and disconnect");
1900             hfp_ag_set_call_indicator();
1901             hfp_ag_set_callheld_indicator();
1902             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1903             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1904             hfp_connection->call_state = HFP_CALL_IDLE;
1905             break;
1906 
1907         default:
1908             break;
1909     }
1910 
1911 
1912 }
1913 
1914 
1915 static void hfp_ag_send_call_status(hfp_connection_t * hfp_connection, int call_index){
1916     hfp_gsm_call_t * active_call = hfp_gsm_call(call_index);
1917     if (!active_call) return;
1918 
1919     int idx = active_call->index;
1920     hfp_enhanced_call_dir_t dir = active_call->direction;
1921     hfp_enhanced_call_status_t status = active_call->enhanced_status;
1922     hfp_enhanced_call_mode_t mode = active_call->mode;
1923     hfp_enhanced_call_mpty_t mpty = active_call->mpty;
1924     uint8_t type = active_call->clip_type;
1925     char * number = active_call->clip_number;
1926 
1927     char buffer[100];
1928     // TODO: check length of a buffer, to fit the MTU
1929     int offset = snprintf(buffer, sizeof(buffer), "\r\n%s: %d,%d,%d,%d,%d", HFP_LIST_CURRENT_CALLS, idx, dir, status, mode, mpty);
1930     if (number){
1931         offset += snprintf(buffer+offset, sizeof(buffer)-offset-3, ", \"%s\",%u", number, type);
1932     }
1933     snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n");
1934     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,
1935        mode, mpty, type, number);
1936     send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1937 }
1938 
1939 // sends pending command, returns if command was sent
1940 static int hfp_ag_send_commands(hfp_connection_t *hfp_connection){
1941     if (hfp_connection->send_status_of_current_calls){
1942         hfp_connection->ok_pending = 0;
1943         if (hfp_connection->next_call_index < hfp_gsm_get_number_of_calls()){
1944             hfp_connection->next_call_index++;
1945             hfp_ag_send_call_status(hfp_connection, hfp_connection->next_call_index);
1946             return 1;
1947         } else {
1948             // 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
1949             hfp_connection->next_call_index = 0;
1950             hfp_connection->ok_pending = 1;
1951             hfp_connection->send_status_of_current_calls = 0;
1952         }
1953     }
1954 
1955     if (hfp_connection->ag_notify_incoming_call_waiting){
1956         hfp_connection->ag_notify_incoming_call_waiting = 0;
1957         hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1958         return 1;
1959     }
1960 
1961     if (hfp_connection->command == HFP_CMD_UNKNOWN){
1962         hfp_connection->ok_pending = 0;
1963         hfp_connection->send_error = 0;
1964         hfp_connection->command = HFP_CMD_NONE;
1965         hfp_ag_send_error(hfp_connection->rfcomm_cid);
1966         return 1;
1967     }
1968 
1969     if (hfp_connection->send_error){
1970         hfp_connection->send_error = 0;
1971         hfp_connection->command = HFP_CMD_NONE;
1972         hfp_ag_send_error(hfp_connection->rfcomm_cid);
1973         return 1;
1974     }
1975 
1976     // note: before update AG indicators and ok_pending
1977     if (hfp_connection->send_response_and_hold_status){
1978         int status = hfp_connection->send_response_and_hold_status - 1;
1979         hfp_connection->send_response_and_hold_status = 0;
1980         hfp_ag_send_set_response_and_hold(hfp_connection->rfcomm_cid, status);
1981         return 1;
1982     }
1983 
1984     if (hfp_connection->ok_pending){
1985         hfp_connection->ok_pending = 0;
1986         hfp_connection->command = HFP_CMD_NONE;
1987         hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1988         return 1;
1989     }
1990 
1991     // update AG indicators
1992     if (hfp_connection->ag_indicators_status_update_bitmap){
1993         int i;
1994         for (i=0;i<hfp_connection->ag_indicators_nr;i++){
1995             if (get_bit(hfp_connection->ag_indicators_status_update_bitmap, i)){
1996                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, i, 0);
1997                 if (!hfp_connection->enable_status_update_for_ag_indicators) {
1998                     log_info("+CMER:3,0,0,0 - not sending update for '%s'", hfp_ag_indicators[i].name);
1999                     break;
2000                 }
2001                 hfp_ag_send_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[i]);
2002                 return 1;
2003             }
2004         }
2005     }
2006 
2007     if (hfp_connection->ag_send_no_carrier){
2008         hfp_connection->ag_send_no_carrier = false;
2009         hfp_ag_send_no_carrier(hfp_connection->rfcomm_cid);
2010         return 1;
2011     }
2012 
2013     if (hfp_connection->ag_ring){
2014         hfp_connection->ag_ring = 0;
2015         hfp_connection->command = HFP_CMD_NONE;
2016         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_RING);
2017         hfp_ag_send_ring(hfp_connection->rfcomm_cid);
2018         return 1;
2019     }
2020 
2021     if (hfp_connection->ag_send_clip){
2022         hfp_connection->ag_send_clip = 0;
2023         hfp_connection->command = HFP_CMD_NONE;
2024         hfp_ag_send_clip(hfp_connection->rfcomm_cid);
2025         return 1;
2026     }
2027 
2028     if (hfp_connection->send_phone_number_for_voice_tag){
2029         hfp_connection->send_phone_number_for_voice_tag = 0;
2030         hfp_connection->command = HFP_CMD_NONE;
2031         hfp_connection->ok_pending = 1;
2032         hfp_ag_send_phone_number_for_voice_tag_cmd(hfp_connection->rfcomm_cid);
2033         return 1;
2034     }
2035 
2036     if (hfp_connection->send_subscriber_number){
2037         if (hfp_connection->next_subscriber_number_to_send < hfp_ag_subscriber_numbers_count){
2038             hfp_phone_number_t phone = hfp_ag_subscriber_numbers[hfp_connection->next_subscriber_number_to_send++];
2039             hfp_send_subscriber_number_cmd(hfp_connection->rfcomm_cid, phone.type, phone.number);
2040         } else {
2041             hfp_connection->send_subscriber_number = 0;
2042             hfp_connection->next_subscriber_number_to_send = 0;
2043             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
2044         }
2045         hfp_connection->command = HFP_CMD_NONE;
2046         return 1;
2047     }
2048 
2049     if (hfp_connection->send_microphone_gain){
2050         hfp_connection->send_microphone_gain = 0;
2051         hfp_connection->command = HFP_CMD_NONE;
2052         hfp_ag_send_set_microphone_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->microphone_gain);
2053         return 1;
2054     }
2055 
2056     if (hfp_connection->send_speaker_gain){
2057         hfp_connection->send_speaker_gain = 0;
2058         hfp_connection->command = HFP_CMD_NONE;
2059         hfp_ag_send_set_speaker_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->speaker_gain);
2060         return 1;
2061     }
2062 
2063     if (hfp_connection->send_ag_status_indicators){
2064         hfp_connection->send_ag_status_indicators = 0;
2065         hfp_ag_send_retrieve_indicators_status_cmd(hfp_connection->rfcomm_cid);
2066         return 1;
2067     }
2068 
2069     return 0;
2070 }
2071 
2072 static void hfp_ag_run_for_context(hfp_connection_t *hfp_connection){
2073 
2074 	btstack_assert(hfp_connection != NULL);
2075 	btstack_assert(hfp_connection->local_role == HFP_ROLE_AG);
2076 
2077 	// during SDP query, RFCOMM CID is not set
2078 	if (hfp_connection->rfcomm_cid == 0) return;
2079 
2080     // assert command could be sent
2081     if (hci_can_send_command_packet_now() == 0) return;
2082 
2083     if ((hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) && hfp_connection->release_audio_connection){
2084         hfp_connection->state = HFP_W4_SCO_DISCONNECTED;
2085         hfp_connection->release_audio_connection = 0;
2086         gap_disconnect(hfp_connection->sco_handle);
2087         return;
2088     }
2089 
2090 #ifdef ENABLE_CC256X_ASSISTED_HFP
2091     // WBS Disassociate
2092     if (hfp_connection->cc256x_send_wbs_disassociate){
2093         hfp_connection->cc256x_send_wbs_disassociate = false;
2094         hci_send_cmd(&hci_ti_wbs_disassociate);
2095         return;
2096     }
2097     // Write Codec Config
2098     if (hfp_connection->cc256x_send_write_codec_config){
2099         hfp_connection->cc256x_send_write_codec_config = false;
2100         hfp_cc256x_write_codec_config(hfp_connection);
2101         return;
2102     }
2103     // WBS Associate
2104     if (hfp_connection->cc256x_send_wbs_associate){
2105         hfp_connection->cc256x_send_wbs_associate = false;
2106         hci_send_cmd(&hci_ti_wbs_associate, hfp_connection->acl_handle);
2107         return;
2108     }
2109 #endif
2110 #ifdef ENABLE_BCM_PCM_WBS
2111     // Enable WBS
2112     if (hfp_connection->bcm_send_enable_wbs){
2113         hfp_connection->bcm_send_enable_wbs = false;
2114         hci_send_cmd(&hci_bcm_enable_wbs, 1, 2);
2115         return;
2116     }
2117     // Write I2S/PCM params
2118     if (hfp_connection->bcm_send_write_i2spcm_interface_param){
2119         hfp_connection->bcm_send_write_i2spcm_interface_param = false;
2120         hfp_bcm_write_i2spcm_interface_param(hfp_connection);
2121         return;
2122     }
2123     // Disable WBS
2124     if (hfp_connection->bcm_send_disable_wbs){
2125         hfp_connection->bcm_send_disable_wbs = false;
2126         hci_send_cmd(&hci_bcm_enable_wbs, 0, 2);
2127         return;
2128     }
2129 #endif
2130 #if defined (ENABLE_CC256X_ASSISTED_HFP) || defined (ENABLE_BCM_PCM_WBS)
2131     if (hfp_connection->state == HFP_W4_WBS_SHUTDOWN){
2132         hfp_finalize_connection_context(hfp_connection);
2133         return;
2134     }
2135 #endif
2136 
2137     if (!rfcomm_can_send_packet_now(hfp_connection->rfcomm_cid)) {
2138         log_info("hfp_ag_run_for_context: request can send for 0x%02x", hfp_connection->rfcomm_cid);
2139         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
2140         return;
2141     }
2142 
2143     int cmd_sent = hfp_ag_send_commands(hfp_connection);
2144 
2145     if (!cmd_sent){
2146         cmd_sent = hfp_ag_run_for_context_service_level_connection(hfp_connection);
2147     }
2148 
2149     if (!cmd_sent){
2150         cmd_sent = hfp_ag_run_for_context_service_level_connection_queries(hfp_connection);
2151     }
2152 
2153     if (!cmd_sent){
2154         cmd_sent = call_setup_state_machine(hfp_connection);
2155     }
2156 
2157     // trigger codec exchange (must be before hfp_ag_run_for_audio_connection)
2158     if (!cmd_sent && (hfp_connection->command == HFP_CMD_NONE) && hfp_connection->trigger_codec_exchange){
2159         switch (hfp_connection->codecs_state){
2160             case HFP_CODECS_IDLE:
2161             case HFP_CODECS_RECEIVED_LIST:
2162             case HFP_CODECS_AG_RESEND_COMMON_CODEC:
2163             case HFP_CODECS_ERROR:
2164                 hfp_connection->trigger_codec_exchange = 0;
2165                 hfp_connection->command = HFP_CMD_AG_SEND_COMMON_CODEC;
2166                 break;
2167             default:
2168                 break;
2169         }
2170     }
2171 
2172     if (!cmd_sent){
2173         cmd_sent = hfp_ag_run_for_audio_connection(hfp_connection);
2174     }
2175 
2176     if (!cmd_sent){
2177         cmd_sent = hfp_ag_voice_recognition_state_machine(hfp_connection);
2178     }
2179 
2180     // disconnect
2181     if (!cmd_sent && (hfp_connection->command == HFP_CMD_NONE) && (hfp_connection->state == HFP_W2_DISCONNECT_RFCOMM)){
2182         hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED;
2183         rfcomm_disconnect(hfp_connection->rfcomm_cid);
2184     }
2185 
2186     if (cmd_sent){
2187         hfp_connection->command = HFP_CMD_NONE;
2188         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
2189     }
2190 }
2191 
2192 static int hfp_parser_is_end_of_line(uint8_t byte){
2193     return (byte == '\n') || (byte == '\r');
2194 }
2195 
2196 static void hfp_ag_handle_rfcomm_data(hfp_connection_t * hfp_connection, uint8_t *packet, uint16_t size){
2197     // assertion: size >= 1 as rfcomm.c does not deliver empty packets
2198     if (size < 1) return;
2199     uint8_t status = ERROR_CODE_SUCCESS;
2200 
2201     hfp_log_rfcomm_message("HFP_AG_RX", packet, size);
2202 #ifdef ENABLE_HFP_AT_MESSAGES
2203     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_RECEIVED, (char *) packet);
2204 #endif
2205 
2206     // process messages byte-wise
2207     int pos;
2208     for (pos = 0; pos < size ; pos++){
2209         hfp_parse(hfp_connection, packet[pos], 0);
2210 
2211         // parse until end of line
2212         if (!hfp_parser_is_end_of_line(packet[pos])) continue;
2213 
2214         hfp_generic_status_indicator_t * indicator;
2215         switch(hfp_connection->command){
2216             case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
2217                 // dealt with in hfp_ag_voice_recognition_state_machine
2218                 break;
2219             case HFP_CMD_RESPONSE_AND_HOLD_QUERY:
2220                 if (hfp_ag_response_and_hold_active){
2221                     hfp_connection->send_response_and_hold_status = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD + 1;
2222                 }
2223                 hfp_connection->ok_pending = 1;
2224                 break;
2225             case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
2226                 switch(hfp_connection->ag_response_and_hold_action){
2227                     case HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD:
2228                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, hfp_connection);
2229                         break;
2230                     case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED:
2231                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF, hfp_connection);
2232                         break;
2233                     case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED:
2234                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF, hfp_connection);
2235                         break;
2236                     default:
2237                         break;
2238                 }
2239                 hfp_connection->ok_pending = 1;
2240                 break;
2241             case HFP_CMD_HF_INDICATOR_STATUS:
2242                 hfp_connection->command = HFP_CMD_NONE;
2243 
2244                 if (hfp_connection->parser_indicator_index < hfp_ag_generic_status_indicators_nr){
2245                     indicator = &hfp_ag_generic_status_indicators[hfp_connection->parser_indicator_index];
2246                     switch (indicator->uuid){
2247                         case HFP_HF_INDICATOR_UUID_ENHANCED_SAFETY:
2248                             if (hfp_connection->parser_indicator_value > 1) {
2249                                 hfp_connection->send_error = 1;
2250                                 break;
2251                             }
2252                             hfp_connection->ok_pending = 1;
2253                             hfp_ag_emit_hf_indicator_value(hfp_connection, indicator->uuid, hfp_connection->parser_indicator_value);
2254                             break;
2255                         case HFP_HF_INDICATOR_UUID_BATTERY_LEVEL:
2256                             if (hfp_connection->parser_indicator_value > 100){
2257                                 hfp_connection->send_error = 1;
2258                                 break;
2259                             }
2260                             hfp_connection->ok_pending = 1;
2261                             hfp_ag_emit_hf_indicator_value(hfp_connection, indicator->uuid, hfp_connection->parser_indicator_value);
2262                             break;
2263                         default:
2264                             hfp_connection->send_error = 1;
2265                             break;
2266                     }
2267                 } else {
2268                     hfp_connection->send_error = 1;
2269                 }
2270                 break;
2271             case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
2272                 // expected by SLC state machine
2273                 if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) break;
2274                 hfp_connection->send_ag_indicators_segment = 0;
2275                 hfp_connection->send_ag_status_indicators = 1;
2276                 break;
2277             case HFP_CMD_LIST_CURRENT_CALLS:
2278                 hfp_connection->command = HFP_CMD_NONE;
2279                 hfp_connection->next_call_index = 0;
2280                 hfp_connection->send_status_of_current_calls = 1;
2281                 break;
2282             case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
2283                 if (hfp_ag_subscriber_numbers_count == 0){
2284                     hfp_ag_send_ok(hfp_connection->rfcomm_cid);
2285                     break;
2286                 }
2287                 hfp_connection->next_subscriber_number_to_send = 0;
2288                 hfp_connection->send_subscriber_number = 1;
2289                 break;
2290             case HFP_CMD_TRANSMIT_DTMF_CODES:
2291             {
2292                 hfp_connection->command = HFP_CMD_NONE;
2293                 char buffer[2];
2294                 buffer[0] = (char) hfp_connection->ag_dtmf_code;
2295                 buffer[1] = 0;
2296                 hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_TRANSMIT_DTMF_CODES, buffer);
2297                 break;
2298             }
2299             case HFP_CMD_HF_REQUEST_PHONE_NUMBER:
2300                 hfp_connection->command = HFP_CMD_NONE;
2301                 hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_ATTACH_NUMBER_TO_VOICE_TAG);
2302                 break;
2303             case HFP_CMD_TURN_OFF_EC_AND_NR:
2304                 hfp_connection->command = HFP_CMD_NONE;
2305 
2306                 if (get_bit(hfp_ag_supported_features, HFP_AGSF_EC_NR_FUNCTION)){
2307                     hfp_connection->ok_pending = 1;
2308                     hfp_ag_supported_features = store_bit(hfp_ag_supported_features, HFP_AGSF_EC_NR_FUNCTION, hfp_connection->ag_echo_and_noise_reduction);
2309                     status = ERROR_CODE_SUCCESS;
2310                 } else {
2311                     hfp_connection->send_error = 1;
2312                     status = ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
2313                 }
2314                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_ECHO_CANCELING_AND_NOISE_REDUCTION_DEACTIVATE, status);
2315                 break;
2316             case HFP_CMD_CALL_ANSWERED:
2317                 hfp_connection->command = HFP_CMD_NONE;
2318                 log_info("HFP: ATA");
2319                 hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, hfp_connection);
2320                 break;
2321             case HFP_CMD_HANG_UP_CALL:
2322                 hfp_connection->command = HFP_CMD_NONE;
2323                 hfp_connection->ok_pending = 1;
2324                 hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_HF, hfp_connection);
2325                 break;
2326             case HFP_CMD_CALL_HOLD: {
2327                 hfp_connection->command = HFP_CMD_NONE;
2328                 hfp_connection->ok_pending = 1;
2329 
2330                 switch (hfp_connection->ag_call_hold_action){
2331                     case 0:
2332                         // Releases all held calls or sets User Determined User Busy (UDUB) for a waiting call.
2333                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_USER_BUSY, hfp_connection);
2334                         break;
2335                     case 1:
2336                         // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
2337                         // Where both a held and a waiting call exist, the above procedures shall apply to the
2338                         // waiting call (i.e., not to the held call) in conflicting situation.
2339                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
2340                         break;
2341                     case 2:
2342                         // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
2343                         // Where both a held and a waiting call exist, the above procedures shall apply to the
2344                         // waiting call (i.e., not to the held call) in conflicting situation.
2345                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
2346                         break;
2347                     case 3:
2348                         // Adds a held call to the conversation.
2349                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_ADD_HELD_CALL, hfp_connection);
2350                         break;
2351                     case 4:
2352                         // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer).
2353                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, hfp_connection);
2354                         break;
2355                     default:
2356                         break;
2357                 }
2358 				hfp_connection->call_index = 0;
2359                 break;
2360             }
2361             case HFP_CMD_CALL_PHONE_NUMBER:
2362                 hfp_connection->command = HFP_CMD_NONE;
2363                 hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED_BY_HF, hfp_connection);
2364                 break;
2365             case HFP_CMD_REDIAL_LAST_NUMBER:
2366                 hfp_connection->command = HFP_CMD_NONE;
2367                 hfp_ag_call_sm(HFP_AG_OUTGOING_REDIAL_INITIATED, hfp_connection);
2368                 break;
2369             case HFP_CMD_ENABLE_CLIP:
2370                 hfp_connection->command = HFP_CMD_NONE;
2371                 log_info("hfp: clip set, now: %u", hfp_connection->clip_enabled);
2372                 hfp_connection->ok_pending = 1;
2373                 break;
2374             case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
2375                 hfp_connection->command = HFP_CMD_NONE;
2376                 log_info("hfp: call waiting notification set, now: %u", hfp_connection->call_waiting_notification_enabled);
2377                 hfp_connection->ok_pending = 1;
2378                 break;
2379             case HFP_CMD_SET_SPEAKER_GAIN:
2380                 hfp_connection->command = HFP_CMD_NONE;
2381                 hfp_connection->ok_pending = 1;
2382                 log_info("HF speaker gain = %u", hfp_connection->speaker_gain);
2383                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_SPEAKER_VOLUME, hfp_connection->speaker_gain);
2384                 break;
2385             case HFP_CMD_SET_MICROPHONE_GAIN:
2386                 hfp_connection->command = HFP_CMD_NONE;
2387                 hfp_connection->ok_pending = 1;
2388                 log_info("HF microphone gain = %u", hfp_connection->microphone_gain);
2389                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_MICROPHONE_VOLUME, hfp_connection->microphone_gain);
2390                 break;
2391             default:
2392                 break;
2393         }
2394     }
2395 }
2396 
2397 static void hfp_ag_run(void){
2398     btstack_linked_list_iterator_t it;
2399     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2400     while (btstack_linked_list_iterator_has_next(&it)){
2401         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2402         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2403         hfp_ag_run_for_context(hfp_connection);
2404     }
2405 }
2406 
2407 static void hfp_ag_rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2408     hfp_connection_t * hfp_connection = NULL;
2409     switch (packet_type){
2410         case RFCOMM_DATA_PACKET:
2411             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(channel);
2412             btstack_assert(hfp_connection != NULL);
2413 
2414             hfp_ag_handle_rfcomm_data(hfp_connection, packet, size);
2415             hfp_ag_run_for_context(hfp_connection);
2416             return;
2417         case HCI_EVENT_PACKET:
2418             if (packet[0] == RFCOMM_EVENT_CAN_SEND_NOW){
2419                 uint16_t rfcomm_cid = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
2420                 hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
2421                 btstack_assert(hfp_connection != NULL);
2422 
2423                 hfp_ag_run_for_context(hfp_connection);
2424                 return;
2425             }
2426             hfp_handle_rfcomm_event(packet_type, channel, packet, size, HFP_ROLE_AG);
2427             break;
2428         default:
2429             break;
2430     }
2431 
2432     hfp_ag_run();
2433 }
2434 
2435 static void hfp_ag_hci_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2436     hfp_handle_hci_event(packet_type, channel, packet, size, HFP_ROLE_AG);
2437     hfp_ag_run();
2438 }
2439 
2440 void hfp_ag_init_codecs(int codecs_nr, const uint8_t * codecs){
2441     if (codecs_nr > HFP_MAX_NUM_CODECS){
2442         log_error("hfp_init: codecs_nr (%d) > HFP_MAX_NUM_CODECS (%d)", codecs_nr, HFP_MAX_NUM_CODECS);
2443         return;
2444     }
2445     int i;
2446     hfp_ag_codecs_nr = codecs_nr;
2447     for (i=0; i < codecs_nr; i++){
2448         hfp_ag_codecs[i] = codecs[i];
2449     }
2450 }
2451 
2452 void hfp_ag_init_supported_features(uint32_t supported_features){
2453     hfp_ag_supported_features = supported_features;
2454 }
2455 
2456 void hfp_ag_init_ag_indicators(int ag_indicators_nr, const hfp_ag_indicator_t * ag_indicators){
2457     hfp_ag_indicators_nr = ag_indicators_nr;
2458     (void)memcpy(hfp_ag_indicators, ag_indicators,
2459                  ag_indicators_nr * sizeof(hfp_ag_indicator_t));
2460 }
2461 
2462 void hfp_ag_init_hf_indicators(int hf_indicators_nr, const hfp_generic_status_indicator_t * hf_indicators){
2463     if (hf_indicators_nr > HFP_MAX_NUM_INDICATORS) return;
2464     hfp_ag_generic_status_indicators_nr = hf_indicators_nr;
2465     (void)memcpy(hfp_ag_generic_status_indicators, hf_indicators,
2466                  hf_indicators_nr * sizeof(hfp_generic_status_indicator_t));
2467 }
2468 
2469 void hfp_ag_init_call_hold_services(int call_hold_services_nr, const char * call_hold_services[]){
2470     hfp_ag_call_hold_services_nr = call_hold_services_nr;
2471     (void)memcpy(hfp_ag_call_hold_services, call_hold_services,
2472                  call_hold_services_nr * sizeof(char *));
2473 }
2474 
2475 
2476 void hfp_ag_init(uint16_t rfcomm_channel_nr){
2477 
2478     hfp_init();
2479     hfp_ag_call_hold_services_nr = 0;
2480     hfp_ag_response_and_hold_active = 0;
2481     hfp_ag_indicators_nr = 0;
2482     hfp_ag_codecs_nr = 0;
2483     hfp_ag_supported_features = HFP_DEFAULT_AG_SUPPORTED_FEATURES;
2484     hfp_ag_subscriber_numbers = NULL;
2485     hfp_ag_subscriber_numbers_count = 0;
2486 
2487     hfp_ag_hci_event_callback_registration.callback = &hfp_ag_hci_event_packet_handler;
2488     hci_add_event_handler(&hfp_ag_hci_event_callback_registration);
2489 
2490     rfcomm_register_service(&hfp_ag_rfcomm_packet_handler, rfcomm_channel_nr, 0xffff);
2491 
2492     // used to set packet handler for outgoing rfcomm connections - could be handled by emitting an event to us
2493     hfp_set_ag_rfcomm_packet_handler(&hfp_ag_rfcomm_packet_handler);
2494 
2495     hfp_gsm_init();
2496 }
2497 
2498 void hfp_ag_deinit(void){
2499     hfp_deinit();
2500     hfp_gsm_deinit();
2501 
2502     hfp_ag_callback = NULL;
2503     hfp_ag_supported_features = 0;
2504     hfp_ag_codecs_nr = 0;
2505     hfp_ag_indicators_nr = 0;
2506     hfp_ag_call_hold_services_nr = 0;
2507     (void) memset(&hfp_ag_call_hold_services, 0, sizeof(hfp_ag_call_hold_services));
2508     hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
2509     (void) memset(&hfp_ag_response_and_hold_state, 0, sizeof(hfp_response_and_hold_state_t));
2510     hfp_ag_subscriber_numbers = NULL;
2511     (void) memset(&hfp_ag_hci_event_callback_registration, 0, sizeof(btstack_packet_callback_registration_t));
2512 }
2513 
2514 uint8_t hfp_ag_establish_service_level_connection(bd_addr_t bd_addr){
2515     return hfp_establish_service_level_connection(bd_addr, BLUETOOTH_SERVICE_CLASS_HANDSFREE, HFP_ROLE_AG);
2516 }
2517 
2518 uint8_t hfp_ag_release_service_level_connection(hci_con_handle_t acl_handle){
2519     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2520     if (!hfp_connection){
2521         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2522     }
2523 
2524     hfp_trigger_release_service_level_connection(hfp_connection);
2525     hfp_ag_run_for_context(hfp_connection);
2526     return ERROR_CODE_SUCCESS;
2527 }
2528 
2529 uint8_t hfp_ag_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle, hfp_cme_error_t error){
2530     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2531     if (!hfp_connection){
2532         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2533     }
2534 
2535     hfp_connection->extended_audio_gateway_error = 0;
2536     if (!hfp_connection->enable_extended_audio_gateway_error_report){
2537         return ERROR_CODE_COMMAND_DISALLOWED;
2538     }
2539 
2540     hfp_connection->extended_audio_gateway_error = error;
2541     hfp_ag_run_for_context(hfp_connection);
2542     return ERROR_CODE_SUCCESS;
2543 }
2544 
2545 static uint8_t hfp_ag_setup_audio_connection(hfp_connection_t * hfp_connection){
2546     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
2547         return ERROR_CODE_COMMAND_DISALLOWED;
2548     }
2549     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO){
2550         return ERROR_CODE_COMMAND_DISALLOWED;
2551     }
2552 
2553     hfp_connection->establish_audio_connection = 1;
2554     if (!has_codec_negotiation_feature(hfp_connection)){
2555         log_info("hfp_ag_establish_audio_connection - no codec negotiation feature, using CVSD");
2556         hfp_connection->negotiated_codec = HFP_CODEC_CVSD;
2557         hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
2558         // now, pick link settings
2559         hfp_init_link_settings(hfp_connection, hfp_ag_esco_s4_supported(hfp_connection));
2560 #ifdef ENABLE_CC256X_ASSISTED_HFP
2561         hfp_cc256x_prepare_for_sco(hfp_connection);
2562 #endif
2563         return ERROR_CODE_SUCCESS;
2564     }
2565 
2566     uint8_t i;
2567     bool codec_was_in_use = false;
2568     bool better_codec_can_be_used = false;
2569 
2570     for (i = 0; i<hfp_connection->remote_codecs_nr; i++){
2571         if (hfp_connection->negotiated_codec == hfp_connection->remote_codecs[i]){
2572             codec_was_in_use = true;
2573         } else if (hfp_connection->negotiated_codec < hfp_connection->remote_codecs[i]){
2574             better_codec_can_be_used = true;
2575         }
2576     }
2577 
2578     if (!codec_was_in_use || better_codec_can_be_used){
2579         hfp_connection->trigger_codec_exchange = 1;
2580         hfp_connection->codecs_state = HFP_CODECS_IDLE;
2581     }
2582     return ERROR_CODE_SUCCESS;
2583 }
2584 
2585 uint8_t hfp_ag_establish_audio_connection(hci_con_handle_t acl_handle){
2586     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2587     if (!hfp_connection){
2588         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2589     }
2590     uint8_t status = hfp_ag_setup_audio_connection(hfp_connection);
2591     if (status != ERROR_CODE_SUCCESS){
2592         return status;
2593     }
2594     hfp_ag_run_for_context(hfp_connection);
2595     return ERROR_CODE_SUCCESS;
2596 }
2597 
2598 uint8_t hfp_ag_release_audio_connection(hci_con_handle_t acl_handle){
2599     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2600     if (!hfp_connection){
2601         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2602     }
2603 
2604     if (hfp_connection->vra_state == HFP_VRA_VOICE_RECOGNITION_ACTIVATED){
2605         return ERROR_CODE_COMMAND_DISALLOWED;
2606     }
2607 
2608     uint8_t status = hfp_trigger_release_audio_connection(hfp_connection);
2609     if (status == ERROR_CODE_SUCCESS){
2610         hfp_ag_run_for_context(hfp_connection);
2611     }
2612     return status;
2613 }
2614 
2615 /**
2616  * @brief Enable in-band ring tone
2617  */
2618 void hfp_ag_set_use_in_band_ring_tone(int use_in_band_ring_tone){
2619     if (get_bit(hfp_ag_supported_features, HFP_AGSF_IN_BAND_RING_TONE) == use_in_band_ring_tone){
2620         return;
2621     }
2622 
2623     hfp_ag_supported_features = store_bit(hfp_ag_supported_features, HFP_AGSF_IN_BAND_RING_TONE, use_in_band_ring_tone);
2624 
2625     btstack_linked_list_iterator_t it;
2626     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2627     while (btstack_linked_list_iterator_has_next(&it)){
2628         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2629         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2630         hfp_connection->command = HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING;
2631         hfp_ag_run_for_context(hfp_connection);
2632     }
2633 }
2634 
2635 /**
2636  * @brief Called from GSM
2637  */
2638 void hfp_ag_incoming_call(void){
2639     hfp_ag_call_sm(HFP_AG_INCOMING_CALL, NULL);
2640 }
2641 
2642 void hfp_ag_outgoing_call_initiated(const char * number) {
2643     UNUSED(number);
2644     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED_BY_AG, NULL);
2645 }
2646 
2647 /**
2648  * @brief number is stored.
2649  */
2650 void hfp_ag_set_clip(uint8_t type, const char * number){
2651     hfp_gsm_handler(HFP_AG_SET_CLIP, 0, type, number);
2652 }
2653 
2654 void hfp_ag_call_dropped(void){
2655     hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2656 }
2657 
2658 // call from AG UI
2659 void hfp_ag_answer_incoming_call(void){
2660     hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, NULL);
2661 }
2662 
2663 void hfp_ag_join_held_call(void){
2664     hfp_ag_call_sm(HFP_AG_HELD_CALL_JOINED_BY_AG, NULL);
2665 }
2666 
2667 void hfp_ag_terminate_call(void){
2668     hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_AG, NULL);
2669 }
2670 
2671 void hfp_ag_outgoing_call_ringing(void){
2672     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_RINGING, NULL);
2673 }
2674 
2675 void hfp_ag_outgoing_call_established(void){
2676     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ESTABLISHED, NULL);
2677 }
2678 
2679 void hfp_ag_outgoing_call_rejected(void){
2680     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_REJECTED, NULL);
2681 }
2682 
2683 void hfp_ag_outgoing_call_accepted(void){
2684     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ACCEPTED, NULL);
2685 }
2686 
2687 void hfp_ag_hold_incoming_call(void){
2688     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, NULL);
2689 }
2690 
2691 void hfp_ag_accept_held_incoming_call(void) {
2692     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, NULL);
2693 }
2694 
2695 void hfp_ag_reject_held_incoming_call(void){
2696     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, NULL);
2697 }
2698 
2699 static void hfp_ag_set_ag_indicator(const char * name, int value){
2700     int indicator_index = get_ag_indicator_index_for_name(name);
2701     if (indicator_index < 0) return;
2702     hfp_ag_indicators[indicator_index].status = value;
2703 
2704     btstack_linked_list_iterator_t it;
2705     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2706     while (btstack_linked_list_iterator_has_next(&it)){
2707         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2708         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2709         if (!hfp_connection->ag_indicators[indicator_index].enabled) {
2710             log_info("Requested AG indicator '%s' update to %u, but it is not enabled", hfp_ag_indicators[indicator_index].name, value);
2711             continue;
2712         }
2713         log_info("AG indicator '%s' changed to %u, request transfer status", hfp_ag_indicators[indicator_index].name, value);
2714         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
2715         hfp_ag_run_for_context(hfp_connection);
2716     }
2717 }
2718 
2719 uint8_t hfp_ag_set_registration_status(int registration_status){
2720     if ((registration_status < 0) || (registration_status > 1)){
2721         return ERROR_CODE_COMMAND_DISALLOWED;
2722     }
2723 
2724     if ( (registration_status == 0) && (hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
2725 
2726         // if network goes away wihle a call is active:
2727         // - the  call gets dropped
2728         // - we send NO CARRIER
2729         // NOTE: the CALL=0 has to be sent before NO CARRIER
2730 
2731         hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2732 
2733         btstack_linked_list_iterator_t it;
2734         btstack_linked_list_iterator_init(&it, hfp_get_connections());
2735         while (btstack_linked_list_iterator_has_next(&it)){
2736             hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2737             hfp_connection->ag_send_no_carrier = true;
2738         }
2739     }
2740     hfp_ag_set_ag_indicator("service", registration_status);
2741     return ERROR_CODE_SUCCESS;
2742 }
2743 
2744 uint8_t hfp_ag_set_signal_strength(int signal_strength){
2745     if ((signal_strength < 0) || (signal_strength > 5)){
2746         return ERROR_CODE_COMMAND_DISALLOWED;
2747     }
2748 
2749     hfp_ag_set_ag_indicator("signal", signal_strength);
2750     return ERROR_CODE_SUCCESS;
2751 }
2752 
2753 uint8_t hfp_ag_set_roaming_status(int roaming_status){
2754     if ((roaming_status < 0) || (roaming_status > 1)){
2755         return ERROR_CODE_COMMAND_DISALLOWED;
2756     }
2757 
2758     hfp_ag_set_ag_indicator("roam", roaming_status);
2759     return ERROR_CODE_SUCCESS;
2760 }
2761 
2762 uint8_t hfp_ag_set_battery_level(int battery_level){
2763     if ((battery_level < 0) || (battery_level > 5)){
2764         return ERROR_CODE_COMMAND_DISALLOWED;
2765     }
2766     hfp_ag_set_ag_indicator("battchg", battery_level);
2767     return ERROR_CODE_SUCCESS;
2768 }
2769 
2770 static uint8_t activate_voice_recognition(hci_con_handle_t acl_handle, bool enhanced){
2771     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2772     if (!hfp_connection){
2773         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2774     }
2775 
2776     uint8_t status = hfp_ag_can_activate_voice_recognition(hfp_connection, enhanced);
2777     if (status == ERROR_CODE_SUCCESS){
2778         hfp_connection->ag_activate_voice_recognition_value = 1;
2779         hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED;
2780         hfp_connection->command = HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
2781         hfp_connection->enhanced_voice_recognition_enabled = enhanced;
2782         hfp_connection->ag_audio_connection_opened_before_vra = hfp_ag_is_audio_connection_active(hfp_connection);
2783         hfp_connection->ag_vra_state = HFP_VOICE_RECOGNITION_STATE_AG_READY;
2784         hfp_ag_run_for_context(hfp_connection);
2785     }
2786     return status;
2787 }
2788 
2789 static uint8_t deactivate_voice_recognition(hci_con_handle_t acl_handle, bool enhanced){
2790     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2791     if (!hfp_connection){
2792         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2793     }
2794     uint8_t status = hfp_ag_voice_recognition_session_active(hfp_connection, enhanced);
2795     if (status == ERROR_CODE_SUCCESS){
2796         hfp_connection->ag_activate_voice_recognition_value = 0;
2797         hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF;
2798         hfp_connection->command = HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
2799         hfp_connection->ag_vra_state = HFP_VOICE_RECOGNITION_STATE_AG_READY;
2800         hfp_ag_run_for_context(hfp_connection);
2801     }
2802     return status;
2803 }
2804 
2805 uint8_t hfp_ag_activate_voice_recognition(hci_con_handle_t acl_handle){
2806     return activate_voice_recognition(acl_handle, false);
2807 }
2808 
2809 uint8_t hfp_ag_activate_enhanced_voice_recognition(hci_con_handle_t acl_handle){
2810     return activate_voice_recognition(acl_handle, true);
2811 }
2812 
2813 uint8_t hfp_ag_deactivate_voice_recognition(hci_con_handle_t acl_handle){
2814     return deactivate_voice_recognition(acl_handle, false);
2815 }
2816 
2817 uint8_t hfp_ag_deactivate_enhanced_voice_recognition(hci_con_handle_t acl_handle){
2818     return deactivate_voice_recognition(acl_handle, true);
2819 }
2820 
2821 static uint8_t hfp_ag_enhanced_voice_recognition_send_state(hci_con_handle_t acl_handle, hfp_voice_recognition_state_t state){
2822     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2823     if (!hfp_connection){
2824         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2825     }
2826 
2827     uint8_t status = hfp_ag_voice_recognition_session_active(hfp_connection, true);
2828     if (status == ERROR_CODE_SUCCESS){
2829         hfp_connection->command = HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
2830         hfp_connection->ag_vra_state = state;
2831         hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_STATUS;
2832         hfp_ag_run_for_context(hfp_connection);
2833     }
2834     return status;
2835 }
2836 
2837 uint8_t hfp_ag_enhanced_voice_recognition_report_sending_audio(hci_con_handle_t acl_handle){
2838     return hfp_ag_enhanced_voice_recognition_send_state(acl_handle, HFP_VOICE_RECOGNITION_STATE_AG_IS_STARTING_SOUND);
2839 }
2840 uint8_t hfp_ag_enhanced_voice_recognition_report_ready_for_audio(hci_con_handle_t acl_handle){
2841     return hfp_ag_enhanced_voice_recognition_send_state(acl_handle, HFP_VOICE_RECOGNITION_STATE_AG_READY_TO_ACCEPT_AUDIO_INPUT);
2842 }
2843 uint8_t hfp_ag_enhanced_voice_recognition_report_processing_input(hci_con_handle_t acl_handle){
2844     return hfp_ag_enhanced_voice_recognition_send_state(acl_handle, HFP_VOICE_RECOGNITION_STATE_AG_IS_PROCESSING_AUDIO_INPUT);
2845 }
2846 
2847 
2848 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){
2849     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2850     if (!hfp_connection){
2851         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2852     }
2853 
2854     uint8_t status = hfp_ag_can_send_enahnced_voice_recognition_message(hfp_connection, true);
2855     if (status == ERROR_CODE_SUCCESS){
2856         hfp_connection->command = HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
2857         hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_ENHANCED_VOICE_RECOGNITION_MSG;
2858         hfp_connection->ag_msg = msg;
2859         hfp_connection->ag_vra_state = state;
2860         hfp_ag_run_for_context(hfp_connection);
2861     }
2862     return status;
2863 }
2864 
2865 
2866 uint8_t hfp_ag_set_microphone_gain(hci_con_handle_t acl_handle, int gain){
2867     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2868     if (!hfp_connection){
2869         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2870     }
2871 
2872     if ((gain < 0) || (gain > 15)){
2873         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
2874         return ERROR_CODE_COMMAND_DISALLOWED;
2875     }
2876 
2877     if (hfp_connection->microphone_gain != gain){
2878         hfp_connection->command = HFP_CMD_SET_MICROPHONE_GAIN;
2879         hfp_connection->microphone_gain = gain;
2880         hfp_connection->send_microphone_gain = 1;
2881     }
2882     hfp_ag_run_for_context(hfp_connection);
2883     return ERROR_CODE_SUCCESS;
2884 }
2885 
2886 uint8_t hfp_ag_set_speaker_gain(hci_con_handle_t acl_handle, int gain){
2887     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2888     if (!hfp_connection){
2889         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2890     }
2891 
2892     if ((gain < 0) || (gain > 15)){
2893         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
2894         return ERROR_CODE_COMMAND_DISALLOWED;
2895     }
2896 
2897     if (hfp_connection->speaker_gain != gain){
2898         hfp_connection->speaker_gain = gain;
2899         hfp_connection->send_speaker_gain = 1;
2900     }
2901     hfp_ag_run_for_context(hfp_connection);
2902     return ERROR_CODE_SUCCESS;
2903 }
2904 
2905 uint8_t hfp_ag_send_phone_number_for_voice_tag(hci_con_handle_t acl_handle, const char * number){
2906     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2907     if (!hfp_connection){
2908         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2909     }
2910 
2911     hfp_ag_set_clip(0, number);
2912     hfp_connection->send_phone_number_for_voice_tag = 1;
2913     return ERROR_CODE_SUCCESS;
2914 }
2915 
2916 uint8_t hfp_ag_reject_phone_number_for_voice_tag(hci_con_handle_t acl_handle){
2917     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2918     if (!hfp_connection){
2919         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2920     }
2921 
2922     hfp_connection->send_error = 1;
2923     return ERROR_CODE_SUCCESS;
2924 }
2925 
2926 uint8_t hfp_ag_send_dtmf_code_done(hci_con_handle_t acl_handle){
2927     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2928     if (!hfp_connection){
2929         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2930     }
2931 
2932     hfp_connection->ok_pending = 1;
2933     return ERROR_CODE_SUCCESS;
2934 }
2935 
2936 void hfp_ag_set_subcriber_number_information(hfp_phone_number_t * numbers, int numbers_count){
2937     hfp_ag_subscriber_numbers = numbers;
2938     hfp_ag_subscriber_numbers_count = numbers_count;
2939 }
2940 
2941 void hfp_ag_clear_last_dialed_number(void){
2942     hfp_gsm_clear_last_dialed_number();
2943 }
2944 
2945 void hfp_ag_set_last_dialed_number(const char * number){
2946     hfp_gsm_set_last_dialed_number(number);
2947 }
2948 
2949 uint8_t hfp_ag_notify_incoming_call_waiting(hci_con_handle_t acl_handle){
2950     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2951     if (!hfp_connection){
2952         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2953     }
2954 
2955     if (!hfp_connection->call_waiting_notification_enabled){
2956         return ERROR_CODE_COMMAND_DISALLOWED;
2957     }
2958 
2959     hfp_connection->ag_notify_incoming_call_waiting = 1;
2960     hfp_ag_run_for_context(hfp_connection);
2961     return ERROR_CODE_SUCCESS;
2962 }
2963 
2964 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){
2965 	if (!name){
2966 		name = hfp_ag_default_service_name;
2967 	}
2968 	hfp_create_sdp_record(service, service_record_handle, BLUETOOTH_SERVICE_CLASS_HANDSFREE_AUDIO_GATEWAY, rfcomm_channel_nr, name);
2969 
2970 	/*
2971 	 * 0x01 – Ability to reject a call
2972 	 * 0x00 – No ability to reject a call
2973 	 */
2974 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0301);    // Hands-Free Profile - Network
2975 	de_add_number(service, DE_UINT, DE_SIZE_8, ability_to_reject_call);
2976 
2977 	// Construct SupportedFeatures for SDP bitmap:
2978 	//
2979 	// "The values of the “SupportedFeatures” bitmap given in Table 5.4 shall be the same as the values
2980 	//  of the Bits 0 to 4 of the unsolicited result code +BRSF"
2981 	//
2982 	// Wide band speech (bit 5) requires Codec negotiation
2983 	//
2984 	uint16_t sdp_features = supported_features & 0x1f;
2985 	if ( (wide_band_speech == 1) && (supported_features & (1 << HFP_AGSF_CODEC_NEGOTIATION))){
2986 		sdp_features |= 1 << 5;
2987 	}
2988 
2989     if (supported_features & (1 << HFP_AGSF_ENHANCED_VOICE_RECOGNITION_STATUS)){
2990         sdp_features |= 1 << 6;
2991     }
2992 
2993     if (supported_features & (1 << HFP_AGSF_VOICE_RECOGNITION_TEXT)){
2994         sdp_features |= 1 << 7;
2995     }
2996 
2997 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);    // Hands-Free Profile - SupportedFeatures
2998 	de_add_number(service, DE_UINT, DE_SIZE_16, sdp_features);
2999 }
3000 
3001 void hfp_ag_register_packet_handler(btstack_packet_handler_t callback){
3002 	btstack_assert(callback != NULL);
3003 
3004 	hfp_ag_callback = callback;
3005 	hfp_set_ag_callback(callback);
3006 }
3007