xref: /btstack/src/classic/hfp_ag.c (revision eb4dccece89f38c3fa8fb13197f36188f58d954a)
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 callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1162     int callheld_indicator_index = get_ag_indicator_index_for_name("callheld");
1163     int call_indicator_index = get_ag_indicator_index_for_name("call");
1164 
1165     switch (event){
1166         case HFP_AG_INCOMING_CALL:
1167             switch (hfp_gsm_call_status()){
1168                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1169                     switch (hfp_gsm_callsetup_status()){
1170                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1171                             hfp_gsm_handler(HFP_AG_INCOMING_CALL, 0, 0, NULL);
1172                             hfp_ag_set_callsetup_indicator();
1173                             hfp_ag_trigger_incoming_call();
1174                             log_info("AG rings");
1175                             break;
1176                         default:
1177                             break;
1178                     }
1179                     break;
1180                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1181                     switch (hfp_gsm_callsetup_status()){
1182                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1183                             hfp_gsm_handler(HFP_AG_INCOMING_CALL, 0, 0, NULL);
1184                             hfp_ag_set_callsetup_indicator();
1185                             hfp_ag_trigger_incoming_call();
1186                             log_info("AG call waiting");
1187                             break;
1188                         default:
1189                             break;
1190                     }
1191                     break;
1192                 default:
1193                     break;
1194             }
1195             break;
1196         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG:
1197             switch (hfp_gsm_call_status()){
1198                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1199                     switch (hfp_gsm_callsetup_status()){
1200                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1201                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, 0, 0, NULL);
1202                             hfp_ag_set_call_indicator();
1203                             hfp_ag_set_callsetup_indicator();
1204                             hfp_ag_ag_accept_call();
1205                             log_info("AG answers call, accept call by GSM");
1206                             break;
1207                         default:
1208                             break;
1209                     }
1210                     break;
1211                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1212                     switch (hfp_gsm_callsetup_status()){
1213                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1214                             log_info("AG: current call is placed on hold, incoming call gets active");
1215                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, 0, 0, NULL);
1216                             hfp_ag_set_callsetup_indicator();
1217                             hfp_ag_set_callheld_indicator();
1218                             hfp_ag_transfer_callsetup_state();
1219                             hfp_ag_transfer_callheld_state();
1220                             break;
1221                         default:
1222                             break;
1223                     }
1224                     break;
1225                 default:
1226                     break;
1227             }
1228             break;
1229 
1230         case HFP_AG_HELD_CALL_JOINED_BY_AG:
1231             switch (hfp_gsm_call_status()){
1232                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1233                     switch (hfp_gsm_callheld_status()){
1234                         case HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED:
1235                             log_info("AG: joining held call with active call");
1236                             hfp_gsm_handler(HFP_AG_HELD_CALL_JOINED_BY_AG, 0, 0, NULL);
1237                             hfp_ag_set_callheld_indicator();
1238                             hfp_ag_transfer_callheld_state();
1239                             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CONFERENCE_CALL);
1240                             break;
1241                         default:
1242                             break;
1243                     }
1244                     break;
1245                 default:
1246                     break;
1247             }
1248             break;
1249 
1250         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF:
1251             switch (hfp_gsm_call_status()){
1252                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1253                     switch (hfp_gsm_callsetup_status()){
1254                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1255                             hfp_gsm_handler(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, 0, 0, NULL);
1256                             hfp_ag_set_callsetup_indicator();
1257                             hfp_ag_set_call_indicator();
1258                             hfp_ag_hf_accept_call(hfp_connection);
1259                             hfp_connection->ok_pending = 1;
1260                             log_info("HF answers call, accept call by GSM");
1261                             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_ANSWERED);
1262                             break;
1263                         default:
1264                             break;
1265                     }
1266                     break;
1267                 default:
1268                     break;
1269             }
1270             break;
1271 
1272         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG:
1273             switch (hfp_gsm_call_status()){
1274                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1275                     switch (hfp_gsm_callsetup_status()){
1276                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1277                             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, 0, 0, NULL);
1278                             hfp_ag_response_and_hold_active = 1;
1279                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1280                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1281                             // as with regualr call
1282                             hfp_ag_set_call_indicator();
1283                             hfp_ag_set_callsetup_indicator();
1284                             hfp_ag_ag_accept_call();
1285                             log_info("AG response and hold - hold by AG");
1286                             break;
1287                         default:
1288                             break;
1289                     }
1290                     break;
1291                 default:
1292                     break;
1293             }
1294             break;
1295 
1296         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF:
1297             switch (hfp_gsm_call_status()){
1298                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1299                     switch (hfp_gsm_callsetup_status()){
1300                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1301                             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, 0, 0, NULL);
1302                             hfp_ag_response_and_hold_active = 1;
1303                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1304                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1305                             // as with regualr call
1306                             hfp_ag_set_call_indicator();
1307                             hfp_ag_set_callsetup_indicator();
1308                             hfp_ag_hf_accept_call(hfp_connection);
1309                             log_info("AG response and hold - hold by HF");
1310                             break;
1311                         default:
1312                             break;
1313                     }
1314                     break;
1315                 default:
1316                     break;
1317             }
1318             break;
1319 
1320         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG:
1321         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF:
1322             if (!hfp_ag_response_and_hold_active) break;
1323             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1324             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, 0, 0, NULL);
1325             hfp_ag_response_and_hold_active = 0;
1326             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED;
1327             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1328             log_info("Held Call accepted and active");
1329             break;
1330 
1331         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG:
1332         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF:
1333             if (!hfp_ag_response_and_hold_active) break;
1334             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1335             hfp_gsm_handler(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, 0, 0, NULL);
1336             hfp_ag_response_and_hold_active = 0;
1337             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1338             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1339             // from terminate by ag
1340             hfp_ag_set_call_indicator();
1341             hfp_ag_trigger_terminate_call();
1342             break;
1343 
1344         case HFP_AG_TERMINATE_CALL_BY_HF:
1345             switch (hfp_gsm_call_status()){
1346                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1347                     switch (hfp_gsm_callsetup_status()){
1348                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1349                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1350                             hfp_ag_set_callsetup_indicator();
1351                             hfp_ag_transfer_callsetup_state();
1352                             hfp_ag_trigger_reject_call();
1353                             log_info("HF Rejected Incoming call, AG terminate call");
1354                             break;
1355                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1356                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1357                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1358                             hfp_ag_set_callsetup_indicator();
1359                             hfp_ag_transfer_callsetup_state();
1360                             log_info("AG terminate outgoing call process");
1361                             break;
1362                         default:
1363                             break;
1364                     }
1365                     break;
1366                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1367                     hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_HF, 0, 0, NULL);
1368                     hfp_ag_set_callsetup_indicator();
1369                     hfp_ag_set_call_indicator();
1370                     hfp_ag_trigger_terminate_call();
1371                     log_info("AG terminate call");
1372                     break;
1373                 default:
1374                     break;
1375             }
1376             hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CALL_TERMINATED);
1377             break;
1378 
1379         case HFP_AG_TERMINATE_CALL_BY_AG:
1380             switch (hfp_gsm_call_status()){
1381                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1382                     switch (hfp_gsm_callsetup_status()){
1383                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1384                             hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_AG, 0, 0, NULL);
1385                             hfp_ag_set_callsetup_indicator();
1386                             hfp_ag_trigger_reject_call();
1387                             log_info("AG Rejected Incoming call, AG terminate call");
1388                             break;
1389                         default:
1390                             break;
1391                     }
1392                     break;
1393                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1394                     hfp_gsm_handler(HFP_AG_TERMINATE_CALL_BY_AG, 0, 0, NULL);
1395                     hfp_ag_set_callsetup_indicator();
1396                     hfp_ag_set_call_indicator();
1397                     hfp_ag_trigger_terminate_call();
1398                     log_info("AG terminate call");
1399                     break;
1400                 default:
1401                     break;
1402             }
1403             break;
1404         case HFP_AG_CALL_DROPPED:
1405             switch (hfp_gsm_call_status()){
1406                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1407                     switch (hfp_gsm_callsetup_status()){
1408                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1409                             hfp_ag_stop_ringing();
1410                             log_info("Incoming call interrupted");
1411                             break;
1412                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1413                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1414                             log_info("Outgoing call interrupted\n");
1415                             log_info("AG notify call dropped\n");
1416                             break;
1417                         default:
1418                             break;
1419                     }
1420                     hfp_gsm_handler(HFP_AG_CALL_DROPPED, 0, 0, NULL);
1421                     hfp_ag_set_callsetup_indicator();
1422                     hfp_ag_transfer_callsetup_state();
1423                     hfp_ag_trigger_terminate_call();
1424                     break;
1425                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1426                     if (hfp_ag_response_and_hold_active) {
1427                         hfp_gsm_handler(HFP_AG_CALL_DROPPED, 0, 0, NULL);
1428                         hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1429                         hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1430                     }
1431                     hfp_gsm_handler(HFP_AG_CALL_DROPPED, 0, 0, NULL);
1432                     hfp_ag_set_callsetup_indicator();
1433                     hfp_ag_set_call_indicator();
1434                     hfp_ag_trigger_terminate_call();
1435                     log_info("AG notify call dropped");
1436                     break;
1437                 default:
1438                     break;
1439             }
1440             break;
1441 
1442         case HFP_AG_OUTGOING_CALL_INITIATED_BY_HF:
1443             // directly reject call if number of free slots is exceeded
1444             if (!hfp_gsm_call_possible()){
1445                 hfp_connection->send_error = 1;
1446                 hfp_ag_run_for_context(hfp_connection);
1447                 break;
1448             }
1449 
1450             // note: number not used currently
1451             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_INITIATED_BY_HF, 0, 0, (const char *) &hfp_connection->line_buffer[3]);
1452 
1453             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1454 
1455             hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, (const char *) &hfp_connection->line_buffer[3]);
1456             break;
1457 
1458         case HFP_AG_OUTGOING_CALL_INITIATED_BY_AG:
1459             // directly reject call if number of free slots is exceeded
1460             if (!hfp_gsm_call_possible()) {
1461                 // TODO: no error for user
1462                 break;
1463             }
1464             switch (hfp_gsm_call_status()) {
1465                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1466                     switch (hfp_gsm_callsetup_status()) {
1467                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1468                             // note: number not used currently
1469                             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_INITIATED_BY_AG, 0, 0, "1234567");
1470                             // init call state for all connections
1471                             hfp_ag_trigger_outgoing_call();
1472                             // get first one and accept call
1473                             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1474                             if (hfp_connection) {
1475                                 hfp_ag_handle_outgoing_call_accepted(hfp_connection);
1476                             }
1477                             break;
1478                         default:
1479                             // TODO: no error for user
1480                             break;
1481                     }
1482                     break;
1483                 default:
1484                     // TODO: no error for user
1485                     break;
1486             }
1487             break;
1488         case HFP_AG_OUTGOING_REDIAL_INITIATED:{
1489             // directly reject call if number of free slots is exceeded
1490             if (!hfp_gsm_call_possible()){
1491                 hfp_connection->send_error = 1;
1492                 hfp_ag_run_for_context(hfp_connection);
1493                 break;
1494             }
1495 
1496             hfp_gsm_handler(HFP_AG_OUTGOING_REDIAL_INITIATED, 0, 0, NULL);
1497             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1498 
1499             log_info("Redial last number");
1500             char * last_dialed_number = hfp_gsm_last_dialed_number();
1501 
1502             if (strlen(last_dialed_number) > 0){
1503                 log_info("Last number exists: accept call");
1504                 hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, last_dialed_number);
1505             } else {
1506                 log_info("log_infoLast number missing: reject call");
1507                 hfp_ag_handle_reject_outgoing_call();
1508             }
1509             break;
1510         }
1511         case HFP_AG_OUTGOING_CALL_REJECTED:
1512             hfp_ag_handle_reject_outgoing_call();
1513             break;
1514 
1515         case HFP_AG_OUTGOING_CALL_ACCEPTED:{
1516             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1517             if (!hfp_connection){
1518                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1519                 break;
1520             }
1521 
1522             hfp_connection->ok_pending = 1;
1523             hfp_ag_handle_outgoing_call_accepted(hfp_connection);
1524             break;
1525         }
1526         case HFP_AG_OUTGOING_CALL_RINGING:
1527             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1528             if (!hfp_connection){
1529                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in dialing state");
1530                 break;
1531             }
1532 
1533             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_RINGING, 0, 0, NULL);
1534             hfp_connection->call_state = HFP_CALL_OUTGOING_RINGING;
1535             hfp_ag_set_callsetup_indicator();
1536             hfp_ag_transfer_callsetup_state();
1537             break;
1538 
1539         case HFP_AG_OUTGOING_CALL_ESTABLISHED:{
1540             // get outgoing call
1541             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_RINGING);
1542             if (!hfp_connection){
1543                 hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1544             }
1545             if (!hfp_connection){
1546                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection");
1547                 break;
1548             }
1549 
1550             int CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS = hfp_gsm_callheld_status() == HFP_CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS;
1551             hfp_gsm_handler(HFP_AG_OUTGOING_CALL_ESTABLISHED, 0, 0, NULL);
1552             hfp_connection->call_state = HFP_CALL_ACTIVE;
1553             hfp_ag_set_callsetup_indicator();
1554             hfp_ag_set_call_indicator();
1555             hfp_ag_transfer_call_state();
1556             hfp_ag_transfer_callsetup_state();
1557             if (CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS){
1558                 hfp_ag_set_callheld_indicator();
1559                 hfp_ag_transfer_callheld_state();
1560             }
1561             break;
1562         }
1563 
1564         case HFP_AG_CALL_HOLD_USER_BUSY:
1565             hfp_gsm_handler(HFP_AG_CALL_HOLD_USER_BUSY, 0, 0, NULL);
1566             hfp_ag_set_callsetup_indicator();
1567             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1568             hfp_connection->call_state = HFP_CALL_ACTIVE;
1569             log_info("AG: Call Waiting, User Busy");
1570             break;
1571 
1572         case HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1573             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1574             int call_held = hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1575 
1576             // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1577             if (call_held || call_setup_in_progress){
1578                 hfp_gsm_handler(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index,
1579                                 0, NULL);
1580 
1581             }
1582 
1583             if (call_setup_in_progress){
1584                 log_info("AG: Call Dropped, Accept new call");
1585                 hfp_ag_set_callsetup_indicator();
1586                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1587             } else {
1588                 log_info("AG: Call Dropped, Resume held call");
1589             }
1590             if (call_held){
1591                 hfp_ag_set_callheld_indicator();
1592                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1593             }
1594 
1595             hfp_connection->call_state = HFP_CALL_ACTIVE;
1596             break;
1597         }
1598 
1599         case HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1600             // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1601             // only update if callsetup changed
1602             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1603             hfp_gsm_handler(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index, 0,
1604                             NULL);
1605 
1606             if (call_setup_in_progress){
1607                 log_info("AG: Call on Hold, Accept new call");
1608                 hfp_ag_set_callsetup_indicator();
1609                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1610             } else {
1611                 log_info("AG: Swap calls");
1612             }
1613 
1614             hfp_ag_set_callheld_indicator();
1615             // hfp_ag_set_callheld_state(HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED);
1616             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1617             hfp_connection->call_state = HFP_CALL_ACTIVE;
1618             break;
1619         }
1620 
1621         case HFP_AG_CALL_HOLD_ADD_HELD_CALL:
1622             // Adds a held call to the conversation.
1623             if (hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD){
1624                 log_info("AG: Join 3-way-call");
1625                 hfp_gsm_handler(HFP_AG_CALL_HOLD_ADD_HELD_CALL, 0, 0, NULL);
1626                 hfp_ag_set_callheld_indicator();
1627                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1628                 hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_CONFERENCE_CALL);
1629             }
1630             hfp_connection->call_state = HFP_CALL_ACTIVE;
1631             break;
1632         case HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS:
1633             // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer)
1634             hfp_gsm_handler(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, 0, 0, NULL);
1635             log_info("AG: Transfer call -> Connect two calls and disconnect");
1636             hfp_ag_set_call_indicator();
1637             hfp_ag_set_callheld_indicator();
1638             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1639             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1640             hfp_connection->call_state = HFP_CALL_IDLE;
1641             break;
1642 
1643         default:
1644             break;
1645     }
1646 
1647 
1648 }
1649 
1650 
1651 static void hfp_ag_send_call_status(hfp_connection_t * hfp_connection, int call_index){
1652     hfp_gsm_call_t * active_call = hfp_gsm_call(call_index);
1653     if (!active_call) return;
1654 
1655     int idx = active_call->index;
1656     hfp_enhanced_call_dir_t dir = active_call->direction;
1657     hfp_enhanced_call_status_t status = active_call->enhanced_status;
1658     hfp_enhanced_call_mode_t mode = active_call->mode;
1659     hfp_enhanced_call_mpty_t mpty = active_call->mpty;
1660     uint8_t type = active_call->clip_type;
1661     char * number = active_call->clip_number;
1662 
1663     char buffer[100];
1664     // TODO: check length of a buffer, to fit the MTU
1665     int offset = snprintf(buffer, sizeof(buffer), "\r\n%s: %d,%d,%d,%d,%d", HFP_LIST_CURRENT_CALLS, idx, dir, status, mode, mpty);
1666     if (number){
1667         offset += snprintf(buffer+offset, sizeof(buffer)-offset-3, ", \"%s\",%u", number, type);
1668     }
1669     snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n");
1670     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,
1671        mode, mpty, type, number);
1672     send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1673 }
1674 
1675 
1676 // sends pending command, returns if command was sent
1677 static int hfp_ag_send_commands(hfp_connection_t *hfp_connection){
1678 
1679     if (hfp_connection->send_status_of_current_calls){
1680         hfp_connection->ok_pending = 0;
1681         if (hfp_connection->next_call_index < hfp_gsm_get_number_of_calls()){
1682             hfp_connection->next_call_index++;
1683             hfp_ag_send_call_status(hfp_connection, hfp_connection->next_call_index);
1684             return 1;
1685         } else {
1686             // 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
1687             hfp_connection->next_call_index = 0;
1688             hfp_connection->ok_pending = 1;
1689             hfp_connection->send_status_of_current_calls = 0;
1690         }
1691     }
1692 
1693     if (hfp_connection->ag_notify_incoming_call_waiting){
1694         hfp_connection->ag_notify_incoming_call_waiting = 0;
1695         hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1696         return 1;
1697     }
1698 
1699     if (hfp_connection->command == HFP_CMD_UNKNOWN){
1700         hfp_connection->ok_pending = 0;
1701         hfp_connection->send_error = 0;
1702         hfp_connection->command = HFP_CMD_NONE;
1703         hfp_ag_send_error(hfp_connection->rfcomm_cid);
1704         return 1;
1705     }
1706 
1707     if (hfp_connection->send_error){
1708         hfp_connection->send_error = 0;
1709         hfp_connection->command = HFP_CMD_NONE;
1710         hfp_ag_send_error(hfp_connection->rfcomm_cid);
1711         return 1;
1712     }
1713 
1714     // note: before update AG indicators and ok_pending
1715     if (hfp_connection->send_response_and_hold_status){
1716         int status = hfp_connection->send_response_and_hold_status - 1;
1717         hfp_connection->send_response_and_hold_status = 0;
1718         hfp_ag_send_set_response_and_hold(hfp_connection->rfcomm_cid, status);
1719         return 1;
1720     }
1721 
1722     if (hfp_connection->ok_pending){
1723         hfp_connection->ok_pending = 0;
1724         hfp_connection->command = HFP_CMD_NONE;
1725         hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1726         return 1;
1727     }
1728 
1729     // update AG indicators
1730     if (hfp_connection->ag_indicators_status_update_bitmap){
1731         int i;
1732         for (i=0;i<hfp_connection->ag_indicators_nr;i++){
1733             if (get_bit(hfp_connection->ag_indicators_status_update_bitmap, i)){
1734                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, i, 0);
1735                 if (!hfp_connection->enable_status_update_for_ag_indicators) {
1736                     log_info("+CMER:3,0,0,0 - not sending update for '%s'", hfp_ag_indicators[i].name);
1737                     break;
1738                 }
1739                 hfp_ag_send_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[i]);
1740                 return 1;
1741             }
1742         }
1743     }
1744 
1745     if (hfp_connection->ag_send_no_carrier){
1746         hfp_connection->ag_send_no_carrier = false;
1747         hfp_ag_send_no_carrier(hfp_connection->rfcomm_cid);
1748         return 1;
1749     }
1750 
1751     if (hfp_connection->ag_ring){
1752         hfp_connection->ag_ring = 0;
1753         hfp_connection->command = HFP_CMD_NONE;
1754         hfp_ag_send_ring(hfp_connection->rfcomm_cid);
1755         return 1;
1756     }
1757 
1758     if (hfp_connection->ag_send_clip){
1759         hfp_connection->ag_send_clip = 0;
1760         hfp_connection->command = HFP_CMD_NONE;
1761         hfp_ag_send_clip(hfp_connection->rfcomm_cid);
1762         return 1;
1763     }
1764 
1765     if (hfp_connection->send_phone_number_for_voice_tag){
1766         hfp_connection->send_phone_number_for_voice_tag = 0;
1767         hfp_connection->command = HFP_CMD_NONE;
1768         hfp_connection->ok_pending = 1;
1769         hfp_ag_send_phone_number_for_voice_tag_cmd(hfp_connection->rfcomm_cid);
1770         return 1;
1771     }
1772 
1773     if (hfp_connection->send_subscriber_number){
1774         if (hfp_connection->next_subscriber_number_to_send < subscriber_numbers_count){
1775             hfp_phone_number_t phone = subscriber_numbers[hfp_connection->next_subscriber_number_to_send++];
1776             hfp_send_subscriber_number_cmd(hfp_connection->rfcomm_cid, phone.type, phone.number);
1777         } else {
1778             hfp_connection->send_subscriber_number = 0;
1779             hfp_connection->next_subscriber_number_to_send = 0;
1780             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1781         }
1782         hfp_connection->command = HFP_CMD_NONE;
1783         return 1;
1784     }
1785 
1786     if (hfp_connection->send_microphone_gain){
1787         hfp_connection->send_microphone_gain = 0;
1788         hfp_connection->command = HFP_CMD_NONE;
1789         hfp_ag_send_set_microphone_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->microphone_gain);
1790         return 1;
1791     }
1792 
1793     if (hfp_connection->send_speaker_gain){
1794         hfp_connection->send_speaker_gain = 0;
1795         hfp_connection->command = HFP_CMD_NONE;
1796         hfp_ag_send_set_speaker_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->speaker_gain);
1797         return 1;
1798     }
1799 
1800     if (hfp_connection->send_ag_status_indicators){
1801         hfp_connection->send_ag_status_indicators = 0;
1802         hfp_ag_send_retrieve_indicators_status_cmd(hfp_connection->rfcomm_cid);
1803         return 1;
1804     }
1805 
1806     return 0;
1807 }
1808 
1809 static void hfp_ag_run_for_context(hfp_connection_t *hfp_connection){
1810 
1811 	btstack_assert(hfp_connection != NULL);
1812 	btstack_assert(hfp_connection->local_role == HFP_ROLE_AG);
1813 
1814 	// during SDP query, RFCOMM CID is not set
1815 	if (hfp_connection->rfcomm_cid == 0) return;
1816 
1817     // assert command could be sent
1818     if (hci_can_send_command_packet_now() == 0) return;
1819 
1820     if ((hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) && hfp_connection->release_audio_connection){
1821         hfp_connection->state = HFP_W4_SCO_DISCONNECTED;
1822         hfp_connection->release_audio_connection = 0;
1823         gap_disconnect(hfp_connection->sco_handle);
1824         return;
1825     }
1826 
1827 #ifdef ENABLE_CC256X_ASSISTED_HFP
1828     // WBS Disassociate
1829     if (hfp_connection->cc256x_send_wbs_disassociate){
1830         hfp_connection->cc256x_send_wbs_disassociate = false;
1831         hci_send_cmd(&hci_ti_wbs_disassociate);
1832         return;
1833     }
1834     // Write Codec Config
1835     if (hfp_connection->cc256x_send_write_codec_config){
1836         hfp_connection->cc256x_send_write_codec_config = false;
1837         hfp_cc256x_write_codec_config(hfp_connection);
1838         return;
1839     }
1840     // WBS Associate
1841     if (hfp_connection->cc256x_send_wbs_associate){
1842         hfp_connection->cc256x_send_wbs_associate = false;
1843         hci_send_cmd(&hci_ti_wbs_associate, hfp_connection->acl_handle);
1844         return;
1845     }
1846 #endif
1847 #ifdef ENABLE_BCM_PCM_WBS
1848     // Enable WBS
1849     if (hfp_connection->bcm_send_enable_wbs){
1850         hfp_connection->bcm_send_enable_wbs = false;
1851         hci_send_cmd(&hci_bcm_enable_wbs, 1, 2);
1852         return;
1853     }
1854     // Write I2S/PCM params
1855     if (hfp_connection->bcm_send_write_i2spcm_interface_param){
1856         hfp_connection->bcm_send_write_i2spcm_interface_param = false;
1857         hfp_bcm_write_i2spcm_interface_param(hfp_connection);
1858         return;
1859     }
1860     // Disable WBS
1861     if (hfp_connection->bcm_send_disable_wbs){
1862         hfp_connection->bcm_send_disable_wbs = false;
1863         hci_send_cmd(&hci_bcm_enable_wbs, 0, 2);
1864         return;
1865     }
1866 #endif
1867 #if defined (ENABLE_CC256X_ASSISTED_HFP) || defined (ENABLE_BCM_PCM_WBS)
1868     if (hfp_connection->state == HFP_W4_WBS_SHUTDOWN){
1869         hfp_finalize_connection_context(hfp_connection);
1870         return;
1871     }
1872 #endif
1873 
1874     if (!rfcomm_can_send_packet_now(hfp_connection->rfcomm_cid)) {
1875         log_info("hfp_ag_run_for_context: request can send for 0x%02x", hfp_connection->rfcomm_cid);
1876         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1877         return;
1878     }
1879 
1880     int cmd_sent = hfp_ag_send_commands(hfp_connection);
1881 
1882     if (!cmd_sent){
1883         cmd_sent = hfp_ag_run_for_context_service_level_connection(hfp_connection);
1884     }
1885 
1886     if (!cmd_sent){
1887         cmd_sent = hfp_ag_run_for_context_service_level_connection_queries(hfp_connection);
1888     }
1889 
1890     if (!cmd_sent){
1891         cmd_sent = call_setup_state_machine(hfp_connection);
1892     }
1893 
1894     // trigger codec exchange (must be before hfp_ag_run_for_audio_connection)
1895     if (!cmd_sent && (hfp_connection->command == HFP_CMD_NONE) && hfp_connection->trigger_codec_exchange){
1896         switch (hfp_connection->codecs_state){
1897             case HFP_CODECS_IDLE:
1898             case HFP_CODECS_RECEIVED_LIST:
1899             case HFP_CODECS_AG_RESEND_COMMON_CODEC:
1900             case HFP_CODECS_ERROR:
1901                 hfp_connection->trigger_codec_exchange = 0;
1902                 hfp_connection->command = HFP_CMD_AG_SEND_COMMON_CODEC;
1903                 break;
1904             default:
1905                 break;
1906         }
1907     }
1908 
1909     if (!cmd_sent){
1910         cmd_sent = hfp_ag_run_for_audio_connection(hfp_connection);
1911     }
1912 
1913 
1914     // disconnect
1915     if (!cmd_sent && (hfp_connection->command == HFP_CMD_NONE) && (hfp_connection->state == HFP_W2_DISCONNECT_RFCOMM)){
1916         hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED;
1917         rfcomm_disconnect(hfp_connection->rfcomm_cid);
1918     }
1919 
1920     if (cmd_sent){
1921         hfp_connection->command = HFP_CMD_NONE;
1922         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1923     }
1924 }
1925 
1926 static int hfp_parser_is_end_of_line(uint8_t byte){
1927     return (byte == '\n') || (byte == '\r');
1928 }
1929 
1930 static void hfp_ag_handle_rfcomm_data(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1931     UNUSED(packet_type);    // ok: only called with RFCOMM_DATA_PACKET
1932 
1933     // assertion: size >= 1 as rfcomm.c does not deliver empty packets
1934     if (size < 1) return;
1935 
1936     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_rfcomm_cid(channel);
1937     if (!hfp_connection) return;
1938 
1939     hfp_log_rfcomm_message("HFP_AG_RX", packet, size);
1940 #ifdef ENABLE_HFP_AT_MESSAGES
1941     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_RECEIVED, (char *) packet);
1942 #endif
1943 
1944     // process messages byte-wise
1945     int pos;
1946     for (pos = 0; pos < size ; pos++){
1947         hfp_parse(hfp_connection, packet[pos], 0);
1948 
1949         // parse until end of line
1950         if (!hfp_parser_is_end_of_line(packet[pos])) continue;
1951 
1952         hfp_generic_status_indicator_t * indicator;
1953         switch(hfp_connection->command){
1954             case HFP_CMD_RESPONSE_AND_HOLD_QUERY:
1955                 if (hfp_ag_response_and_hold_active){
1956                     hfp_connection->send_response_and_hold_status = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD + 1;
1957                 }
1958                 hfp_connection->ok_pending = 1;
1959                 break;
1960             case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1961                 switch(hfp_connection->ag_response_and_hold_action){
1962                     case HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD:
1963                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, hfp_connection);
1964                         break;
1965                     case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED:
1966                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF, hfp_connection);
1967                         break;
1968                     case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED:
1969                         hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF, hfp_connection);
1970                         break;
1971                     default:
1972                         break;
1973                 }
1974                 hfp_connection->ok_pending = 1;
1975                 break;
1976             case HFP_CMD_HF_INDICATOR_STATUS:
1977                 hfp_connection->command = HFP_CMD_NONE;
1978                 if (hfp_connection->parser_indicator_index < hfp_generic_status_indicators_nr){
1979                     indicator = &hfp_generic_status_indicators[hfp_connection->parser_indicator_index];
1980                 } else {
1981                     hfp_connection->send_error = 1;
1982                     break;
1983                 }
1984                 switch (indicator->uuid){
1985                     case 1: // enhanced security
1986                         if (hfp_connection->parser_indicator_value > 1) {
1987                             hfp_connection->send_error = 1;
1988                             return;
1989                         }
1990                         log_info("HF Indicator 'enhanced security' set to %u", (unsigned int) hfp_connection->parser_indicator_value);
1991                         break;
1992                     case 2: // battery level
1993                         if (hfp_connection->parser_indicator_value > 100){
1994                             hfp_connection->send_error = 1;
1995                             return;
1996                         }
1997                         log_info("HF Indicator 'battery' set to %u", (unsigned int) hfp_connection->parser_indicator_value);
1998                         break;
1999                     default:
2000                         log_info("HF Indicator unknown set to %u", (unsigned int) hfp_connection->parser_indicator_value);
2001                         break;
2002                 }
2003                 hfp_connection->ok_pending = 1;
2004                 break;
2005             case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
2006                 // expected by SLC state machine
2007                 if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) break;
2008                 hfp_connection->send_ag_indicators_segment = 0;
2009                 hfp_connection->send_ag_status_indicators = 1;
2010                 break;
2011             case HFP_CMD_LIST_CURRENT_CALLS:
2012                 hfp_connection->command = HFP_CMD_NONE;
2013                 hfp_connection->next_call_index = 0;
2014                 hfp_connection->send_status_of_current_calls = 1;
2015                 break;
2016             case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
2017                 if (subscriber_numbers_count == 0){
2018                     hfp_ag_send_ok(hfp_connection->rfcomm_cid);
2019                     break;
2020                 }
2021                 hfp_connection->next_subscriber_number_to_send = 0;
2022                 hfp_connection->send_subscriber_number = 1;
2023                 break;
2024             case HFP_CMD_TRANSMIT_DTMF_CODES:
2025             {
2026                 hfp_connection->command = HFP_CMD_NONE;
2027                 char buffer[2];
2028                 buffer[0] = (char) hfp_connection->ag_dtmf_code;
2029                 buffer[1] = 0;
2030                 hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_TRANSMIT_DTMF_CODES, buffer);
2031                 break;
2032             }
2033             case HFP_CMD_HF_REQUEST_PHONE_NUMBER:
2034                 hfp_connection->command = HFP_CMD_NONE;
2035                 hfp_emit_simple_event(hfp_connection, HFP_SUBEVENT_ATTACH_NUMBER_TO_VOICE_TAG);
2036                 break;
2037             case HFP_CMD_TURN_OFF_EC_AND_NR:
2038                 hfp_connection->command = HFP_CMD_NONE;
2039                 if (get_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION)){
2040                     hfp_connection->ok_pending = 1;
2041                     hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION, hfp_connection->ag_echo_and_noise_reduction);
2042                     log_info("AG: EC/NR = %u", hfp_connection->ag_echo_and_noise_reduction);
2043                 } else {
2044                     hfp_connection->send_error = 1;
2045                 }
2046                 break;
2047             case HFP_CMD_CALL_ANSWERED:
2048                 hfp_connection->command = HFP_CMD_NONE;
2049                 log_info("HFP: ATA");
2050                 hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, hfp_connection);
2051                 break;
2052             case HFP_CMD_HANG_UP_CALL:
2053                 hfp_connection->command = HFP_CMD_NONE;
2054                 hfp_connection->ok_pending = 1;
2055                 hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_HF, hfp_connection);
2056                 break;
2057             case HFP_CMD_CALL_HOLD: {
2058                 hfp_connection->command = HFP_CMD_NONE;
2059                 hfp_connection->ok_pending = 1;
2060 
2061                 switch (hfp_connection->ag_call_hold_action){
2062                     case 0:
2063                         // Releases all held calls or sets User Determined User Busy (UDUB) for a waiting call.
2064                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_USER_BUSY, hfp_connection);
2065                         break;
2066                     case 1:
2067                         // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
2068                         // Where both a held and a waiting call exist, the above procedures shall apply to the
2069                         // waiting call (i.e., not to the held call) in conflicting situation.
2070                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
2071                         break;
2072                     case 2:
2073                         // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
2074                         // Where both a held and a waiting call exist, the above procedures shall apply to the
2075                         // waiting call (i.e., not to the held call) in conflicting situation.
2076                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
2077                         break;
2078                     case 3:
2079                         // Adds a held call to the conversation.
2080                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_ADD_HELD_CALL, hfp_connection);
2081                         break;
2082                     case 4:
2083                         // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer).
2084                         hfp_ag_call_sm(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, hfp_connection);
2085                         break;
2086                     default:
2087                         break;
2088                 }
2089 				hfp_connection->call_index = 0;
2090                 break;
2091             }
2092             case HFP_CMD_CALL_PHONE_NUMBER:
2093                 hfp_connection->command = HFP_CMD_NONE;
2094                 hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED_BY_HF, hfp_connection);
2095                 break;
2096             case HFP_CMD_REDIAL_LAST_NUMBER:
2097                 hfp_connection->command = HFP_CMD_NONE;
2098                 hfp_ag_call_sm(HFP_AG_OUTGOING_REDIAL_INITIATED, hfp_connection);
2099                 break;
2100             case HFP_CMD_ENABLE_CLIP:
2101                 hfp_connection->command = HFP_CMD_NONE;
2102                 log_info("hfp: clip set, now: %u", hfp_connection->clip_enabled);
2103                 hfp_connection->ok_pending = 1;
2104                 break;
2105             case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
2106                 hfp_connection->command = HFP_CMD_NONE;
2107                 log_info("hfp: call waiting notification set, now: %u", hfp_connection->call_waiting_notification_enabled);
2108                 hfp_connection->ok_pending = 1;
2109                 break;
2110             case HFP_CMD_SET_SPEAKER_GAIN:
2111                 hfp_connection->command = HFP_CMD_NONE;
2112                 hfp_connection->ok_pending = 1;
2113                 log_info("HF speaker gain = %u", hfp_connection->speaker_gain);
2114                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_SPEAKER_VOLUME, hfp_connection->speaker_gain);
2115                 break;
2116             case HFP_CMD_SET_MICROPHONE_GAIN:
2117                 hfp_connection->command = HFP_CMD_NONE;
2118                 hfp_connection->ok_pending = 1;
2119                 log_info("HF microphone gain = %u", hfp_connection->microphone_gain);
2120                 hfp_emit_event(hfp_connection, HFP_SUBEVENT_MICROPHONE_VOLUME, hfp_connection->microphone_gain);
2121                 break;
2122             default:
2123                 break;
2124         }
2125     }
2126 }
2127 
2128 static void hfp_ag_run(void){
2129     btstack_linked_list_iterator_t it;
2130     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2131     while (btstack_linked_list_iterator_has_next(&it)){
2132         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2133         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2134         hfp_ag_run_for_context(hfp_connection);
2135     }
2136 }
2137 
2138 static void hfp_ag_rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2139     switch (packet_type){
2140         case RFCOMM_DATA_PACKET:
2141             hfp_ag_handle_rfcomm_data(packet_type, channel, packet, size);
2142             break;
2143         case HCI_EVENT_PACKET:
2144             if (packet[0] == RFCOMM_EVENT_CAN_SEND_NOW){
2145                 uint16_t rfcomm_cid = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
2146                 hfp_ag_run_for_context(get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid));
2147                 return;
2148             }
2149             hfp_handle_rfcomm_event(packet_type, channel, packet, size, HFP_ROLE_AG);
2150             break;
2151         default:
2152             break;
2153     }
2154 
2155     hfp_ag_run();
2156 }
2157 
2158 static void hfp_ag_hci_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2159     hfp_handle_hci_event(packet_type, channel, packet, size, HFP_ROLE_AG);
2160     hfp_ag_run();
2161 }
2162 
2163 void hfp_ag_init_codecs(int codecs_nr, const uint8_t * codecs){
2164     if (codecs_nr > HFP_MAX_NUM_CODECS){
2165         log_error("hfp_init: codecs_nr (%d) > HFP_MAX_NUM_CODECS (%d)", codecs_nr, HFP_MAX_NUM_CODECS);
2166         return;
2167     }
2168     int i;
2169     hfp_codecs_nr = codecs_nr;
2170     for (i=0; i < codecs_nr; i++){
2171         hfp_codecs[i] = codecs[i];
2172     }
2173 }
2174 
2175 void hfp_ag_init_supported_features(uint32_t supported_features){
2176     hfp_supported_features = supported_features;
2177 }
2178 
2179 void hfp_ag_init_ag_indicators(int ag_indicators_nr, const hfp_ag_indicator_t * ag_indicators){
2180     hfp_ag_indicators_nr = ag_indicators_nr;
2181     (void)memcpy(hfp_ag_indicators, ag_indicators,
2182                  ag_indicators_nr * sizeof(hfp_ag_indicator_t));
2183 }
2184 
2185 void hfp_ag_init_hf_indicators(int hf_indicators_nr, const hfp_generic_status_indicator_t * hf_indicators){
2186     if (hf_indicators_nr > HFP_MAX_NUM_INDICATORS) return;
2187     hfp_generic_status_indicators_nr = hf_indicators_nr;
2188     (void)memcpy(hfp_generic_status_indicators, hf_indicators,
2189                  hf_indicators_nr * sizeof(hfp_generic_status_indicator_t));
2190 }
2191 
2192 void hfp_ag_init_call_hold_services(int call_hold_services_nr, const char * call_hold_services[]){
2193     hfp_ag_call_hold_services_nr = call_hold_services_nr;
2194     (void)memcpy(hfp_ag_call_hold_services, call_hold_services,
2195                  call_hold_services_nr * sizeof(char *));
2196 }
2197 
2198 
2199 void hfp_ag_init(uint16_t rfcomm_channel_nr){
2200 
2201     hfp_init();
2202     hfp_ag_call_hold_services_nr = 0;
2203     hfp_ag_response_and_hold_active = 0;
2204     hfp_ag_indicators_nr = 0;
2205     hfp_codecs_nr = 0;
2206     hfp_supported_features = HFP_DEFAULT_AG_SUPPORTED_FEATURES;
2207     subscriber_numbers = NULL;
2208     subscriber_numbers_count = 0;
2209 
2210     hfp_ag_hci_event_callback_registration.callback = &hfp_ag_hci_event_packet_handler;
2211     hci_add_event_handler(&hfp_ag_hci_event_callback_registration);
2212 
2213     rfcomm_register_service(&hfp_ag_rfcomm_packet_handler, rfcomm_channel_nr, 0xffff);
2214 
2215     // used to set packet handler for outgoing rfcomm connections - could be handled by emitting an event to us
2216     hfp_set_ag_rfcomm_packet_handler(&hfp_ag_rfcomm_packet_handler);
2217 
2218     hfp_gsm_init();
2219 }
2220 
2221 void hfp_ag_deinit(void){
2222     hfp_deinit();
2223     hfp_gsm_deinit();
2224     (void) memset(&hfp_ag_hci_event_callback_registration, 0, sizeof(btstack_packet_callback_registration_t));
2225     (void) memset(&hfp_ag_callback, 0, sizeof(btstack_packet_handler_t));
2226     (void) memset(&hfp_ag_call_hold_services, 0, sizeof(hfp_ag_call_hold_services));
2227     (void) memset(&hfp_ag_response_and_hold_state, 0, sizeof(hfp_response_and_hold_state_t));
2228 }
2229 
2230 void hfp_ag_establish_service_level_connection(bd_addr_t bd_addr){
2231     hfp_establish_service_level_connection(bd_addr, BLUETOOTH_SERVICE_CLASS_HANDSFREE, HFP_ROLE_AG);
2232 }
2233 
2234 void hfp_ag_release_service_level_connection(hci_con_handle_t acl_handle){
2235     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2236     if (!hfp_connection){
2237         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2238         return;
2239     }
2240     hfp_release_service_level_connection(hfp_connection);
2241     hfp_ag_run_for_context(hfp_connection);
2242 }
2243 
2244 void hfp_ag_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle, hfp_cme_error_t error){
2245     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2246     if (!hfp_connection){
2247         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2248         return;
2249     }
2250     hfp_connection->extended_audio_gateway_error = 0;
2251     if (!hfp_connection->enable_extended_audio_gateway_error_report){
2252         return;
2253     }
2254     hfp_connection->extended_audio_gateway_error = error;
2255     hfp_ag_run_for_context(hfp_connection);
2256 }
2257 
2258 static void hfp_ag_setup_audio_connection(hfp_connection_t * hfp_connection){
2259     log_info("hfp_ag_setup_audio_connection state %u", hfp_connection->state);
2260     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return;
2261     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
2262 
2263     hfp_connection->establish_audio_connection = 1;
2264     if (!has_codec_negotiation_feature(hfp_connection)){
2265         log_info("hfp_ag_establish_audio_connection - no codec negotiation feature, using CVSD");
2266         hfp_connection->negotiated_codec = HFP_CODEC_CVSD;
2267         hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
2268         // now, pick link settings
2269         hfp_init_link_settings(hfp_connection, hfp_ag_esco_s4_supported(hfp_connection));
2270 #ifdef ENABLE_CC256X_ASSISTED_HFP
2271         hfp_cc256x_prepare_for_sco(hfp_connection);
2272 #endif
2273         return;
2274     }
2275 
2276     uint8_t i;
2277     bool codec_was_in_use = false;
2278     bool better_codec_can_be_used = false;
2279 
2280     for (i = 0; i<hfp_connection->remote_codecs_nr; i++){
2281         if (hfp_connection->negotiated_codec == hfp_connection->remote_codecs[i]){
2282             codec_was_in_use = true;
2283         } else if (hfp_connection->negotiated_codec < hfp_connection->remote_codecs[i]){
2284             better_codec_can_be_used = true;
2285         }
2286     }
2287 
2288     if (!codec_was_in_use || better_codec_can_be_used){
2289         hfp_connection->trigger_codec_exchange = 1;
2290         hfp_connection->codecs_state = HFP_CODECS_IDLE;
2291     }
2292 }
2293 
2294 void hfp_ag_establish_audio_connection(hci_con_handle_t acl_handle){
2295     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2296     if (!hfp_connection){
2297         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2298         return;
2299     }
2300 
2301     hfp_connection->establish_audio_connection = 0;
2302     hfp_ag_setup_audio_connection(hfp_connection);
2303     hfp_ag_run_for_context(hfp_connection);
2304 }
2305 
2306 void hfp_ag_release_audio_connection(hci_con_handle_t acl_handle){
2307     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2308     if (!hfp_connection){
2309         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2310         return;
2311     }
2312     hfp_release_audio_connection(hfp_connection);
2313     hfp_ag_run_for_context(hfp_connection);
2314 }
2315 
2316 /**
2317  * @brief Enable in-band ring tone
2318  */
2319 void hfp_ag_set_use_in_band_ring_tone(int use_in_band_ring_tone){
2320     if (get_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE) == use_in_band_ring_tone){
2321         return;
2322     }
2323     hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE, use_in_band_ring_tone);
2324 
2325     btstack_linked_list_iterator_t it;
2326     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2327     while (btstack_linked_list_iterator_has_next(&it)){
2328         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2329         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2330         hfp_connection->command = HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING;
2331         hfp_ag_run_for_context(hfp_connection);
2332     }
2333 }
2334 
2335 /**
2336  * @brief Called from GSM
2337  */
2338 void hfp_ag_incoming_call(void){
2339     hfp_ag_call_sm(HFP_AG_INCOMING_CALL, NULL);
2340 }
2341 
2342 void hfp_ag_outgoing_call_initiated(const char * number) {
2343     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED_BY_AG, NULL);
2344 }
2345 
2346 /**
2347  * @brief number is stored.
2348  */
2349 void hfp_ag_set_clip(uint8_t type, const char * number){
2350     hfp_gsm_handler(HFP_AG_SET_CLIP, 0, type, number);
2351 }
2352 
2353 void hfp_ag_call_dropped(void){
2354     hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2355 }
2356 
2357 // call from AG UI
2358 void hfp_ag_answer_incoming_call(void){
2359     hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, NULL);
2360 }
2361 
2362 void hfp_ag_join_held_call(void){
2363     hfp_ag_call_sm(HFP_AG_HELD_CALL_JOINED_BY_AG, NULL);
2364 }
2365 
2366 void hfp_ag_terminate_call(void){
2367     hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_AG, NULL);
2368 }
2369 
2370 void hfp_ag_outgoing_call_ringing(void){
2371     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_RINGING, NULL);
2372 }
2373 
2374 void hfp_ag_outgoing_call_established(void){
2375     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ESTABLISHED, NULL);
2376 }
2377 
2378 void hfp_ag_outgoing_call_rejected(void){
2379     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_REJECTED, NULL);
2380 }
2381 
2382 void hfp_ag_outgoing_call_accepted(void){
2383     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ACCEPTED, NULL);
2384 }
2385 
2386 void hfp_ag_hold_incoming_call(void){
2387     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, NULL);
2388 }
2389 
2390 void hfp_ag_accept_held_incoming_call(void) {
2391     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, NULL);
2392 }
2393 
2394 void hfp_ag_reject_held_incoming_call(void){
2395     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, NULL);
2396 }
2397 
2398 static void hfp_ag_set_ag_indicator(const char * name, int value){
2399     int indicator_index = get_ag_indicator_index_for_name(name);
2400     if (indicator_index < 0) return;
2401     hfp_ag_indicators[indicator_index].status = value;
2402 
2403     btstack_linked_list_iterator_t it;
2404     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2405     while (btstack_linked_list_iterator_has_next(&it)){
2406         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2407         if (hfp_connection->local_role != HFP_ROLE_AG) continue;
2408         if (!hfp_connection->ag_indicators[indicator_index].enabled) {
2409             log_info("Requested AG indicator '%s' update to %u, but it is not enabled", hfp_ag_indicators[indicator_index].name, value);
2410             continue;
2411         }
2412         log_info("AG indicator '%s' changed to %u, request transfer status", hfp_ag_indicators[indicator_index].name, value);
2413         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
2414         hfp_ag_run_for_context(hfp_connection);
2415     }
2416 }
2417 
2418 void hfp_ag_set_registration_status(int status){
2419     if ( (status == 0) && (hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT)){
2420 
2421         // if network goes away wihle a call is active:
2422         // - the  call gets dropped
2423         // - we send NO CARRIER
2424         // NOTE: the CALL=0 has to be sent before NO CARRIER
2425 
2426         hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2427 
2428         btstack_linked_list_iterator_t it;
2429         btstack_linked_list_iterator_init(&it, hfp_get_connections());
2430         while (btstack_linked_list_iterator_has_next(&it)){
2431             hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2432             hfp_connection->ag_send_no_carrier = true;
2433         }
2434     }
2435     hfp_ag_set_ag_indicator("service", status);
2436 }
2437 
2438 void hfp_ag_set_signal_strength(int strength){
2439     hfp_ag_set_ag_indicator("signal", strength);
2440 }
2441 
2442 void hfp_ag_set_roaming_status(int status){
2443     hfp_ag_set_ag_indicator("roam", status);
2444 }
2445 
2446 void hfp_ag_set_battery_level(int level){
2447     hfp_ag_set_ag_indicator("battchg", level);
2448 }
2449 
2450 void hfp_ag_activate_voice_recognition(hci_con_handle_t acl_handle, int activate){
2451     if (!get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)) return;
2452     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2453     if (!hfp_connection){
2454         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2455         return;
2456     }
2457 
2458     if (!get_bit(hfp_connection->remote_supported_features, HFP_HFSF_VOICE_RECOGNITION_FUNCTION)) {
2459         log_info("AG cannot acivate voice recognition - not supported by HF");
2460         return;
2461     }
2462 
2463     hfp_connection->ag_activate_voice_recognition = activate;
2464     hfp_connection->command = HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
2465     hfp_ag_run_for_context(hfp_connection);
2466 }
2467 
2468 void hfp_ag_set_microphone_gain(hci_con_handle_t acl_handle, int gain){
2469     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2470     if (!hfp_connection){
2471         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2472         return;
2473     }
2474     if (hfp_connection->microphone_gain != gain){
2475         hfp_connection->command = HFP_CMD_SET_MICROPHONE_GAIN;
2476         hfp_connection->microphone_gain = gain;
2477         hfp_connection->send_microphone_gain = 1;
2478     }
2479     hfp_ag_run_for_context(hfp_connection);
2480 }
2481 
2482 void hfp_ag_set_speaker_gain(hci_con_handle_t acl_handle, int gain){
2483     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2484     if (!hfp_connection){
2485         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2486         return;
2487     }
2488     if (hfp_connection->speaker_gain != gain){
2489         hfp_connection->speaker_gain = gain;
2490         hfp_connection->send_speaker_gain = 1;
2491     }
2492     hfp_ag_run_for_context(hfp_connection);
2493 }
2494 
2495 void hfp_ag_send_phone_number_for_voice_tag(hci_con_handle_t acl_handle, const char * number){
2496     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2497     if (!hfp_connection){
2498         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2499         return;
2500     }
2501     hfp_ag_set_clip(0, number);
2502     hfp_connection->send_phone_number_for_voice_tag = 1;
2503 }
2504 
2505 void hfp_ag_reject_phone_number_for_voice_tag(hci_con_handle_t acl_handle){
2506     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2507     if (!hfp_connection){
2508         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2509         return;
2510     }
2511     hfp_connection->send_error = 1;
2512 }
2513 
2514 void hfp_ag_send_dtmf_code_done(hci_con_handle_t acl_handle){
2515     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2516     if (!hfp_connection){
2517         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2518         return;
2519     }
2520     hfp_connection->ok_pending = 1;
2521 }
2522 
2523 void hfp_ag_set_subcriber_number_information(hfp_phone_number_t * numbers, int numbers_count){
2524     subscriber_numbers = numbers;
2525     subscriber_numbers_count = numbers_count;
2526 }
2527 
2528 void hfp_ag_clear_last_dialed_number(void){
2529     hfp_gsm_clear_last_dialed_number();
2530 }
2531 
2532 void hfp_ag_set_last_dialed_number(const char * number){
2533     hfp_gsm_set_last_dialed_number(number);
2534 }
2535 
2536 void hfp_ag_notify_incoming_call_waiting(hci_con_handle_t acl_handle){
2537     hfp_connection_t * hfp_connection = get_hfp_ag_connection_context_for_acl_handle(acl_handle);
2538     if (!hfp_connection){
2539         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2540         return;
2541     }
2542     if (!hfp_connection->call_waiting_notification_enabled) return;
2543 
2544     hfp_connection->ag_notify_incoming_call_waiting = 1;
2545     hfp_ag_run_for_context(hfp_connection);
2546 }
2547 
2548 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){
2549 	if (!name){
2550 		name = default_hfp_ag_service_name;
2551 	}
2552 	hfp_create_sdp_record(service, service_record_handle, BLUETOOTH_SERVICE_CLASS_HANDSFREE_AUDIO_GATEWAY, rfcomm_channel_nr, name);
2553 
2554 	/*
2555 	 * 0x01 – Ability to reject a call
2556 	 * 0x00 – No ability to reject a call
2557 	 */
2558 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0301);    // Hands-Free Profile - Network
2559 	de_add_number(service, DE_UINT, DE_SIZE_8, ability_to_reject_call);
2560 
2561 	// Construct SupportedFeatures for SDP bitmap:
2562 	//
2563 	// "The values of the “SupportedFeatures” bitmap given in Table 5.4 shall be the same as the values
2564 	//  of the Bits 0 to 4 of the unsolicited result code +BRSF"
2565 	//
2566 	// Wide band speech (bit 5) requires Codec negotiation
2567 	//
2568 	uint16_t sdp_features = supported_features & 0x1f;
2569 	if (wide_band_speech && (supported_features & (1 << HFP_AGSF_CODEC_NEGOTIATION))){
2570 		sdp_features |= 1 << 5;
2571 	}
2572 	de_add_number(service, DE_UINT, DE_SIZE_16, 0x0311);    // Hands-Free Profile - SupportedFeatures
2573 	de_add_number(service, DE_UINT, DE_SIZE_16, sdp_features);
2574 }
2575 
2576 void hfp_ag_register_packet_handler(btstack_packet_handler_t callback){
2577 	if (callback == NULL){
2578 		log_error("hfp_ag_register_packet_handler called with NULL callback");
2579 		return;
2580 	}
2581 	hfp_ag_callback = callback;
2582 	hfp_set_ag_callback(callback);
2583 }
2584