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