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