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