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