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