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