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