xref: /btstack/src/classic/hfp_ag.c (revision e83c202541a02b09236bd4dc8c266a0bbc81f536)
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     if (hfp_connection->release_audio_connection){
938         hfp_connection->state = HFP_W4_SCO_DISCONNECTED;
939         hfp_connection->release_audio_connection = 0;
940         gap_disconnect(hfp_connection->sco_handle);
941         return 1;
942     }
943 
944     // accept incoming audio connection (codec negotiation is not used)
945     if (hfp_connection->accept_sco){
946         // notify about codec selection if not done already
947         if (hfp_connection->negotiated_codec == 0){
948             hfp_connection->negotiated_codec = HFP_CODEC_CVSD;
949         }
950         //
951         bool incoming_eSCO = hfp_connection->accept_sco == 2;
952         hfp_connection->accept_sco = 0;
953         hfp_connection->state = HFP_W4_SCO_CONNECTED;
954         hfp_accept_synchronous_connection(hfp_connection, incoming_eSCO);
955         return 1;
956     }
957 
958     // run codecs exchange
959     int sent = codecs_exchange_state_machine(hfp_connection);
960     if (sent) return 1;
961 
962     if (hfp_connection->codecs_state != HFP_CODECS_EXCHANGED) return 0;
963     if (hfp_connection->establish_audio_connection){
964         hfp_connection->state = HFP_W4_SCO_CONNECTED;
965         hfp_connection->establish_audio_connection = 0;
966         hfp_setup_synchronous_connection(hfp_connection);
967         return 1;
968     }
969     return 0;
970 }
971 
972 static hfp_connection_t * hfp_ag_context_for_timer(btstack_timer_source_t * ts){
973     btstack_linked_list_iterator_t it;
974     btstack_linked_list_iterator_init(&it, hfp_get_connections());
975 
976     while (btstack_linked_list_iterator_has_next(&it)){
977         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
978         if ( & hfp_connection->hfp_timeout == ts) {
979             return hfp_connection;
980         }
981     }
982     return NULL;
983 }
984 
985 static void hfp_timeout_handler(btstack_timer_source_t * timer){
986     hfp_connection_t * hfp_connection = hfp_ag_context_for_timer(timer);
987     if (!hfp_connection) return;
988 
989     log_info("HFP start ring timeout, con handle 0x%02x", hfp_connection->acl_handle);
990     hfp_connection->ag_ring = 1;
991     hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
992 
993     btstack_run_loop_set_timer(& hfp_connection->hfp_timeout, 2000); // 2 seconds timeout
994     btstack_run_loop_add_timer(& hfp_connection->hfp_timeout);
995 
996     hfp_ag_run_for_context(hfp_connection);
997 }
998 
999 static void hfp_timeout_start(hfp_connection_t * hfp_connection){
1000     btstack_run_loop_remove_timer(& hfp_connection->hfp_timeout);
1001     btstack_run_loop_set_timer_handler(& hfp_connection->hfp_timeout, hfp_timeout_handler);
1002     btstack_run_loop_set_timer(& hfp_connection->hfp_timeout, 2000); // 2 seconds timeout
1003     btstack_run_loop_add_timer(& hfp_connection->hfp_timeout);
1004 }
1005 
1006 static void hfp_timeout_stop(hfp_connection_t * hfp_connection){
1007     log_info("HFP stop ring timeout, con handle 0x%02x", hfp_connection->acl_handle);
1008     btstack_run_loop_remove_timer(& hfp_connection->hfp_timeout);
1009 }
1010 
1011 static void hfp_ag_set_callsetup_indicator(void){
1012     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("callsetup");
1013     if (!indicator){
1014         log_error("hfp_ag_set_callsetup_indicator: callsetup indicator is missing");
1015         return;
1016     };
1017     indicator->status = hfp_gsm_callsetup_status();
1018 }
1019 
1020 static void hfp_ag_set_callheld_indicator(void){
1021     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("callheld");
1022     if (!indicator){
1023         log_error("hfp_ag_set_callheld_state: callheld indicator is missing");
1024         return;
1025     };
1026     indicator->status = hfp_gsm_callheld_status();
1027 }
1028 
1029 //
1030 // transitition implementations for hfp_ag_call_state_machine
1031 //
1032 
1033 static void hfp_ag_hf_start_ringing(hfp_connection_t * hfp_connection){
1034     if (use_in_band_tone()){
1035         hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING;
1036         hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
1037     } else {
1038         hfp_timeout_start(hfp_connection);
1039         hfp_connection->ag_ring = 1;
1040         hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
1041         hfp_connection->call_state = HFP_CALL_RINGING;
1042         hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_START_RINGINIG);
1043     }
1044 }
1045 
1046 static void hfp_ag_hf_stop_ringing(hfp_connection_t * hfp_connection){
1047     hfp_connection->ag_ring = 0;
1048     hfp_connection->ag_send_clip = 0;
1049     hfp_timeout_stop(hfp_connection);
1050     hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_STOP_RINGINIG);
1051 }
1052 
1053 static void hfp_ag_trigger_incoming_call(void){
1054     int indicator_index = get_ag_indicator_index_for_name("callsetup");
1055     if (indicator_index < 0) return;
1056 
1057     btstack_linked_list_iterator_t it;
1058     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1059     while (btstack_linked_list_iterator_has_next(&it)){
1060         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1061         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1062         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
1063         if (hfp_connection->call_state == HFP_CALL_IDLE){
1064             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1065             hfp_ag_hf_start_ringing(hfp_connection);
1066         }
1067         if (hfp_connection->call_state == HFP_CALL_ACTIVE){
1068             hfp_connection->call_state = HFP_CALL_W2_SEND_CALL_WAITING;
1069         }
1070         hfp_ag_run_for_context(hfp_connection);
1071     }
1072 }
1073 
1074 static void hfp_ag_trigger_outgoing_call(void){
1075     btstack_linked_list_iterator_t it;
1076     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1077     while (btstack_linked_list_iterator_has_next(&it)){
1078         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1079         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1080         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
1081         if (hfp_connection->call_state == HFP_CALL_IDLE){
1082             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1083         }
1084     }
1085 }
1086 
1087 static void hfp_ag_handle_outgoing_call_accepted(hfp_connection_t * hfp_connection){
1088     hfp_connection->call_state = HFP_CALL_OUTGOING_DIALING;
1089 
1090     // trigger callsetup to be
1091     int put_call_on_hold = hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT;
1092     hfp_gsm_handler(HFP_AG_OUTGOING_CALL_ACCEPTED, 0, 0, NULL);
1093 
1094     int indicator_index ;
1095 
1096     hfp_ag_set_callsetup_indicator();
1097     indicator_index = get_ag_indicator_index_for_name("callsetup");
1098     hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1099 
1100     // put current call on hold if active
1101     if (put_call_on_hold){
1102         log_info("AG putting current call on hold for new outgoing call");
1103         hfp_ag_set_callheld_indicator();
1104         indicator_index = get_ag_indicator_index_for_name("callheld");
1105         hfp_ag_send_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[indicator_index]);
1106     }
1107 
1108     // start audio if needed
1109     hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
1110 }
1111 
1112 static void hfp_ag_transfer_indicator(const char * name){
1113     int indicator_index = get_ag_indicator_index_for_name(name);
1114     if (indicator_index < 0) return;
1115 
1116     btstack_linked_list_iterator_t it;
1117     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1118     while (btstack_linked_list_iterator_has_next(&it)){
1119         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1120         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1121         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
1122         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1123         hfp_ag_run_for_context(hfp_connection);
1124     }
1125 }
1126 
1127 static void hfp_ag_transfer_callsetup_state(void){
1128     hfp_ag_transfer_indicator("callsetup");
1129 }
1130 
1131 static void hfp_ag_transfer_call_state(void){
1132     hfp_ag_transfer_indicator("call");
1133 }
1134 
1135 static void hfp_ag_transfer_callheld_state(void){
1136     hfp_ag_transfer_indicator("callheld");
1137 }
1138 
1139 static void hfp_ag_hf_accept_call(hfp_connection_t * source){
1140     int call_indicator_index = get_ag_indicator_index_for_name("call");
1141     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1142 
1143     btstack_linked_list_iterator_t it;
1144     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1145     while (btstack_linked_list_iterator_has_next(&it)){
1146         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1147         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1148         if ((hfp_connection->call_state != HFP_CALL_RINGING) &&
1149             (hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
1150 
1151         hfp_ag_hf_stop_ringing(hfp_connection);
1152         if (hfp_connection == source){
1153 
1154             if (use_in_band_tone()){
1155                 hfp_connection->call_state = HFP_CALL_ACTIVE;
1156             } else {
1157                 hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE;
1158                 hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
1159             }
1160 
1161             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1162             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1163 
1164         } else {
1165             hfp_connection->call_state = HFP_CALL_IDLE;
1166         }
1167         hfp_ag_run_for_context(hfp_connection);
1168     }
1169 }
1170 
1171 static void hfp_ag_ag_accept_call(void){
1172     int call_indicator_index = get_ag_indicator_index_for_name("call");
1173     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1174 
1175     btstack_linked_list_iterator_t it;
1176     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1177     while (btstack_linked_list_iterator_has_next(&it)){
1178         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1179         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1180         if (hfp_connection->call_state != HFP_CALL_RINGING) continue;
1181 
1182         hfp_ag_hf_stop_ringing(hfp_connection);
1183         hfp_connection->call_state = HFP_CALL_TRIGGER_AUDIO_CONNECTION;
1184 
1185         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1186         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1187 
1188         hfp_ag_run_for_context(hfp_connection);
1189         break;  // only single
1190     }
1191 }
1192 
1193 static void hfp_ag_trigger_reject_call(void){
1194     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1195     btstack_linked_list_iterator_t it;
1196     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1197     while (btstack_linked_list_iterator_has_next(&it)){
1198         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1199         if (connection->local_role != HFP_ROLE_AG) continue;
1200         if ((connection->call_state != HFP_CALL_RINGING) &&
1201             (connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
1202         hfp_ag_hf_stop_ringing(connection);
1203         connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1204         connection->call_state = HFP_CALL_IDLE;
1205         hfp_ag_run_for_context(connection);
1206     }
1207 }
1208 
1209 static void hfp_ag_trigger_terminate_call(void){
1210     int call_indicator_index = get_ag_indicator_index_for_name("call");
1211 
1212     btstack_linked_list_iterator_t it;
1213     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1214     while (btstack_linked_list_iterator_has_next(&it)){
1215         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1216         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1217         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
1218         if (hfp_connection->call_state == HFP_CALL_IDLE) continue;
1219         hfp_connection->call_state = HFP_CALL_IDLE;
1220         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1221         if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
1222             hfp_connection->release_audio_connection = 1;
1223         }
1224         hfp_ag_run_for_context(hfp_connection);
1225     }
1226     hfp_emit_simple_event(NULL, HFP_SUBEVENT_CALL_TERMINATED);
1227 }
1228 
1229 static void hfp_ag_set_call_indicator(void){
1230     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("call");
1231     if (!indicator){
1232         log_error("hfp_ag_set_call_state: call indicator is missing");
1233         return;
1234     };
1235     indicator->status = hfp_gsm_call_status();
1236 }
1237 
1238 static void hfp_ag_stop_ringing(void){
1239     btstack_linked_list_iterator_t it;
1240     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1241     while (btstack_linked_list_iterator_has_next(&it)){
1242         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1243         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1244         if ((hfp_connection->call_state != HFP_CALL_RINGING) &&
1245             (hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING)) continue;
1246         hfp_ag_hf_stop_ringing(hfp_connection);
1247     }
1248 }
1249 
1250 static hfp_connection_t * hfp_ag_connection_for_call_state(hfp_call_state_t call_state){
1251     btstack_linked_list_iterator_t it;
1252     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1253     while (btstack_linked_list_iterator_has_next(&it)){
1254         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1255         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1256         if (hfp_connection->call_state == call_state) return hfp_connection;
1257     }
1258     return NULL;
1259 }
1260 
1261 static void hfp_ag_send_response_and_hold_state(hfp_response_and_hold_state_t state){
1262     btstack_linked_list_iterator_t it;
1263     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1264     while (btstack_linked_list_iterator_has_next(&it)){
1265         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1266         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
1267         hfp_connection->send_response_and_hold_status = state + 1;
1268     }
1269 }
1270 
1271 static int call_setup_state_machine(hfp_connection_t * hfp_connection){
1272     int indicator_index;
1273     switch (hfp_connection->call_state){
1274         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING:
1275             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1276             // we got event: audio hfp_connection established
1277             hfp_timeout_start(hfp_connection);
1278             hfp_connection->ag_ring = 1;
1279             hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
1280             hfp_connection->call_state = HFP_CALL_RINGING;
1281             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_START_RINGINIG);
1282             break;
1283         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE:
1284             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1285             // we got event: audio hfp_connection established
1286             hfp_connection->call_state = HFP_CALL_ACTIVE;
1287             break;
1288         case HFP_CALL_W2_SEND_CALL_WAITING:
1289             hfp_connection->call_state = HFP_CALL_W4_CHLD;
1290             hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1291             indicator_index = get_ag_indicator_index_for_name("callsetup");
1292             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1293             break;
1294         default:
1295             break;
1296     }
1297     return 0;
1298 }
1299 
1300 // functions extracted from hfp_ag_call_sm below
1301 static void hfp_ag_handle_reject_outgoing_call(void){
1302     hfp_connection_t * hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1303     if (!hfp_connection){
1304         log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1305         return;
1306     }
1307 
1308     hfp_gsm_handler(HFP_AG_OUTGOING_CALL_REJECTED, 0, 0, NULL);
1309     hfp_connection->call_state = HFP_CALL_IDLE;
1310     hfp_connection->send_error = 1;
1311     hfp_ag_run_for_context(hfp_connection);
1312 }
1313 
1314 // hfp_connection is used to identify originating HF
1315 static void hfp_ag_call_sm(hfp_ag_call_event_t event, hfp_connection_t * hfp_connection){
1316     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1317     int callheld_indicator_index = get_ag_indicator_index_for_name("callheld");
1318     int call_indicator_index = get_ag_indicator_index_for_name("call");
1319 
1320     switch (event){
1321         case HFP_AG_INCOMING_CALL:
1322             switch (hfp_gsm_call_status()){
1323                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1324                     switch (hfp_gsm_callsetup_status()){
1325                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1326                             hfp_gsm_handler(HFP_AG_INCOMING_CALL, 0, 0, NULL);
1327                             hfp_ag_set_callsetup_indicator();
1328                             hfp_ag_trigger_incoming_call();
1329                             log_info("AG rings");
1330                             break;
1331                         default:
1332                             break;
1333                     }
1334                     break;
1335                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1336                     switch (hfp_gsm_callsetup_status()){
1337                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1338                             hfp_gsm_handler(HFP_AG_INCOMING_CALL, 0, 0, NULL);
1339                             hfp_ag_set_callsetup_indicator();
1340                             hfp_ag_trigger_incoming_call();
1341                             log_info("AG call waiting");
1342                             break;
1343                         default:
1344                             break;
1345                     }
1346                     break;
1347                 default:
1348                     break;
1349             }
1350             break;
1351         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG:
1352             switch (hfp_gsm_call_status()){
1353                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1354                     switch (hfp_gsm_callsetup_status()){
1355                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1356                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, 0, 0, NULL);
1357                             hfp_ag_set_call_indicator();
1358                             hfp_ag_set_callsetup_indicator();
1359                             hfp_ag_ag_accept_call();
1360                             log_info("AG answers call, accept call by GSM");
1361                             break;
1362                         default:
1363                             break;
1364                     }
1365                     break;
1366                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1367                     switch (hfp_gsm_callsetup_status()){
1368                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1369                             log_info("AG: current call is placed on hold, incoming call gets active");
1370                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, 0, 0, NULL);
1371                             hfp_ag_set_callsetup_indicator();
1372                             hfp_ag_set_callheld_indicator();
1373                             hfp_ag_transfer_callsetup_state();
1374                             hfp_ag_transfer_callheld_state();
1375                             break;
1376                         default:
1377                             break;
1378                     }
1379                     break;
1380                 default:
1381                     break;
1382             }
1383             break;
1384 
1385         case HFP_AG_HELD_CALL_JOINED_BY_AG:
1386             switch (hfp_gsm_call_status()){
1387                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1388                     switch (hfp_gsm_callheld_status()){
1389                         case HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED:
1390                             log_info("AG: joining held call with active call");
1391                             hfp_gsm_handler(HFP_AG_HELD_CALL_JOINED_BY_AG, 0, 0, NULL);
1392                             hfp_ag_set_callheld_indicator();
1393                             hfp_ag_transfer_callheld_state();
1394                             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CONFERENCE_CALL);
1395                             break;
1396                         default:
1397                             break;
1398                     }
1399                     break;
1400                 default:
1401                     break;
1402             }
1403             break;
1404 
1405         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF:
1406             switch (hfp_gsm_call_status()){
1407                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1408                     switch (hfp_gsm_callsetup_status()){
1409                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1410                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, 0, 0, NULL);
1411                             hfp_ag_set_callsetup_indicator();
1412                             hfp_ag_set_call_indicator();
1413                             hfp_ag_hf_accept_call(hfp_connection);
1414                             hfp_connection->ok_pending = 1;
1415                             log_info("HF answers call, accept call by GSM");
1416                             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_ANSWERED);
1417                             break;
1418                         default:
1419                             break;
1420                     }
1421                     break;
1422                 default:
1423                     break;
1424             }
1425             break;
1426 
1427         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG:
1428             switch (hfp_gsm_call_status()){
1429                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1430                     switch (hfp_gsm_callsetup_status()){
1431                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1432                             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, 0, 0, NULL);
1433                             hfp_ag_response_and_hold_active = 1;
1434                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1435                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1436                             // as with regular call
1437                             hfp_ag_set_call_indicator();
1438                             hfp_ag_set_callsetup_indicator();
1439                             hfp_ag_ag_accept_call();
1440                             log_info("AG response and hold - hold by AG");
1441                             break;
1442                         default:
1443                             break;
1444                     }
1445                     break;
1446                 default:
1447                     break;
1448             }
1449             break;
1450 
1451         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF:
1452             switch (hfp_gsm_call_status()){
1453                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1454                     switch (hfp_gsm_callsetup_status()){
1455                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1456                             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, 0, 0, NULL);
1457                             hfp_ag_response_and_hold_active = 1;
1458                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1459                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1460                             // as with regular call
1461                             hfp_ag_set_call_indicator();
1462                             hfp_ag_set_callsetup_indicator();
1463                             hfp_ag_hf_accept_call(hfp_connection);
1464                             log_info("AG response and hold - hold by HF");
1465                             break;
1466                         default:
1467                             break;
1468                     }
1469                     break;
1470                 default:
1471                     break;
1472             }
1473             break;
1474 
1475         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG:
1476         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF:
1477             if (!hfp_ag_response_and_hold_active) break;
1478             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1479             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, 0, 0, NULL);
1480             hfp_ag_response_and_hold_active = 0;
1481             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED;
1482             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1483             log_info("Held Call accepted and active");
1484             break;
1485 
1486         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG:
1487         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF:
1488             if (!hfp_ag_response_and_hold_active) break;
1489             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1490             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, 0, 0, NULL);
1491             hfp_ag_response_and_hold_active = 0;
1492             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1493             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1494             // from terminate by ag
1495             hfp_ag_set_call_indicator();
1496             hfp_ag_trigger_terminate_call();
1497             break;
1498 
1499         case HFP_AG_TERMINATE_CALL_BY_HF:
1500             switch (hfp_gsm_call_status()){
1501                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1502                     switch (hfp_gsm_callsetup_status()){
1503                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1504                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1505                             hfp_ag_set_callsetup_indicator();
1506                             hfp_ag_transfer_callsetup_state();
1507                             hfp_ag_trigger_reject_call();
1508                             log_info("HF Rejected Incoming call, AG terminate call");
1509                             break;
1510                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1511                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1512                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1513                             hfp_ag_set_callsetup_indicator();
1514                             hfp_ag_transfer_callsetup_state();
1515                             log_info("AG terminate outgoing call process");
1516                             break;
1517                         default:
1518                             break;
1519                     }
1520                     break;
1521                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1522                     hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1523                     hfp_ag_set_callsetup_indicator();
1524                     hfp_ag_set_call_indicator();
1525                     hfp_ag_trigger_terminate_call();
1526                     log_info("AG terminate call");
1527                     break;
1528                 default:
1529                     break;
1530             }
1531             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_TERMINATED);
1532             break;
1533 
1534         case HFP_AG_TERMINATE_CALL_BY_AG:
1535             switch (hfp_gsm_call_status()){
1536                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1537                     switch (hfp_gsm_callsetup_status()){
1538                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1539                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_AG, 0, 0, NULL);
1540                             hfp_ag_set_callsetup_indicator();
1541                             hfp_ag_trigger_reject_call();
1542                             log_info("AG Rejected Incoming call, AG terminate call");
1543                             break;
1544                         default:
1545                             break;
1546                     }
1547                     break;
1548                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1549                     hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_AG, 0, 0, NULL);
1550                     hfp_ag_set_callsetup_indicator();
1551                     hfp_ag_set_call_indicator();
1552                     hfp_ag_trigger_terminate_call();
1553                     log_info("AG terminate call");
1554                     break;
1555                 default:
1556                     break;
1557             }
1558             break;
1559         case HFP_AG_CALL_DROPPED:
1560             switch (hfp_gsm_call_status()){
1561                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1562                     switch (hfp_gsm_callsetup_status()){
1563                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1564                             hfp_ag_stop_ringing();
1565                             log_info("Incoming call interrupted");
1566                             break;
1567                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1568                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1569                             log_info("Outgoing call interrupted\n");
1570                             log_info("AG notify call dropped\n");
1571                             break;
1572                         default:
1573                             break;
1574                     }
1575                     hfp_gsm_handler(HFP_AG_CALL_DROPPED, 0, 0, NULL);
1576                     hfp_ag_set_callsetup_indicator();
1577                     hfp_ag_transfer_callsetup_state();
1578                     hfp_ag_trigger_terminate_call();
1579                     break;
1580                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1581                     if (hfp_ag_response_and_hold_active) {
1582                         hfp_gsm_handler(HFP_AG_CALL_DROPPED, 0, 0, NULL);
1583                         hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1584                         hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1585                     }
1586                     hfp_gsm_handler(HFP_AG_CALL_DROPPED, 0, 0, NULL);
1587                     hfp_ag_set_callsetup_indicator();
1588                     hfp_ag_set_call_indicator();
1589                     hfp_ag_trigger_terminate_call();
1590                     log_info("AG notify call dropped");
1591                     break;
1592                 default:
1593                     break;
1594             }
1595             break;
1596 
1597         case HFP_AG_OUTGOING_CALL_INITIATED_BY_HF:
1598             // directly reject call if number of free slots is exceeded
1599             if (!hfp_gsm_call_possible()){
1600                 hfp_connection->send_error = 1;
1601                 hfp_ag_run_for_context(hfp_connection);
1602                 break;
1603             }
1604 
1605             // note: number not used currently
1606             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_INITIATED_BY_HF, 0, 0, (const char *) &hfp_connection->line_buffer[3]);
1607 
1608             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1609 
1610             hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, (const char *) &hfp_connection->line_buffer[3]);
1611             break;
1612 
1613         case HFP_AG_OUTGOING_CALL_INITIATED_BY_AG:
1614             // directly reject call if number of free slots is exceeded
1615             if (!hfp_gsm_call_possible()) {
1616                 // TODO: no error for user
1617                 break;
1618             }
1619             switch (hfp_gsm_call_status()) {
1620                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1621                     switch (hfp_gsm_callsetup_status()) {
1622                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1623                             // note: number not used currently
1624                             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_INITIATED_BY_AG, 0, 0, "1234567");
1625                             // init call state for all connections
1626                             hfp_ag_trigger_outgoing_call();
1627                             // get first one and accept call
1628                             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1629                             if (hfp_connection) {
1630                                 hfp_ag_handle_outgoing_call_accepted(hfp_connection);
1631                             }
1632                             break;
1633                         default:
1634                             // TODO: no error for user
1635                             break;
1636                     }
1637                     break;
1638                 default:
1639                     // TODO: no error for user
1640                     break;
1641             }
1642             break;
1643         case HFP_AG_OUTGOING_REDIAL_INITIATED:{
1644             // directly reject call if number of free slots is exceeded
1645             if (!hfp_gsm_call_possible()){
1646                 hfp_connection->send_error = 1;
1647                 hfp_ag_run_for_context(hfp_connection);
1648                 break;
1649             }
1650 
1651             hfp_gsm_handler(HFP_AG_OUTGOING_REDIAL_INITIATED, 0, 0, NULL);
1652             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1653 
1654             log_info("Redial last number");
1655             char * last_dialed_number = hfp_gsm_last_dialed_number();
1656 
1657             if (strlen(last_dialed_number) > 0){
1658                 log_info("Last number exists: accept call");
1659                 hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, last_dialed_number);
1660             } else {
1661                 log_info("log_infoLast number missing: reject call");
1662                 hfp_ag_handle_reject_outgoing_call();
1663             }
1664             break;
1665         }
1666         case HFP_AG_OUTGOING_CALL_REJECTED:
1667             hfp_ag_handle_reject_outgoing_call();
1668             break;
1669 
1670         case HFP_AG_OUTGOING_CALL_ACCEPTED:{
1671             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1672             if (!hfp_connection){
1673                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1674                 break;
1675             }
1676 
1677             hfp_connection->ok_pending = 1;
1678             hfp_ag_handle_outgoing_call_accepted(hfp_connection);
1679             break;
1680         }
1681         case HFP_AG_OUTGOING_CALL_RINGING:
1682             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1683             if (!hfp_connection){
1684                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in dialing state");
1685                 break;
1686             }
1687 
1688             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_RINGING, 0, 0, NULL);
1689             hfp_connection->call_state = HFP_CALL_OUTGOING_RINGING;
1690             hfp_ag_set_callsetup_indicator();
1691             hfp_ag_transfer_callsetup_state();
1692             break;
1693 
1694         case HFP_AG_OUTGOING_CALL_ESTABLISHED:{
1695             // get outgoing call
1696             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_RINGING);
1697             if (!hfp_connection){
1698                 hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1699             }
1700             if (!hfp_connection){
1701                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection");
1702                 break;
1703             }
1704 
1705             int CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS = hfp_gsm_callheld_status() == HFP_CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS;
1706             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_ESTABLISHED, 0, 0, NULL);
1707             hfp_connection->call_state = HFP_CALL_ACTIVE;
1708             hfp_ag_set_callsetup_indicator();
1709             hfp_ag_set_call_indicator();
1710             hfp_ag_transfer_call_state();
1711             hfp_ag_transfer_callsetup_state();
1712             if (CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS){
1713                 hfp_ag_set_callheld_indicator();
1714                 hfp_ag_transfer_callheld_state();
1715             }
1716             break;
1717         }
1718 
1719         case HFP_AG_CALL_HOLD_USER_BUSY:
1720             hfp_gsm_handler(HFP_AG_CALL_HOLD_USER_BUSY, 0, 0, NULL);
1721             hfp_ag_set_callsetup_indicator();
1722             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1723             hfp_connection->call_state = HFP_CALL_ACTIVE;
1724             log_info("AG: Call Waiting, User Busy");
1725             break;
1726 
1727         case HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1728             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1729             int call_held = hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1730 
1731             // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1732             if (call_held || call_setup_in_progress){
1733                 hfp_gsm_handler(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index,
1734                                 0, NULL);
1735 
1736             }
1737 
1738             if (call_setup_in_progress){
1739                 log_info("AG: Call Dropped, Accept new call");
1740                 hfp_ag_set_callsetup_indicator();
1741                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1742             } else {
1743                 log_info("AG: Call Dropped, Resume held call");
1744             }
1745             if (call_held){
1746                 hfp_ag_set_callheld_indicator();
1747                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1748             }
1749 
1750             hfp_connection->call_state = HFP_CALL_ACTIVE;
1751             break;
1752         }
1753 
1754         case HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1755             // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1756             // only update if callsetup changed
1757             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1758             hfp_gsm_handler(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index, 0,
1759                             NULL);
1760 
1761             if (call_setup_in_progress){
1762                 log_info("AG: Call on Hold, Accept new call");
1763                 hfp_ag_set_callsetup_indicator();
1764                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1765             } else {
1766                 log_info("AG: Swap calls");
1767             }
1768 
1769             hfp_ag_set_callheld_indicator();
1770             // hfp_ag_set_callheld_state(HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED);
1771             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1772             hfp_connection->call_state = HFP_CALL_ACTIVE;
1773             break;
1774         }
1775 
1776         case HFP_AG_CALL_HOLD_ADD_HELD_CALL:
1777             // Adds a held call to the conversation.
1778             if (hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD){
1779                 log_info("AG: Join 3-way-call");
1780                 hfp_gsm_handler(HFP_AG_CALL_HOLD_ADD_HELD_CALL, 0, 0, NULL);
1781                 hfp_ag_set_callheld_indicator();
1782                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1783                 hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CONFERENCE_CALL);
1784             }
1785             hfp_connection->call_state = HFP_CALL_ACTIVE;
1786             break;
1787         case HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS:
1788             // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer)
1789             hfp_gsm_handler(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, 0, 0, NULL);
1790             log_info("AG: Transfer call -> Connect two calls and disconnect");
1791             hfp_ag_set_call_indicator();
1792             hfp_ag_set_callheld_indicator();
1793             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1794             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1795             hfp_connection->call_state = HFP_CALL_IDLE;
1796             break;
1797 
1798         default:
1799             break;
1800     }
1801 
1802 
1803 }
1804 
1805 
1806 static void hfp_ag_send_call_status(hfp_connection_t * hfp_connection, int call_index){
1807     hfp_gsm_call_t * active_call = hfp_gsm_call(call_index);
1808     if (!active_call) return;
1809 
1810     int idx = active_call->index;
1811     hfp_enhanced_call_dir_t dir = active_call->direction;
1812     hfp_enhanced_call_status_t status = active_call->enhanced_status;
1813     hfp_enhanced_call_mode_t mode = active_call->mode;
1814     hfp_enhanced_call_mpty_t mpty = active_call->mpty;
1815     uint8_t type = active_call->clip_type;
1816     char * number = active_call->clip_number;
1817 
1818     char buffer[100];
1819     // TODO: check length of a buffer, to fit the MTU
1820     int offset = snprintf(buffer, sizeof(buffer), "\r\n%s: %d,%d,%d,%d,%d", HFP_LIST_CURRENT_CALLS, idx, dir, status, mode, mpty);
1821     if (number){
1822         offset += snprintf(buffer+offset, sizeof(buffer)-offset-3, ", \"%s\",%u", number, type);
1823     }
1824     snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n");
1825     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,
1826        mode, mpty, type, number);
1827     send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1828 }
1829 
1830 
1831 // sends pending command, returns if command was sent
1832 static int hfp_ag_send_commands(hfp_connection_t *hfp_connection){
1833 
1834     if (hfp_connection->send_status_of_current_calls){
1835         hfp_connection->ok_pending = 0;
1836         if (hfp_connection->next_call_index < hfp_gsm_get_number_of_calls()){
1837             hfp_connection->next_call_index++;
1838             hfp_ag_send_call_status(hfp_connection, hfp_connection->next_call_index);
1839             return 1;
1840         } else {
1841             // 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
1842             hfp_connection->next_call_index = 0;
1843             hfp_connection->ok_pending = 1;
1844             hfp_connection->send_status_of_current_calls = 0;
1845         }
1846     }
1847 
1848     if (hfp_connection->ag_notify_incoming_call_waiting){
1849         hfp_connection->ag_notify_incoming_call_waiting = 0;
1850         hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1851         return 1;
1852     }
1853 
1854     if (hfp_connection->command == HFP_CMD_UNKNOWN){
1855         hfp_connection->ok_pending = 0;
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     if (hfp_connection->send_error){
1863         hfp_connection->send_error = 0;
1864         hfp_connection->command = HFP_CMD_NONE;
1865         hfp_ag_send_error(hfp_connection->rfcomm_cid);
1866         return 1;
1867     }
1868 
1869     // note: before update AG indicators and ok_pending
1870     if (hfp_connection->send_response_and_hold_status){
1871         int status = hfp_connection->send_response_and_hold_status - 1;
1872         hfp_connection->send_response_and_hold_status = 0;
1873         hfp_ag_send_set_response_and_hold(hfp_connection->rfcomm_cid, status);
1874         return 1;
1875     }
1876 
1877     if (hfp_connection->ok_pending){
1878         hfp_connection->ok_pending = 0;
1879         hfp_connection->command = HFP_CMD_NONE;
1880         hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1881         return 1;
1882     }
1883 
1884     // update AG indicators
1885     if (hfp_connection->ag_indicators_status_update_bitmap){
1886         int i;
1887         for (i=0;i<hfp_connection->ag_indicators_nr;i++){
1888             if (get_bit(hfp_connection->ag_indicators_status_update_bitmap, i)){
1889                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, i, 0);
1890                 if (!hfp_connection->enable_status_update_for_ag_indicators) {
1891                     log_info("+CMER:3,0,0,0 - not sending update for '%s'", hfp_ag_indicators[i].name);
1892                     break;
1893                 }
1894                 hfp_ag_send_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[i]);
1895                 return 1;
1896             }
1897         }
1898     }
1899 
1900     if (hfp_connection->ag_send_no_carrier){
1901         hfp_connection->ag_send_no_carrier = false;
1902         hfp_ag_send_no_carrier(hfp_connection->rfcomm_cid);
1903         return 1;
1904     }
1905 
1906     if (hfp_connection->ag_ring){
1907         hfp_connection->ag_ring = 0;
1908         hfp_connection->command = HFP_CMD_NONE;
1909         hfp_ag_send_ring(hfp_connection->rfcomm_cid);
1910         return 1;
1911     }
1912 
1913     if (hfp_connection->ag_send_clip){
1914         hfp_connection->ag_send_clip = 0;
1915         hfp_connection->command = HFP_CMD_NONE;
1916         hfp_ag_send_clip(hfp_connection->rfcomm_cid);
1917         return 1;
1918     }
1919 
1920     if (hfp_connection->send_phone_number_for_voice_tag){
1921         hfp_connection->send_phone_number_for_voice_tag = 0;
1922         hfp_connection->command = HFP_CMD_NONE;
1923         hfp_connection->ok_pending = 1;
1924         hfp_ag_send_phone_number_for_voice_tag_cmd(hfp_connection->rfcomm_cid);
1925         return 1;
1926     }
1927 
1928     if (hfp_connection->send_subscriber_number){
1929         if (hfp_connection->next_subscriber_number_to_send < subscriber_numbers_count){
1930             hfp_phone_number_t phone = subscriber_numbers[hfp_connection->next_subscriber_number_to_send++];
1931             hfp_send_subscriber_number_cmd(hfp_connection->rfcomm_cid, phone.type, phone.number);
1932         } else {
1933             hfp_connection->send_subscriber_number = 0;
1934             hfp_connection->next_subscriber_number_to_send = 0;
1935             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1936         }
1937         hfp_connection->command = HFP_CMD_NONE;
1938         return 1;
1939     }
1940 
1941     if (hfp_connection->send_microphone_gain){
1942         hfp_connection->send_microphone_gain = 0;
1943         hfp_connection->command = HFP_CMD_NONE;
1944         hfp_ag_send_set_microphone_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->microphone_gain);
1945         return 1;
1946     }
1947 
1948     if (hfp_connection->send_speaker_gain){
1949         hfp_connection->send_speaker_gain = 0;
1950         hfp_connection->command = HFP_CMD_NONE;
1951         hfp_ag_send_set_speaker_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->speaker_gain);
1952         return 1;
1953     }
1954 
1955     if (hfp_connection->send_ag_status_indicators){
1956         hfp_connection->send_ag_status_indicators = 0;
1957         hfp_ag_send_retrieve_indicators_status_cmd(hfp_connection->rfcomm_cid);
1958         return 1;
1959     }
1960 
1961     return 0;
1962 }
1963 
1964 static void hfp_ag_run_for_context(hfp_connection_t *hfp_connection){
1965 
1966 	btstack_assert(hfp_connection != NULL);
1967 	btstack_assert(hfp_connection->local_role == HFP_ROLE_AG);
1968 
1969 	// during SDP query, RFCOMM CID is not set
1970 	if (hfp_connection->rfcomm_cid == 0) return;
1971 
1972     // assert command could be sent
1973     if (hci_can_send_command_packet_now() == 0) return;
1974 
1975     if ((hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) && hfp_connection->release_audio_connection){
1976         hfp_connection->state = HFP_W4_SCO_DISCONNECTED;
1977         hfp_connection->release_audio_connection = 0;
1978         gap_disconnect(hfp_connection->sco_handle);
1979         return;
1980     }
1981 
1982 #ifdef ENABLE_CC256X_ASSISTED_HFP
1983     // WBS Disassociate
1984     if (hfp_connection->cc256x_send_wbs_disassociate){
1985         hfp_connection->cc256x_send_wbs_disassociate = false;
1986         hci_send_cmd(&hci_ti_wbs_disassociate);
1987         return;
1988     }
1989     // Write Codec Config
1990     if (hfp_connection->cc256x_send_write_codec_config){
1991         hfp_connection->cc256x_send_write_codec_config = false;
1992         hfp_cc256x_write_codec_config(hfp_connection);
1993         return;
1994     }
1995     // WBS Associate
1996     if (hfp_connection->cc256x_send_wbs_associate){
1997         hfp_connection->cc256x_send_wbs_associate = false;
1998         hci_send_cmd(&hci_ti_wbs_associate, hfp_connection->acl_handle);
1999         return;
2000     }
2001 #endif
2002 #ifdef ENABLE_BCM_PCM_WBS
2003     // Enable WBS
2004     if (hfp_connection->bcm_send_enable_wbs){
2005         hfp_connection->bcm_send_enable_wbs = false;
2006         hci_send_cmd(&hci_bcm_enable_wbs, 1, 2);
2007         return;
2008     }
2009     // Write I2S/PCM params
2010     if (hfp_connection->bcm_send_write_i2spcm_interface_param){
2011         hfp_connection->bcm_send_write_i2spcm_interface_param = false;
2012         hfp_bcm_write_i2spcm_interface_param(hfp_connection);
2013         return;
2014     }
2015     // Disable WBS
2016     if (hfp_connection->bcm_send_disable_wbs){
2017         hfp_connection->bcm_send_disable_wbs = false;
2018         hci_send_cmd(&hci_bcm_enable_wbs, 0, 2);
2019         return;
2020     }
2021 #endif
2022 #if defined (ENABLE_CC256X_ASSISTED_HFP) || defined (ENABLE_BCM_PCM_WBS)
2023     if (hfp_connection->state == HFP_W4_WBS_SHUTDOWN){
2024         hfp_finalize_connection_context(hfp_connection);
2025         return;
2026     }
2027 #endif
2028 
2029     if (!rfcomm_can_send_packet_now(hfp_connection->rfcomm_cid)) {
2030         log_info("hfp_ag_run_for_context: request can send for 0x%02x", hfp_connection->rfcomm_cid);
2031         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
2032         return;
2033     }
2034 
2035     int cmd_sent = hfp_ag_send_commands(hfp_connection);
2036 
2037     if (!cmd_sent){
2038         cmd_sent = hfp_ag_run_for_context_service_level_connection(hfp_connection);
2039     }
2040 
2041     if (!cmd_sent){
2042         cmd_sent = hfp_ag_run_for_context_service_level_connection_queries(hfp_connection);
2043     }
2044 
2045     if (!cmd_sent){
2046         cmd_sent = hfp_ag_voice_recognition_state_machine(hfp_connection);
2047     }
2048 
2049     if (!cmd_sent){
2050         cmd_sent = call_setup_state_machine(hfp_connection);
2051     }
2052 
2053     // trigger codec exchange (must be before hfp_ag_run_for_audio_connection)
2054     if (!cmd_sent && (hfp_connection->command == HFP_CMD_NONE) && hfp_connection->trigger_codec_exchange){
2055         switch (hfp_connection->codecs_state){
2056             case HFP_CODECS_IDLE:
2057             case HFP_CODECS_RECEIVED_LIST:
2058             case HFP_CODECS_AG_RESEND_COMMON_CODEC:
2059             case HFP_CODECS_ERROR:
2060                 hfp_connection->trigger_codec_exchange = 0;
2061                 hfp_connection->command = HFP_CMD_AG_SEND_COMMON_CODEC;
2062                 break;
2063             default:
2064                 break;
2065         }
2066     }
2067 
2068     if (!cmd_sent){
2069         cmd_sent = hfp_ag_run_for_audio_connection(hfp_connection);
2070     }
2071 
2072 
2073     // disconnect
2074     if (!cmd_sent && (hfp_connection->command == HFP_CMD_NONE) && (hfp_connection->state == HFP_W2_DISCONNECT_RFCOMM)){
2075         hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED;
2076         rfcomm_disconnect(hfp_connection->rfcomm_cid);
2077     }
2078 
2079     if (cmd_sent){
2080         hfp_connection->command = HFP_CMD_NONE;
2081         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
2082     }
2083 }
2084 
2085 static int hfp_parser_is_end_of_line(uint8_t byte){
2086     return (byte == '\n') || (byte == '\r');
2087 }
2088 
2089 static void hfp_ag_handle_rfcomm_data(hfp_connection_t * hfp_connection, uint8_t *packet, uint16_t size){
2090     // assertion: size >= 1 as rfcomm.c does not deliver empty packets
2091     if (!hfp_connection) return;
2092     if (size < 1) return;
2093 
2094     hfp_log_rfcomm_message("HFP_AG_RX", packet, size);
2095 #ifdef ENABLE_HFP_AT_MESSAGES
2096     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_RECEIVED, (char *) packet);
2097 #endif
2098 
2099     // process messages byte-wise
2100     int pos;
2101     for (pos = 0; pos < size ; pos++){
2102         hfp_parse(hfp_connection, packet[pos], 0);
2103 
2104         // parse until end of line
2105         if (!hfp_parser_is_end_of_line(packet[pos])) continue;
2106 
2107         hfp_generic_status_indicator_t * indicator;
2108         switch(hfp_connection->command){
2109             case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
2110                 // dealt with in hfp_ag_voice_recognition_state_machine
2111                 break;
2112             case HFP_CMD_RESPONSE_AND_HOLD_QUERY:
2113                 if (hfp_ag_response_and_hold_active){
2114                     hfp_connection->send_response_and_hold_status = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD + 1;
2115                 }
2116                 hfp_connection->ok_pending = 1;
2117                 break;
2118             case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
2119                 switch(hfp_connection->ag_response_and_hold_action){
2120                     case HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD:
2121                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, hfp_connection);
2122                         break;
2123                     case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED:
2124                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF, hfp_connection);
2125                         break;
2126                     case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED:
2127                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF, hfp_connection);
2128                         break;
2129                     default:
2130                         break;
2131                 }
2132                 hfp_connection->ok_pending = 1;
2133                 break;
2134             case HFP_CMD_HF_INDICATOR_STATUS:
2135                 hfp_connection->command = HFP_CMD_NONE;
2136                 if (hfp_connection->parser_indicator_index < hfp_generic_status_indicators_nr){
2137                     indicator = &hfp_generic_status_indicators[hfp_connection->parser_indicator_index];
2138                 } else {
2139                     hfp_connection->send_error = 1;
2140                     break;
2141                 }
2142                 switch (indicator->uuid){
2143                     case 1: // enhanced security
2144                         if (hfp_connection->parser_indicator_value > 1) {
2145                             hfp_connection->send_error = 1;
2146                             return;
2147                         }
2148                         log_info("HF Indicator 'enhanced security' set to %u", (unsigned int) hfp_connection->parser_indicator_value);
2149                         break;
2150                     case 2: // battery level
2151                         if (hfp_connection->parser_indicator_value > 100){
2152                             hfp_connection->send_error = 1;
2153                             return;
2154                         }
2155                         log_info("HF Indicator 'battery' set to %u", (unsigned int) hfp_connection->parser_indicator_value);
2156                         break;
2157                     default:
2158                         log_info("HF Indicator unknown set to %u", (unsigned int) hfp_connection->parser_indicator_value);
2159                         break;
2160                 }
2161                 hfp_connection->ok_pending = 1;
2162                 break;
2163             case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
2164                 // expected by SLC state machine
2165                 if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) break;
2166                 hfp_connection->send_ag_indicators_segment = 0;
2167                 hfp_connection->send_ag_status_indicators = 1;
2168                 break;
2169             case HFP_CMD_LIST_CURRENT_CALLS:
2170                 hfp_connection->command = HFP_CMD_NONE;
2171                 hfp_connection->next_call_index = 0;
2172                 hfp_connection->send_status_of_current_calls = 1;
2173                 break;
2174             case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
2175                 if (subscriber_numbers_count == 0){
2176                     hfp_ag_send_ok(hfp_connection->rfcomm_cid);
2177                     break;
2178                 }
2179                 hfp_connection->next_subscriber_number_to_send = 0;
2180                 hfp_connection->send_subscriber_number = 1;
2181                 break;
2182             case HFP_CMD_TRANSMIT_DTMF_CODES:
2183             {
2184                 hfp_connection->command = HFP_CMD_NONE;
2185                 char buffer[2];
2186                 buffer[0] = (char) hfp_connection->ag_dtmf_code;
2187                 buffer[1] = 0;
2188                 hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_TRANSMIT_DTMF_CODES, buffer);
2189                 break;
2190             }
2191             case HFP_CMD_HF_REQUEST_PHONE_NUMBER:
2192                 hfp_connection->command = HFP_CMD_NONE;
2193                 hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_ATTACH_NUMBER_TO_VOICE_TAG);
2194                 break;
2195             case HFP_CMD_TURN_OFF_EC_AND_NR:
2196                 hfp_connection->command = HFP_CMD_NONE;
2197                 if (get_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION)){
2198                     hfp_connection->ok_pending = 1;
2199                     hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION, hfp_connection->ag_echo_and_noise_reduction);
2200                     log_info("AG: EC/NR = %u", hfp_connection->ag_echo_and_noise_reduction);
2201                 } else {
2202                     hfp_connection->send_error = 1;
2203                 }
2204                 break;
2205             case HFP_CMD_CALL_ANSWERED:
2206                 hfp_connection->command = HFP_CMD_NONE;
2207                 log_info("HFP: ATA");
2208                 hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, hfp_connection);
2209                 break;
2210             case HFP_CMD_HANG_UP_CALL:
2211                 hfp_connection->command = HFP_CMD_NONE;
2212                 hfp_connection->ok_pending = 1;
2213                 hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_HF, hfp_connection);
2214                 break;
2215             case HFP_CMD_CALL_HOLD: {
2216                 hfp_connection->command = HFP_CMD_NONE;
2217                 hfp_connection->ok_pending = 1;
2218 
2219                 switch (hfp_connection->ag_call_hold_action){
2220                     case 0:
2221                         // Releases all held calls or sets User Determined User Busy (UDUB) for a waiting call.
2222                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_USER_BUSY, hfp_connection);
2223                         break;
2224                     case 1:
2225                         // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
2226                         // Where both a held and a waiting call exist, the above procedures shall apply to the
2227                         // waiting call (i.e., not to the held call) in conflicting situation.
2228                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
2229                         break;
2230                     case 2:
2231                         // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
2232                         // Where both a held and a waiting call exist, the above procedures shall apply to the
2233                         // waiting call (i.e., not to the held call) in conflicting situation.
2234                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
2235                         break;
2236                     case 3:
2237                         // Adds a held call to the conversation.
2238                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_ADD_HELD_CALL, hfp_connection);
2239                         break;
2240                     case 4:
2241                         // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer).
2242                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, hfp_connection);
2243                         break;
2244                     default:
2245                         break;
2246                 }
2247 				hfp_connection->call_index = 0;
2248                 break;
2249             }
2250             case HFP_CMD_CALL_PHONE_NUMBER:
2251                 hfp_connection->command = HFP_CMD_NONE;
2252                 hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED_BY_HF, hfp_connection);
2253                 break;
2254             case HFP_CMD_REDIAL_LAST_NUMBER:
2255                 hfp_connection->command = HFP_CMD_NONE;
2256                 hfp_ag_call_sm(HFP_AG_OUTGOING_REDIAL_INITIATED, hfp_connection);
2257                 break;
2258             case HFP_CMD_ENABLE_CLIP:
2259                 hfp_connection->command = HFP_CMD_NONE;
2260                 log_info("hfp: clip set, now: %u", hfp_connection->clip_enabled);
2261                 hfp_connection->ok_pending = 1;
2262                 break;
2263             case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
2264                 hfp_connection->command = HFP_CMD_NONE;
2265                 log_info("hfp: call waiting notification set, now: %u", hfp_connection->call_waiting_notification_enabled);
2266                 hfp_connection->ok_pending = 1;
2267                 break;
2268             case HFP_CMD_SET_SPEAKER_GAIN:
2269                 hfp_connection->command = HFP_CMD_NONE;
2270                 hfp_connection->ok_pending = 1;
2271                 log_info("HF speaker gain = %u", hfp_connection->speaker_gain);
2272                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_SPEAKER_VOLUME, hfp_connection->speaker_gain);
2273                 break;
2274             case HFP_CMD_SET_MICROPHONE_GAIN:
2275                 hfp_connection->command = HFP_CMD_NONE;
2276                 hfp_connection->ok_pending = 1;
2277                 log_info("HF microphone gain = %u", hfp_connection->microphone_gain);
2278                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_MICROPHONE_VOLUME, hfp_connection->microphone_gain);
2279                 break;
2280             default:
2281                 break;
2282         }
2283     }
2284 }
2285 
2286 static void hfp_ag_run(void){
2287     btstack_linked_list_iterator_t it;
2288     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2289     while (btstack_linked_list_iterator_has_next(&it)){
2290         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2291         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2292         hfp_ag_run_for_context(hfp_connection);
2293     }
2294 }
2295 
2296 static void hfp_ag_rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2297     hfp_connection_t * hfp_connection = NULL;
2298     switch (packet_type){
2299         case RFCOMM_DATA_PACKET:
2300             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(channel);
2301 
2302             hfp_ag_handle_rfcomm_data(hfp_connection, packet, size);
2303             hfp_ag_run_for_context(hfp_connection);
2304             return;
2305         case HCI_EVENT_PACKET:
2306             if (packet[0] == RFCOMM_EVENT_CAN_SEND_NOW){
2307                 uint16_t rfcomm_cid = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
2308                 hfp_ag_run_for_context(get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid));
2309                 return;
2310             }
2311             hfp_handle_rfcomm_event(packet_type, channel, packet, size, HFP_ROLE_AG);
2312             break;
2313         default:
2314             break;
2315     }
2316 
2317     hfp_ag_run();
2318 }
2319 
2320 static void hfp_ag_hci_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2321     hfp_handle_hci_event(packet_type, channel, packet, size, HFP_ROLE_AG);
2322     hfp_ag_run();
2323 }
2324 
2325 void hfp_ag_init_codecs(int codecs_nr, const uint8_t * codecs){
2326     if (codecs_nr > HFP_MAX_NUM_CODECS){
2327         log_error("hfp_init: codecs_nr (%d) > HFP_MAX_NUM_CODECS (%d)", codecs_nr, HFP_MAX_NUM_CODECS);
2328         return;
2329     }
2330     int i;
2331     hfp_codecs_nr = codecs_nr;
2332     for (i=0; i < codecs_nr; i++){
2333         hfp_codecs[i] = codecs[i];
2334     }
2335 }
2336 
2337 void hfp_ag_init_supported_features(uint32_t supported_features){
2338     hfp_supported_features = supported_features;
2339 }
2340 
2341 void hfp_ag_init_ag_indicators(int ag_indicators_nr, const hfp_ag_indicator_t * ag_indicators){
2342     hfp_ag_indicators_nr = ag_indicators_nr;
2343     (void)memcpy(hfp_ag_indicators, ag_indicators,
2344                  ag_indicators_nr * sizeof(hfp_ag_indicator_t));
2345 }
2346 
2347 void hfp_ag_init_hf_indicators(int hf_indicators_nr, const hfp_generic_status_indicator_t * hf_indicators){
2348     if (hf_indicators_nr > HFP_MAX_NUM_INDICATORS) return;
2349     hfp_generic_status_indicators_nr = hf_indicators_nr;
2350     (void)memcpy(hfp_generic_status_indicators, hf_indicators,
2351                  hf_indicators_nr * sizeof(hfp_generic_status_indicator_t));
2352 }
2353 
2354 void hfp_ag_init_call_hold_services(int call_hold_services_nr, const char * call_hold_services[]){
2355     hfp_ag_call_hold_services_nr = call_hold_services_nr;
2356     (void)memcpy(hfp_ag_call_hold_services, call_hold_services,
2357                  call_hold_services_nr * sizeof(char *));
2358 }
2359 
2360 
2361 void hfp_ag_init(uint16_t rfcomm_channel_nr){
2362 
2363     hfp_init();
2364     hfp_ag_call_hold_services_nr = 0;
2365     hfp_ag_response_and_hold_active = 0;
2366     hfp_ag_indicators_nr = 0;
2367     hfp_codecs_nr = 0;
2368     hfp_supported_features = HFP_DEFAULT_AG_SUPPORTED_FEATURES;
2369     subscriber_numbers = NULL;
2370     subscriber_numbers_count = 0;
2371 
2372     hfp_ag_hci_event_callback_registration.callback = &hfp_ag_hci_event_packet_handler;
2373     hci_add_event_handler(&hfp_ag_hci_event_callback_registration);
2374 
2375     rfcomm_register_service(&hfp_ag_rfcomm_packet_handler, rfcomm_channel_nr, 0xffff);
2376 
2377     // used to set packet handler for outgoing rfcomm connections - could be handled by emitting an event to us
2378     hfp_set_ag_rfcomm_packet_handler(&hfp_ag_rfcomm_packet_handler);
2379 
2380     hfp_gsm_init();
2381 }
2382 
2383 void hfp_ag_deinit(void){
2384     hfp_deinit();
2385     hfp_gsm_deinit();
2386     (void) memset(&hfp_ag_hci_event_callback_registration, 0, sizeof(btstack_packet_callback_registration_t));
2387     (void) memset(&hfp_ag_callback, 0, sizeof(btstack_packet_handler_t));
2388     (void) memset(&hfp_ag_call_hold_services, 0, sizeof(hfp_ag_call_hold_services));
2389     (void) memset(&hfp_ag_response_and_hold_state, 0, sizeof(hfp_response_and_hold_state_t));
2390 }
2391 
2392 uint8_t hfp_ag_establish_service_level_connection(bd_addr_t bd_addr){
2393     return hfp_establish_service_level_connection(bd_addr, BLUETOOTH_SERVICE_CLASS_HANDSFREE, HFP_ROLE_AG);
2394 }
2395 
2396 uint8_t hfp_ag_release_service_level_connection(hci_con_handle_t acl_handle){
2397     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2398     if (!hfp_connection){
2399         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2400     }
2401 
2402     hfp_trigger_release_service_level_connection(hfp_connection);
2403     hfp_ag_run_for_context(hfp_connection);
2404     return ERROR_CODE_SUCCESS;
2405 }
2406 
2407 uint8_t hfp_ag_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle, hfp_cme_error_t error){
2408     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2409     if (!hfp_connection){
2410         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2411     }
2412 
2413     hfp_connection->extended_audio_gateway_error = 0;
2414     if (!hfp_connection->enable_extended_audio_gateway_error_report){
2415         return ERROR_CODE_COMMAND_DISALLOWED;
2416     }
2417 
2418     hfp_connection->extended_audio_gateway_error = error;
2419     hfp_ag_run_for_context(hfp_connection);
2420     return ERROR_CODE_SUCCESS;
2421 }
2422 
2423 static uint8_t hfp_ag_setup_audio_connection(hfp_connection_t * hfp_connection){
2424     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED){
2425         return ERROR_CODE_COMMAND_DISALLOWED;
2426     }
2427     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO){
2428         return ERROR_CODE_COMMAND_DISALLOWED;
2429     }
2430 
2431     hfp_connection->establish_audio_connection = 1;
2432     if (!has_codec_negotiation_feature(hfp_connection)){
2433         log_info("hfp_ag_establish_audio_connection - no codec negotiation feature, using CVSD");
2434         hfp_connection->negotiated_codec = HFP_CODEC_CVSD;
2435         hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
2436         // now, pick link settings
2437         hfp_init_link_settings(hfp_connection, hfp_ag_esco_s4_supported(hfp_connection));
2438 #ifdef ENABLE_CC256X_ASSISTED_HFP
2439         hfp_cc256x_prepare_for_sco(hfp_connection);
2440 #endif
2441         return ERROR_CODE_SUCCESS;
2442     }
2443 
2444     uint8_t i;
2445     bool codec_was_in_use = false;
2446     bool better_codec_can_be_used = false;
2447 
2448     for (i = 0; i<hfp_connection->remote_codecs_nr; i++){
2449         if (hfp_connection->negotiated_codec == hfp_connection->remote_codecs[i]){
2450             codec_was_in_use = true;
2451         } else if (hfp_connection->negotiated_codec < hfp_connection->remote_codecs[i]){
2452             better_codec_can_be_used = true;
2453         }
2454     }
2455 
2456     if (!codec_was_in_use || better_codec_can_be_used){
2457         hfp_connection->trigger_codec_exchange = 1;
2458         hfp_connection->codecs_state = HFP_CODECS_IDLE;
2459     }
2460     return ERROR_CODE_SUCCESS;
2461 }
2462 
2463 uint8_t hfp_ag_establish_audio_connection(hci_con_handle_t acl_handle){
2464     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2465     if (!hfp_connection){
2466         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2467     }
2468     uint8_t status = hfp_ag_setup_audio_connection(hfp_connection);
2469     if (status != ERROR_CODE_SUCCESS){
2470         return status;
2471     }
2472     hfp_ag_run_for_context(hfp_connection);
2473     return ERROR_CODE_SUCCESS;
2474 }
2475 
2476 uint8_t hfp_ag_release_audio_connection(hci_con_handle_t acl_handle){
2477     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2478     if (!hfp_connection){
2479         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2480     }
2481 
2482     if (hfp_connection->vra_state == HFP_VRA_VOICE_RECOGNITION_ACTIVATED){
2483         if (!hfp_connection->ag_audio_connection_opened_after_vra){
2484             return ERROR_CODE_COMMAND_DISALLOWED;
2485         }
2486     }
2487     uint8_t status = hfp_trigger_release_audio_connection(hfp_connection);
2488     if (status == ERROR_CODE_SUCCESS){
2489         hfp_ag_run_for_context(hfp_connection);
2490     }
2491     return status;
2492 }
2493 
2494 /**
2495  * @brief Enable in-band ring tone
2496  */
2497 void hfp_ag_set_use_in_band_ring_tone(int use_in_band_ring_tone){
2498     if (get_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE) == use_in_band_ring_tone){
2499         return;
2500     }
2501 
2502     hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE, use_in_band_ring_tone);
2503 
2504     btstack_linked_list_iterator_t it;
2505     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2506     while (btstack_linked_list_iterator_has_next(&it)){
2507         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2508         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2509         hfp_connection->command = HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING;
2510         hfp_ag_run_for_context(hfp_connection);
2511     }
2512 }
2513 
2514 /**
2515  * @brief Called from GSM
2516  */
2517 void hfp_ag_incoming_call(void){
2518     hfp_ag_call_sm(HFP_AG_INCOMING_CALL, NULL);
2519 }
2520 
2521 void hfp_ag_outgoing_call_initiated(const char * number) {
2522     UNUSED(number);
2523     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED_BY_AG, NULL);
2524 }
2525 
2526 /**
2527  * @brief number is stored.
2528  */
2529 void hfp_ag_set_clip(uint8_t type, const char * number){
2530     hfp_gsm_handler(HFP_AG_SET_CLIP, 0, type, number);
2531 }
2532 
2533 void hfp_ag_call_dropped(void){
2534     hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2535 }
2536 
2537 // call from AG UI
2538 void hfp_ag_answer_incoming_call(void){
2539     hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, NULL);
2540 }
2541 
2542 void hfp_ag_join_held_call(void){
2543     hfp_ag_call_sm(HFP_AG_HELD_CALL_JOINED_BY_AG, NULL);
2544 }
2545 
2546 void hfp_ag_terminate_call(void){
2547     hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_AG, NULL);
2548 }
2549 
2550 void hfp_ag_outgoing_call_ringing(void){
2551     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_RINGING, NULL);
2552 }
2553 
2554 void hfp_ag_outgoing_call_established(void){
2555     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ESTABLISHED, NULL);
2556 }
2557 
2558 void hfp_ag_outgoing_call_rejected(void){
2559     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_REJECTED, NULL);
2560 }
2561 
2562 void hfp_ag_outgoing_call_accepted(void){
2563     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ACCEPTED, NULL);
2564 }
2565 
2566 void hfp_ag_hold_incoming_call(void){
2567     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, NULL);
2568 }
2569 
2570 void hfp_ag_accept_held_incoming_call(void) {
2571     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, NULL);
2572 }
2573 
2574 void hfp_ag_reject_held_incoming_call(void){
2575     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, NULL);
2576 }
2577 
2578 static void hfp_ag_set_ag_indicator(const char * name, int value){
2579     int indicator_index = get_ag_indicator_index_for_name(name);
2580     if (indicator_index < 0) return;
2581     hfp_ag_indicators[indicator_index].status = value;
2582 
2583     btstack_linked_list_iterator_t it;
2584     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2585     while (btstack_linked_list_iterator_has_next(&it)){
2586         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2587         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2588         if (!hfp_connection->ag_indicators[indicator_index].enabled) {
2589             log_info("Requested AG indicator '%s' update to %u, but it is not enabled", hfp_ag_indicators[indicator_index].name, value);
2590             continue;
2591         }
2592         log_info("AG indicator '%s' changed to %u, request transfer status", hfp_ag_indicators[indicator_index].name, value);
2593         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
2594         hfp_ag_run_for_context(hfp_connection);
2595     }
2596 }
2597 
2598 uint8_t hfp_ag_set_registration_status(int registration_status){
2599     if ((registration_status < 0) || (registration_status > 1)){
2600         return ERROR_CODE_COMMAND_DISALLOWED;
2601     }
2602 
2603     if ( (registration_status == 0) && (hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
2604 
2605         // if network goes away wihle a call is active:
2606         // - the  call gets dropped
2607         // - we send NO CARRIER
2608         // NOTE: the CALL=0 has to be sent before NO CARRIER
2609 
2610         hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2611 
2612         btstack_linked_list_iterator_t it;
2613         btstack_linked_list_iterator_init(&it, hfp_get_connections());
2614         while (btstack_linked_list_iterator_has_next(&it)){
2615             hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2616             hfp_connection->ag_send_no_carrier = true;
2617         }
2618     }
2619     hfp_ag_set_ag_indicator("service", registration_status);
2620     return ERROR_CODE_SUCCESS;
2621 }
2622 
2623 uint8_t hfp_ag_set_signal_strength(int signal_strength){
2624     if ((signal_strength < 0) || (signal_strength > 5)){
2625         return ERROR_CODE_COMMAND_DISALLOWED;
2626     }
2627 
2628     hfp_ag_set_ag_indicator("signal", signal_strength);
2629     return ERROR_CODE_SUCCESS;
2630 }
2631 
2632 uint8_t hfp_ag_set_roaming_status(int roaming_status){
2633     if ((roaming_status < 0) || (roaming_status > 1)){
2634         return ERROR_CODE_COMMAND_DISALLOWED;
2635     }
2636 
2637     hfp_ag_set_ag_indicator("roam", roaming_status);
2638     return ERROR_CODE_SUCCESS;
2639 }
2640 
2641 uint8_t hfp_ag_set_battery_level(int battery_level){
2642     if ((battery_level < 0) || (battery_level > 5)){
2643         return ERROR_CODE_COMMAND_DISALLOWED;
2644     }
2645     hfp_ag_set_ag_indicator("battchg", battery_level);
2646     return ERROR_CODE_SUCCESS;
2647 }
2648 
2649 uint8_t hfp_ag_activate_voice_recognition(hci_con_handle_t acl_handle){
2650     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2651     if (!hfp_connection){
2652         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2653     }
2654     uint8_t status = hfp_ag_can_activate_voice_recognition_for_connection(hfp_connection);
2655     if (status == ERROR_CODE_SUCCESS){
2656         hfp_connection->ag_activate_voice_recognition_value = 1;
2657         hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_ACTIVATED;
2658         hfp_connection->command = HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
2659         hfp_connection->ag_audio_connection_opened_after_vra = hfp_ag_is_audio_connection_active(hfp_connection);
2660         hfp_ag_run_for_context(hfp_connection);
2661     }
2662     return status;
2663 }
2664 
2665 uint8_t hfp_ag_deactivate_voice_recognition(hci_con_handle_t acl_handle){
2666     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2667     if (!hfp_connection){
2668         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2669     }
2670     uint8_t status = hfp_ag_can_deactivate_voice_recognition_for_connection(hfp_connection);
2671     if (status == ERROR_CODE_SUCCESS){
2672         hfp_connection->ag_activate_voice_recognition_value = 0;
2673         hfp_connection->vra_state_requested = HFP_VRA_W2_SEND_VOICE_RECOGNITION_OFF;
2674         hfp_connection->command = HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
2675         hfp_ag_run_for_context(hfp_connection);
2676     }
2677     return status;
2678 }
2679 
2680 
2681 uint8_t hfp_ag_activate_enhanced_voice_recognition(hci_con_handle_t acl_handle){
2682     if (!get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)){
2683         return ERROR_CODE_COMMAND_DISALLOWED;
2684     }
2685 
2686     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2687     if (!hfp_connection){
2688         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2689     }
2690 
2691     if (!get_bit(hfp_connection->remote_supported_features, HFP_HFSF_VOICE_RECOGNITION_FUNCTION)){
2692         return ERROR_CODE_COMMAND_DISALLOWED;
2693     }
2694 
2695     hfp_connection->command = HFP_CMD_AG_ACTIVATE_ENHANCED_VOICE_RECOGNITION;
2696     hfp_connection->ag_vra_state = HFP_VOICE_RECOGNITION_STATE_AG_READY;
2697     hfp_connection->ag_vra_status = HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_ACTIVATED;
2698     hfp_ag_run_for_context(hfp_connection);
2699     return ERROR_CODE_SUCCESS;
2700 }
2701 
2702 uint8_t hfp_ag_deactivate_enhanced_voice_recognition(hci_con_handle_t acl_handle){
2703     if (!get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)){
2704         return ERROR_CODE_COMMAND_DISALLOWED;
2705     }
2706 
2707     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2708     if (!hfp_connection){
2709         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2710     }
2711 
2712     if (!get_bit(hfp_connection->remote_supported_features, HFP_HFSF_VOICE_RECOGNITION_FUNCTION)){
2713         return ERROR_CODE_COMMAND_DISALLOWED;
2714     }
2715 
2716     hfp_connection->command = HFP_CMD_AG_ACTIVATE_ENHANCED_VOICE_RECOGNITION;
2717     hfp_connection->ag_vra_state = HFP_VOICE_RECOGNITION_STATE_AG_READY;
2718     hfp_connection->ag_vra_status = HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_OFF;
2719     hfp_ag_run_for_context(hfp_connection);
2720     return ERROR_CODE_SUCCESS;
2721 }
2722 
2723 uint8_t hfp_ag_enhanced_voice_recognition_state(hci_con_handle_t acl_handle, hfp_voice_recognition_state_t state){
2724     if (!get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)){
2725         return ERROR_CODE_COMMAND_DISALLOWED;
2726     }
2727 
2728     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2729     if (!hfp_connection){
2730         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2731     }
2732 
2733     if (!get_bit(hfp_connection->remote_supported_features, HFP_HFSF_VOICE_RECOGNITION_FUNCTION)){
2734         return ERROR_CODE_COMMAND_DISALLOWED;
2735     }
2736 
2737     hfp_connection->command = HFP_CMD_AG_ACTIVATE_ENHANCED_VOICE_RECOGNITION;
2738     hfp_connection->ag_vra_state = state;
2739     hfp_connection->ag_vra_status = HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_STATUS;
2740     hfp_ag_run_for_context(hfp_connection);
2741     return ERROR_CODE_SUCCESS;
2742 }
2743 
2744 uint8_t hfp_ag_enhanced_voice_recognition_starting_sound(hci_con_handle_t acl_handle){
2745     return hfp_ag_enhanced_voice_recognition_state(acl_handle, HFP_VOICE_RECOGNITION_STATE_AG_IS_SENDING_AUDIO_TO_HF);
2746 }
2747 uint8_t hfp_ag_enhanced_voice_recognition_ready_for_input(hci_con_handle_t acl_handle){
2748     return hfp_ag_enhanced_voice_recognition_state(acl_handle, HFP_VOICE_RECOGNITION_STATE_AG_READY_TO_ACCEPT_AUDIO_INPUT);
2749 }
2750 uint8_t hfp_ag_enhanced_voice_recognition_processing_input(hci_con_handle_t acl_handle){
2751     return hfp_ag_enhanced_voice_recognition_state(acl_handle, HFP_VOICE_RECOGNITION_STATE_AG_IS_PROCESSING_AUDIO_INPUT);
2752 }
2753 
2754 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){
2755     if (!get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)){
2756         return ERROR_CODE_COMMAND_DISALLOWED;
2757     }
2758 
2759     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2760     if (!hfp_connection){
2761         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2762     }
2763 
2764     if (!get_bit(hfp_connection->remote_supported_features, HFP_HFSF_VOICE_RECOGNITION_FUNCTION)){
2765         return ERROR_CODE_COMMAND_DISALLOWED;
2766     }
2767 
2768     hfp_connection->command = HFP_CMD_AG_ACTIVATE_ENHANCED_VOICE_RECOGNITION;
2769     hfp_connection->ag_vra_state = state;
2770     hfp_connection->ag_vra_status = HFP_VRA_W4_ENHANCED_VOICE_RECOGNITION_MSG;
2771     hfp_connection->ag_msg = msg;
2772     hfp_ag_run_for_context(hfp_connection);
2773     return ERROR_CODE_SUCCESS;
2774 }
2775 
2776 uint8_t hfp_ag_set_microphone_gain(hci_con_handle_t acl_handle, int gain){
2777     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2778     if (!hfp_connection){
2779         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2780     }
2781 
2782     if ((gain < 0) || (gain > 15)){
2783         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
2784         return ERROR_CODE_COMMAND_DISALLOWED;
2785     }
2786 
2787     if (hfp_connection->microphone_gain != gain){
2788         hfp_connection->command = HFP_CMD_SET_MICROPHONE_GAIN;
2789         hfp_connection->microphone_gain = gain;
2790         hfp_connection->send_microphone_gain = 1;
2791     }
2792     hfp_ag_run_for_context(hfp_connection);
2793     return ERROR_CODE_SUCCESS;
2794 }
2795 
2796 uint8_t hfp_ag_set_speaker_gain(hci_con_handle_t acl_handle, int gain){
2797     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2798     if (!hfp_connection){
2799         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2800     }
2801 
2802     if ((gain < 0) || (gain > 15)){
2803         log_info("Valid range for a gain is [0..15]. Currently sent: %d", gain);
2804         return ERROR_CODE_COMMAND_DISALLOWED;
2805     }
2806 
2807     if (hfp_connection->speaker_gain != gain){
2808         hfp_connection->speaker_gain = gain;
2809         hfp_connection->send_speaker_gain = 1;
2810     }
2811     hfp_ag_run_for_context(hfp_connection);
2812     return ERROR_CODE_SUCCESS;
2813 }
2814 
2815 uint8_t hfp_ag_send_phone_number_for_voice_tag(hci_con_handle_t acl_handle, const char * number){
2816     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2817     if (!hfp_connection){
2818         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2819     }
2820 
2821     hfp_ag_set_clip(0, number);
2822     hfp_connection->send_phone_number_for_voice_tag = 1;
2823     return ERROR_CODE_SUCCESS;
2824 }
2825 
2826 uint8_t hfp_ag_reject_phone_number_for_voice_tag(hci_con_handle_t acl_handle){
2827     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2828     if (!hfp_connection){
2829         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2830     }
2831 
2832     hfp_connection->send_error = 1;
2833     return ERROR_CODE_SUCCESS;
2834 }
2835 
2836 uint8_t hfp_ag_send_dtmf_code_done(hci_con_handle_t acl_handle){
2837     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2838     if (!hfp_connection){
2839         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2840     }
2841 
2842     hfp_connection->ok_pending = 1;
2843     return ERROR_CODE_SUCCESS;
2844 }
2845 
2846 void hfp_ag_set_subcriber_number_information(hfp_phone_number_t * numbers, int numbers_count){
2847     subscriber_numbers = numbers;
2848     subscriber_numbers_count = numbers_count;
2849 }
2850 
2851 void hfp_ag_clear_last_dialed_number(void){
2852     hfp_gsm_clear_last_dialed_number();
2853 }
2854 
2855 void hfp_ag_set_last_dialed_number(const char * number){
2856     hfp_gsm_set_last_dialed_number(number);
2857 }
2858 
2859 uint8_t hfp_ag_notify_incoming_call_waiting(hci_con_handle_t acl_handle){
2860     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2861     if (!hfp_connection){
2862         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2863     }
2864 
2865     if (!hfp_connection->call_waiting_notification_enabled){
2866         return ERROR_CODE_COMMAND_DISALLOWED;
2867     }
2868 
2869     hfp_connection->ag_notify_incoming_call_waiting = 1;
2870     hfp_ag_run_for_context(hfp_connection);
2871     return ERROR_CODE_SUCCESS;
2872 }
2873 
2874 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){
2875 	if (!name){
2876 		name = default_hfp_ag_service_name;
2877 	}
2878 	hfp_create_sdp_record(service, service_record_handle, BLUETOOTH_SERVICE_CLASS_HANDSFREE_AUDIO_GATEWAY, rfcomm_channel_nr, name);
2879 
2880 	/*
2881 	 * 0x01 – Ability to reject a call
2882 	 * 0x00 – No ability to reject a call
2883 	 */
2884 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0301);    // Hands-Free Profile - Network
2885 	de_add_number(service, DE_UINT, DE_SIZE_8, ability_to_reject_call);
2886 
2887 	// Construct SupportedFeatures for SDP bitmap:
2888 	//
2889 	// "The values of the “SupportedFeatures” bitmap given in Table 5.4 shall be the same as the values
2890 	//  of the Bits 0 to 4 of the unsolicited result code +BRSF"
2891 	//
2892 	// Wide band speech (bit 5) requires Codec negotiation
2893 	//
2894 	uint16_t sdp_features = supported_features & 0x1f;
2895 	if ( (wide_band_speech == 1) && (supported_features & (1 << HFP_AGSF_CODEC_NEGOTIATION))){
2896 		sdp_features |= 1 << 5;
2897 	}
2898 
2899     if (supported_features & (1 << HFP_AGSF_ENHANCED_VOICE_RECOGNITION_STATUS)){
2900         sdp_features |= 1 << 6;
2901     }
2902 
2903     if (supported_features & (1 << HFP_AGSF_VOICE_RECOGNITION_TEXT)){
2904         sdp_features |= 1 << 7;
2905     }
2906 
2907 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);    // Hands-Free Profile - SupportedFeatures
2908 	de_add_number(service, DE_UINT, DE_SIZE_16, sdp_features);
2909 }
2910 
2911 void hfp_ag_register_packet_handler(btstack_packet_handler_t callback){
2912 	btstack_assert(callback != NULL);
2913 
2914 	hfp_ag_callback = callback;
2915 	hfp_set_ag_callback(callback);
2916 }
2917