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