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