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