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