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