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