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