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