xref: /btstack/src/classic/hfp_ag.c (revision e6c9673776c7f85e24c76da7f4b1b83031102d2b)
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     int offset = snprintf(buffer, sizeof(buffer), "\r\n%s:", HFP_INDICATOR);
415     offset += hfp_ag_indicators_status_join(buffer+offset, sizeof(buffer)-offset);
416 
417     buffer[offset] = 0;
418 
419     offset += snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n\r\nOK\r\n");
420     buffer[offset] = 0;
421     return send_str_over_rfcomm(cid, buffer);
422 }
423 
424 static int hfp_ag_send_retrieve_can_hold_call_cmd(uint16_t cid){
425     char buffer[40];
426     int offset = snprintf(buffer, sizeof(buffer), "\r\n%s:", HFP_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES);
427     offset += hfp_ag_call_services_join(buffer+offset, sizeof(buffer)-offset);
428 
429     buffer[offset] = 0;
430 
431     offset += snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n\r\nOK\r\n");
432     buffer[offset] = 0;
433     return send_str_over_rfcomm(cid, buffer);
434 }
435 
436 
437 static int hfp_ag_send_list_supported_generic_status_indicators_cmd(uint16_t cid){
438     return hfp_ag_send_ok(cid);
439 }
440 
441 static int hfp_ag_send_retrieve_supported_generic_status_indicators_cmd(uint16_t cid){
442     char buffer[40];
443     int offset = snprintf(buffer, sizeof(buffer), "\r\n%s:(", HFP_GENERIC_STATUS_INDICATOR);
444     offset += hfp_hf_indicators_join(buffer+offset, sizeof(buffer)-offset);
445 
446     buffer[offset] = 0;
447 
448     offset += snprintf(buffer+offset, sizeof(buffer)-offset, ")\r\n\r\nOK\r\n");
449     buffer[offset] = 0;
450     return send_str_over_rfcomm(cid, buffer);
451 }
452 
453 static int hfp_ag_send_retrieve_initital_supported_generic_status_indicators_cmd(uint16_t cid){
454     char buffer[40];
455     int offset = hfp_hf_indicators_initial_status_join(buffer, sizeof(buffer));
456 
457     buffer[offset] = 0;
458     offset += snprintf(buffer+offset, sizeof(buffer)-offset, "\r\nOK\r\n");
459     buffer[offset] = 0;
460     return send_str_over_rfcomm(cid, buffer);
461 }
462 
463 static int hfp_ag_send_transfer_ag_indicators_status_cmd(uint16_t cid, hfp_ag_indicator_t * indicator){
464     char buffer[20];
465     sprintf(buffer, "\r\n%s:%d,%d\r\n", HFP_TRANSFER_AG_INDICATOR_STATUS, indicator->index, indicator->status);
466     return send_str_over_rfcomm(cid, buffer);
467 }
468 
469 static int hfp_ag_send_report_network_operator_name_cmd(uint16_t cid, hfp_network_opearator_t op){
470     char buffer[40];
471     if (strlen(op.name) == 0){
472         sprintf(buffer, "\r\n%s:%d,,\r\n\r\nOK\r\n", HFP_QUERY_OPERATOR_SELECTION, op.mode);
473     } else {
474         sprintf(buffer, "\r\n%s:%d,%d,%s\r\n\r\nOK\r\n", HFP_QUERY_OPERATOR_SELECTION, op.mode, op.format, op.name);
475     }
476     return send_str_over_rfcomm(cid, buffer);
477 }
478 
479 
480 static int hfp_ag_send_suggest_codec_cmd(uint16_t cid, uint8_t codec){
481     char buffer[30];
482     sprintf(buffer, "\r\n%s:%d\r\n", HFP_CONFIRM_COMMON_CODEC, codec);
483     return send_str_over_rfcomm(cid, buffer);
484 }
485 
486 static int hfp_ag_send_activate_voice_recognition_cmd(uint16_t cid, uint8_t activate_voice_recognition){
487     char buffer[30];
488     sprintf(buffer, "\r\n%s: %d\r\n", HFP_ACTIVATE_VOICE_RECOGNITION, activate_voice_recognition);
489     return send_str_over_rfcomm(cid, buffer);
490 }
491 
492 static int hfp_ag_send_set_speaker_gain_cmd(uint16_t cid, uint8_t gain){
493     char buffer[30];
494     sprintf(buffer, "\r\n%s:%d\r\n", HFP_SET_SPEAKER_GAIN, gain);
495     return send_str_over_rfcomm(cid, buffer);
496 }
497 
498 static int hfp_ag_send_set_microphone_gain_cmd(uint16_t cid, uint8_t gain){
499     char buffer[30];
500     sprintf(buffer, "\r\n%s:%d\r\n", HFP_SET_MICROPHONE_GAIN, gain);
501     return send_str_over_rfcomm(cid, buffer);
502 }
503 
504 static int hfp_ag_send_set_response_and_hold(uint16_t cid, int state){
505     char buffer[30];
506     sprintf(buffer, "\r\n%s: %d\r\n", HFP_RESPONSE_AND_HOLD, state);
507     return send_str_over_rfcomm(cid, buffer);
508 }
509 
510 static uint8_t hfp_ag_suggest_codec(hfp_connection_t *hfp_connection){
511     if (hfp_connection->sco_for_msbc_failed) return HFP_CODEC_CVSD;
512 
513     if (hfp_supports_codec(HFP_CODEC_MSBC, hfp_codecs_nr, hfp_codecs)){
514         if (hfp_supports_codec(HFP_CODEC_MSBC, hfp_connection->remote_codecs_nr, hfp_connection->remote_codecs)){
515             return HFP_CODEC_MSBC;
516         }
517     }
518     return HFP_CODEC_CVSD;
519 }
520 
521 static void hfp_init_link_settings(hfp_connection_t * hfp_connection){
522     // determine highest possible link setting
523     hfp_connection->link_setting = HFP_LINK_SETTINGS_D1;
524     // anything else requires eSCO support on both sides
525     if (hci_extended_sco_link_supported() && hci_remote_esco_supported(hfp_connection->acl_handle)){
526         switch (hfp_connection->negotiated_codec){
527             case HFP_CODEC_CVSD:
528                 hfp_connection->link_setting = HFP_LINK_SETTINGS_S3;
529                 if ((hfp_connection->remote_supported_features & (1<<HFP_HFSF_ESCO_S4))
530                 &&  (hfp_supported_features                    & (1<<HFP_AGSF_ESCO_S4))){
531                     hfp_connection->link_setting = HFP_LINK_SETTINGS_S4;
532                 }
533                 break;
534             case HFP_CODEC_MSBC:
535                 hfp_connection->link_setting = HFP_LINK_SETTINGS_T2;
536                 break;
537             default:
538                 break;
539         }
540     }
541     log_info("hfp_init_link_settings: %u", hfp_connection->link_setting);
542 }
543 
544 static int codecs_exchange_state_machine(hfp_connection_t * hfp_connection){
545     /* events ( == commands):
546         HFP_CMD_AVAILABLE_CODECS == received AT+BAC with list of codecs
547         HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP:
548             hf_trigger_codec_connection_setup == received BCC
549             ag_trigger_codec_connection_setup == received from AG to send BCS
550         HFP_CMD_HF_CONFIRMED_CODEC == received AT+BCS
551     */
552 
553      switch (hfp_connection->codecs_state){
554         case HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE:
555             hfp_connection->command = HFP_CMD_AG_SEND_COMMON_CODEC;
556             break;
557         case HFP_CODECS_AG_RESEND_COMMON_CODEC:
558             hfp_connection->command = HFP_CMD_AG_SEND_COMMON_CODEC;
559             break;
560         default:
561             break;
562     }
563 
564     // printf(" -> State machine: CC\n");
565 
566     switch (hfp_connection->command){
567         case HFP_CMD_AVAILABLE_CODECS:
568             if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){
569                 hfp_connection->codecs_state = HFP_CODECS_RECEIVED_LIST;
570                 hfp_ag_send_ok(hfp_connection->rfcomm_cid);
571                 return 1;
572             }
573 
574             switch (hfp_connection->codecs_state){
575                 case HFP_CODECS_AG_SENT_COMMON_CODEC:
576                 case HFP_CODECS_EXCHANGED:
577                     hfp_connection->codecs_state = HFP_CODECS_AG_RESEND_COMMON_CODEC;
578                     break;
579                 default:
580                     break;
581             }
582             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
583             return 1;
584 
585         case HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP:
586             hfp_connection->codecs_state = HFP_CODECS_RECEIVED_TRIGGER_CODEC_EXCHANGE;
587             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
588             return 1;
589 
590         case HFP_CMD_AG_SEND_COMMON_CODEC:
591             hfp_connection->codecs_state = HFP_CODECS_AG_SENT_COMMON_CODEC;
592             hfp_connection->suggested_codec = hfp_ag_suggest_codec(hfp_connection);
593             hfp_ag_send_suggest_codec_cmd(hfp_connection->rfcomm_cid, hfp_connection->suggested_codec);
594             return 1;
595 
596         case HFP_CMD_HF_CONFIRMED_CODEC:
597             if (hfp_connection->codec_confirmed != hfp_connection->suggested_codec){
598                 hfp_connection->codecs_state = HFP_CODECS_ERROR;
599                 hfp_ag_send_error(hfp_connection->rfcomm_cid);
600                 return 1;
601             }
602             hfp_connection->negotiated_codec = hfp_connection->codec_confirmed;
603             hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
604             log_info("hfp: codec confirmed: %s", hfp_connection->negotiated_codec == HFP_CODEC_MSBC ? "mSBC" : "CVSD");
605             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
606             // now, pick link settings
607             hfp_init_link_settings(hfp_connection);
608             return 1;
609         default:
610             break;
611     }
612     return 0;
613 }
614 
615 static void hfp_ag_slc_established(hfp_connection_t * hfp_connection){
616     hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
617     hfp_emit_slc_connection_event(hfp_callback, 0, hfp_connection->acl_handle, hfp_connection->remote_addr);
618 
619     // if active call exist, set per-hfp_connection state active, too (when audio is on)
620     if (hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT){
621         hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE;
622     }
623     // if AG is ringing, also start ringing on the HF
624     if (hfp_gsm_call_status() == HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS &&
625         hfp_gsm_callsetup_status() == HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS){
626         hfp_ag_hf_start_ringing(hfp_connection);
627     }
628 }
629 
630 static int hfp_ag_run_for_context_service_level_connection(hfp_connection_t * hfp_connection){
631     // log_info("hfp_ag_run_for_context_service_level_connection state %u, command %u", hfp_connection->state, hfp_connection->command);
632     if (hfp_connection->state >= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) return 0;
633     int sent = 0;
634     switch(hfp_connection->command){
635         case HFP_CMD_SUPPORTED_FEATURES:
636             switch(hfp_connection->state){
637                 case HFP_W4_EXCHANGE_SUPPORTED_FEATURES:
638                 case HFP_EXCHANGE_SUPPORTED_FEATURES:
639                     hfp_hf_drop_mSBC_if_eSCO_not_supported(hfp_codecs, &hfp_codecs_nr);
640                     if (has_codec_negotiation_feature(hfp_connection)){
641                         hfp_connection->state = HFP_W4_NOTIFY_ON_CODECS;
642                     } else {
643                         hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS;
644                     }
645                     hfp_ag_exchange_supported_features_cmd(hfp_connection->rfcomm_cid);
646                     return 1;
647                 default:
648                     break;
649             }
650             break;
651         case HFP_CMD_AVAILABLE_CODECS:
652             sent = codecs_exchange_state_machine(hfp_connection);
653             if (hfp_connection->codecs_state == HFP_CODECS_RECEIVED_LIST){
654                 hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS;
655             }
656             return sent;
657 
658         case HFP_CMD_RETRIEVE_AG_INDICATORS:
659             if (hfp_connection->state == HFP_W4_RETRIEVE_INDICATORS) {
660                 // HF requested AG Indicators and we did expect it
661                 hfp_connection->state = HFP_RETRIEVE_INDICATORS;
662                 // continue below in state switch
663             }
664             break;
665 
666         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
667             if (hfp_connection->state != HFP_W4_RETRIEVE_INDICATORS_STATUS) break;
668             hfp_connection->state = HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE;
669             hfp_ag_send_retrieve_indicators_status_cmd(hfp_connection->rfcomm_cid);
670             return 1;
671 
672         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
673             if (hfp_connection->state != HFP_W4_ENABLE_INDICATORS_STATUS_UPDATE) break;
674             if (has_call_waiting_and_3way_calling_feature(hfp_connection)){
675                 hfp_connection->state = HFP_W4_RETRIEVE_CAN_HOLD_CALL;
676             } else if (has_hf_indicators_feature(hfp_connection)){
677                 hfp_connection->state = HFP_W4_LIST_GENERIC_STATUS_INDICATORS;
678             } else {
679                 hfp_ag_slc_established(hfp_connection);
680             }
681             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
682             return 1;
683 
684         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
685             if (hfp_connection->state != HFP_W4_RETRIEVE_CAN_HOLD_CALL) break;
686             if (has_hf_indicators_feature(hfp_connection)){
687                 hfp_connection->state = HFP_W4_LIST_GENERIC_STATUS_INDICATORS;
688             }
689             hfp_ag_send_retrieve_can_hold_call_cmd(hfp_connection->rfcomm_cid);
690             if (!has_hf_indicators_feature(hfp_connection)){
691                 hfp_ag_slc_established(hfp_connection);
692             }
693             return 1;
694 
695         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
696             if (hfp_connection->state != HFP_W4_LIST_GENERIC_STATUS_INDICATORS) break;
697             hfp_connection->state = HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS;
698             hfp_ag_send_list_supported_generic_status_indicators_cmd(hfp_connection->rfcomm_cid);
699             return 1;
700 
701         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
702             if (hfp_connection->state != HFP_W4_RETRIEVE_GENERIC_STATUS_INDICATORS) break;
703             hfp_connection->state = HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS;
704             hfp_ag_send_retrieve_supported_generic_status_indicators_cmd(hfp_connection->rfcomm_cid);
705             return 1;
706 
707         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
708             if (hfp_connection->state != HFP_W4_RETRIEVE_INITITAL_STATE_GENERIC_STATUS_INDICATORS) break;
709             hfp_ag_slc_established(hfp_connection);
710             hfp_ag_send_retrieve_initital_supported_generic_status_indicators_cmd(hfp_connection->rfcomm_cid);
711             return 1;
712         default:
713             break;
714     }
715 
716     switch (hfp_connection->state){
717         case HFP_RETRIEVE_INDICATORS: {
718             int next_segment = hfp_ag_send_retrieve_indicators_cmd_via_generator(hfp_connection->rfcomm_cid, hfp_connection, hfp_connection->send_ag_indicators_segment);
719             int num_segments = hfp_ag_indicators_cmd_generator_num_segments(hfp_connection);
720             log_info("HFP_CMD_RETRIEVE_AG_INDICATORS next segment %u, num_segments %u", next_segment, num_segments);
721             if (next_segment < num_segments){
722                 // prepare sending of next segment
723                 hfp_connection->send_ag_indicators_segment = next_segment;
724                 log_info("HFP_CMD_RETRIEVE_AG_INDICATORS more. command %u, next seg %u", hfp_connection->command, next_segment);
725             } else {
726                 // done, go to next state
727                 hfp_connection->send_ag_indicators_segment = 0;
728                 hfp_connection->state = HFP_W4_RETRIEVE_INDICATORS_STATUS;
729             }
730             return 1;
731         }
732         default:
733             break;
734     }
735     return 0;
736 }
737 
738 static int hfp_ag_run_for_context_service_level_connection_queries(hfp_connection_t * hfp_connection){
739     int sent = codecs_exchange_state_machine(hfp_connection);
740     if (sent) return 1;
741 
742     switch(hfp_connection->command){
743         case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION:
744             hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION, hfp_connection->ag_activate_voice_recognition);
745             hfp_ag_send_activate_voice_recognition_cmd(hfp_connection->rfcomm_cid, hfp_connection->ag_activate_voice_recognition);
746             return 1;
747         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
748             if (get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)){
749                 hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION, hfp_connection->ag_activate_voice_recognition);
750                 hfp_ag_send_ok(hfp_connection->rfcomm_cid);
751                 hfp_ag_setup_audio_connection(hfp_connection);
752             } else {
753                 hfp_ag_send_error(hfp_connection->rfcomm_cid);
754             }
755             return 1;
756         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
757             hfp_ag_send_change_in_band_ring_tone_setting_cmd(hfp_connection->rfcomm_cid);
758             return 1;
759         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
760             hfp_ag_send_report_network_operator_name_cmd(hfp_connection->rfcomm_cid, hfp_connection->network_operator);
761             return 1;
762         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
763             if (hfp_connection->network_operator.format != 0){
764                 hfp_ag_send_error(hfp_connection->rfcomm_cid);
765             } else {
766                 hfp_ag_send_ok(hfp_connection->rfcomm_cid);
767             }
768             return 1;
769         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
770             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
771             return 1;
772         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
773             if (hfp_connection->extended_audio_gateway_error){
774                 hfp_connection->extended_audio_gateway_error = 0;
775                 hfp_ag_send_report_extended_audio_gateway_error(hfp_connection->rfcomm_cid, hfp_connection->extended_audio_gateway_error_value);
776                 return 1;
777             }
778             break;
779         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
780             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
781             return 1;
782         default:
783             break;
784     }
785     return 0;
786 }
787 
788 static int hfp_ag_run_for_audio_connection(hfp_connection_t * hfp_connection){
789     if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED ||
790         hfp_connection->state > HFP_W2_DISCONNECT_SCO) return 0;
791 
792 
793     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED && hfp_connection->release_audio_connection){
794         hfp_connection->state = HFP_W4_SCO_DISCONNECTED;
795         hfp_connection->release_audio_connection = 0;
796         gap_disconnect(hfp_connection->sco_handle);
797         return 1;
798     }
799 
800     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
801 
802     // run codecs exchange
803     int sent = codecs_exchange_state_machine(hfp_connection);
804     if (sent) return 1;
805 
806     if (hfp_connection->codecs_state != HFP_CODECS_EXCHANGED) return 0;
807     if (hfp_connection->establish_audio_connection){
808         hfp_connection->state = HFP_W4_SCO_CONNECTED;
809         hfp_connection->establish_audio_connection = 0;
810         hfp_setup_synchronous_connection(hfp_connection);
811         return 1;
812     }
813     return 0;
814 }
815 
816 static hfp_connection_t * hfp_ag_context_for_timer(btstack_timer_source_t * ts){
817     btstack_linked_list_iterator_t it;
818     btstack_linked_list_iterator_init(&it, hfp_get_connections());
819 
820     while (btstack_linked_list_iterator_has_next(&it)){
821         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
822         if ( & hfp_connection->hfp_timeout == ts) {
823             return hfp_connection;
824         }
825     }
826     return NULL;
827 }
828 
829 static void hfp_timeout_handler(btstack_timer_source_t * timer){
830     hfp_connection_t * hfp_connection = hfp_ag_context_for_timer(timer);
831     if (!hfp_connection) return;
832 
833     log_info("HFP start ring timeout, con handle 0x%02x", hfp_connection->acl_handle);
834     hfp_connection->ag_ring = 1;
835     hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
836 
837     btstack_run_loop_set_timer(& hfp_connection->hfp_timeout, 2000); // 2 seconds timeout
838     btstack_run_loop_add_timer(& hfp_connection->hfp_timeout);
839 
840     hfp_run_for_context(hfp_connection);
841 }
842 
843 static void hfp_timeout_start(hfp_connection_t * hfp_connection){
844     btstack_run_loop_remove_timer(& hfp_connection->hfp_timeout);
845     btstack_run_loop_set_timer_handler(& hfp_connection->hfp_timeout, hfp_timeout_handler);
846     btstack_run_loop_set_timer(& hfp_connection->hfp_timeout, 2000); // 2 seconds timeout
847     btstack_run_loop_add_timer(& hfp_connection->hfp_timeout);
848 }
849 
850 static void hfp_timeout_stop(hfp_connection_t * hfp_connection){
851     log_info("HFP stop ring timeout, con handle 0x%02x", hfp_connection->acl_handle);
852     btstack_run_loop_remove_timer(& hfp_connection->hfp_timeout);
853 }
854 
855 //
856 // transitition implementations for hfp_ag_call_state_machine
857 //
858 
859 static void hfp_ag_hf_start_ringing(hfp_connection_t * hfp_connection){
860     if (use_in_band_tone()){
861         hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING;
862         hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
863     } else {
864         hfp_timeout_start(hfp_connection);
865         hfp_connection->ag_ring = 1;
866         hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
867         hfp_connection->call_state = HFP_CALL_RINGING;
868         hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_START_RINGINIG);
869     }
870 }
871 
872 static void hfp_ag_hf_stop_ringing(hfp_connection_t * hfp_connection){
873     hfp_connection->ag_ring = 0;
874     hfp_connection->ag_send_clip = 0;
875     hfp_timeout_stop(hfp_connection);
876     hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_STOP_RINGINIG);
877 }
878 
879 static void hfp_ag_trigger_incoming_call(void){
880     int indicator_index = get_ag_indicator_index_for_name("callsetup");
881     if (indicator_index < 0) return;
882 
883     btstack_linked_list_iterator_t it;
884     btstack_linked_list_iterator_init(&it, hfp_get_connections());
885     while (btstack_linked_list_iterator_has_next(&it)){
886         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
887         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
888         if (hfp_connection->call_state == HFP_CALL_IDLE){
889             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
890             hfp_ag_hf_start_ringing(hfp_connection);
891         }
892         if (hfp_connection->call_state == HFP_CALL_ACTIVE){
893             hfp_connection->call_state = HFP_CALL_W2_SEND_CALL_WAITING;
894         }
895         hfp_run_for_context(hfp_connection);
896     }
897 }
898 
899 static void hfp_ag_transfer_callsetup_state(void){
900     int indicator_index = get_ag_indicator_index_for_name("callsetup");
901     if (indicator_index < 0) return;
902 
903     btstack_linked_list_iterator_t it;
904     btstack_linked_list_iterator_init(&it, hfp_get_connections());
905     while (btstack_linked_list_iterator_has_next(&it)){
906         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
907         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
908         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
909         hfp_run_for_context(hfp_connection);
910     }
911 }
912 
913 static void hfp_ag_transfer_call_state(void){
914     int indicator_index = get_ag_indicator_index_for_name("call");
915     if (indicator_index < 0) return;
916 
917     btstack_linked_list_iterator_t it;
918     btstack_linked_list_iterator_init(&it, hfp_get_connections());
919     while (btstack_linked_list_iterator_has_next(&it)){
920         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
921         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
922         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
923         hfp_run_for_context(hfp_connection);
924     }
925 }
926 
927 static void hfp_ag_transfer_callheld_state(void){
928     int indicator_index = get_ag_indicator_index_for_name("callheld");
929     if (indicator_index < 0) return;
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         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
936         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
937         hfp_run_for_context(hfp_connection);
938     }
939 }
940 
941 static void hfp_ag_hf_accept_call(hfp_connection_t * source){
942 
943     int call_indicator_index = get_ag_indicator_index_for_name("call");
944     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
945 
946     btstack_linked_list_iterator_t it;
947     btstack_linked_list_iterator_init(&it, hfp_get_connections());
948     while (btstack_linked_list_iterator_has_next(&it)){
949         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
950         if (hfp_connection->call_state != HFP_CALL_RINGING &&
951             hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING) continue;
952 
953         hfp_ag_hf_stop_ringing(hfp_connection);
954         if (hfp_connection == source){
955             hfp_connection->ok_pending = 1;
956 
957             if (use_in_band_tone()){
958                 hfp_connection->call_state = HFP_CALL_ACTIVE;
959             } else {
960                 hfp_connection->call_state = HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE;
961                 hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
962             }
963 
964             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
965             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
966 
967         } else {
968             hfp_connection->call_state = HFP_CALL_IDLE;
969         }
970         hfp_run_for_context(hfp_connection);
971     }
972 }
973 
974 static void hfp_ag_ag_accept_call(void){
975 
976     int call_indicator_index = get_ag_indicator_index_for_name("call");
977     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
978 
979     btstack_linked_list_iterator_t it;
980     btstack_linked_list_iterator_init(&it, hfp_get_connections());
981     while (btstack_linked_list_iterator_has_next(&it)){
982         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
983         if (hfp_connection->call_state != HFP_CALL_RINGING) continue;
984 
985         hfp_ag_hf_stop_ringing(hfp_connection);
986         hfp_connection->call_state = HFP_CALL_TRIGGER_AUDIO_CONNECTION;
987 
988         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
989         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
990 
991         hfp_run_for_context(hfp_connection);
992         break;  // only single
993     }
994 }
995 
996 static void hfp_ag_trigger_reject_call(void){
997     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
998     btstack_linked_list_iterator_t it;
999     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1000     while (btstack_linked_list_iterator_has_next(&it)){
1001         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1002         if (connection->call_state != HFP_CALL_RINGING &&
1003             connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING) continue;
1004         hfp_ag_hf_stop_ringing(connection);
1005         connection->ag_indicators_status_update_bitmap = store_bit(connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1006         connection->call_state = HFP_CALL_IDLE;
1007         hfp_run_for_context(connection);
1008     }
1009 }
1010 
1011 static void hfp_ag_trigger_terminate_call(void){
1012     int call_indicator_index = get_ag_indicator_index_for_name("call");
1013 
1014     btstack_linked_list_iterator_t it;
1015     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1016     while (btstack_linked_list_iterator_has_next(&it)){
1017         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1018         hfp_ag_establish_service_level_connection(hfp_connection->remote_addr);
1019         if (hfp_connection->call_state == HFP_CALL_IDLE) continue;
1020         hfp_connection->call_state = HFP_CALL_IDLE;
1021         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1022         hfp_connection->release_audio_connection = 1;
1023         hfp_run_for_context(hfp_connection);
1024     }
1025     hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_CALL_TERMINATED);
1026 }
1027 
1028 static void hfp_ag_set_callsetup_indicator(void){
1029     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("callsetup");
1030     if (!indicator){
1031         log_error("hfp_ag_set_callsetup_indicator: callsetup indicator is missing");
1032         return;
1033     };
1034     indicator->status = hfp_gsm_callsetup_status();
1035 }
1036 
1037 static void hfp_ag_set_callheld_indicator(void){
1038     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("callheld");
1039     if (!indicator){
1040         log_error("hfp_ag_set_callheld_state: callheld indicator is missing");
1041         return;
1042     };
1043     indicator->status = hfp_gsm_callheld_status();
1044 }
1045 
1046 static void hfp_ag_set_call_indicator(void){
1047     hfp_ag_indicator_t * indicator = get_ag_indicator_for_name("call");
1048     if (!indicator){
1049         log_error("hfp_ag_set_call_state: call indicator is missing");
1050         return;
1051     };
1052     indicator->status = hfp_gsm_call_status();
1053 }
1054 
1055 static void hfp_ag_stop_ringing(void){
1056     btstack_linked_list_iterator_t it;
1057     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1058     while (btstack_linked_list_iterator_has_next(&it)){
1059         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1060         if (hfp_connection->call_state != HFP_CALL_RINGING &&
1061             hfp_connection->call_state != HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING) continue;
1062         hfp_ag_hf_stop_ringing(hfp_connection);
1063     }
1064 }
1065 
1066 static hfp_connection_t * hfp_ag_connection_for_call_state(hfp_call_state_t call_state){
1067     btstack_linked_list_iterator_t it;
1068     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1069     while (btstack_linked_list_iterator_has_next(&it)){
1070         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1071         if (hfp_connection->call_state == call_state) return hfp_connection;
1072     }
1073     return NULL;
1074 }
1075 
1076 static void hfp_ag_send_response_and_hold_state(hfp_response_and_hold_state_t state){
1077     btstack_linked_list_iterator_t it;
1078     btstack_linked_list_iterator_init(&it, hfp_get_connections());
1079     while (btstack_linked_list_iterator_has_next(&it)){
1080         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1081         hfp_connection->send_response_and_hold_status = state + 1;
1082     }
1083 }
1084 
1085 static int call_setup_state_machine(hfp_connection_t * hfp_connection){
1086     int indicator_index;
1087     switch (hfp_connection->call_state){
1088         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_IN_BAND_RING:
1089             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1090             // we got event: audio hfp_connection established
1091             hfp_timeout_start(hfp_connection);
1092             hfp_connection->ag_ring = 1;
1093             hfp_connection->ag_send_clip = hfp_gsm_clip_type() && hfp_connection->clip_enabled;
1094             hfp_connection->call_state = HFP_CALL_RINGING;
1095             hfp_connection->call_state = HFP_CALL_RINGING;
1096             hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_START_RINGINIG);
1097             break;
1098         case HFP_CALL_W4_AUDIO_CONNECTION_FOR_ACTIVE:
1099             if (hfp_connection->state != HFP_AUDIO_CONNECTION_ESTABLISHED) return 0;
1100             // we got event: audio hfp_connection established
1101             hfp_connection->call_state = HFP_CALL_ACTIVE;
1102             break;
1103         case HFP_CALL_W2_SEND_CALL_WAITING:
1104             hfp_connection->call_state = HFP_CALL_W4_CHLD;
1105             hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1106             indicator_index = get_ag_indicator_index_for_name("callsetup");
1107             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1108             break;
1109         default:
1110             break;
1111     }
1112     return 0;
1113 }
1114 // hfp_connection is used to identify originating HF
1115 static void hfp_ag_call_sm(hfp_ag_call_event_t event, hfp_connection_t * hfp_connection){
1116     int indicator_index;
1117     int callsetup_indicator_index = get_ag_indicator_index_for_name("callsetup");
1118     int callheld_indicator_index = get_ag_indicator_index_for_name("callheld");
1119     int call_indicator_index = get_ag_indicator_index_for_name("call");
1120 
1121     //printf("hfp_ag_call_sm event %d \n", event);
1122     switch (event){
1123         case HFP_AG_INCOMING_CALL:
1124             switch (hfp_gsm_call_status()){
1125                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1126                     switch (hfp_gsm_callsetup_status()){
1127                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1128                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL);
1129                             hfp_ag_set_callsetup_indicator();
1130                             hfp_ag_trigger_incoming_call();
1131                             log_info("AG rings");
1132                             break;
1133                         default:
1134                             break;
1135                     }
1136                     break;
1137                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1138                     switch (hfp_gsm_callsetup_status()){
1139                         case HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS:
1140                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL);
1141                             hfp_ag_set_callsetup_indicator();
1142                             hfp_ag_trigger_incoming_call();
1143                             log_info("AG call waiting");
1144                             break;
1145                         default:
1146                             break;
1147                     }
1148                     break;
1149             }
1150             break;
1151         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG:
1152             switch (hfp_gsm_call_status()){
1153                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1154                     switch (hfp_gsm_callsetup_status()){
1155                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1156                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG);
1157                             hfp_ag_set_call_indicator();
1158                             hfp_ag_set_callsetup_indicator();
1159                             hfp_ag_ag_accept_call();
1160                             log_info("AG answers call, accept call by GSM");
1161                             break;
1162                         default:
1163                             break;
1164                     }
1165                     break;
1166                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1167                     switch (hfp_gsm_callsetup_status()){
1168                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1169                             log_info("AG: current call is placed on hold, incoming call gets active");
1170                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG);
1171                             hfp_ag_set_callsetup_indicator();
1172                             hfp_ag_set_callheld_indicator();
1173                             hfp_ag_transfer_callsetup_state();
1174                             hfp_ag_transfer_callheld_state();
1175                             break;
1176                         default:
1177                             break;
1178                     }
1179                     break;
1180             }
1181             break;
1182 
1183         case HFP_AG_HELD_CALL_JOINED_BY_AG:
1184             switch (hfp_gsm_call_status()){
1185                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1186                     switch (hfp_gsm_callheld_status()){
1187                         case HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED:
1188                             log_info("AG: joining held call with active call");
1189                             hfp_gsm_handle_event(HFP_AG_HELD_CALL_JOINED_BY_AG);
1190                             hfp_ag_set_callheld_indicator();
1191                             hfp_ag_transfer_callheld_state();
1192                             hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_CONFERENCE_CALL);
1193                             break;
1194                         default:
1195                             break;
1196                     }
1197                     break;
1198                 default:
1199                     break;
1200             }
1201             break;
1202 
1203         case HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF:
1204             switch (hfp_gsm_call_status()){
1205                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1206                     switch (hfp_gsm_callsetup_status()){
1207                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1208                             hfp_gsm_handle_event(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF);
1209                             hfp_ag_set_callsetup_indicator();
1210                             hfp_ag_set_call_indicator();
1211                             hfp_ag_hf_accept_call(hfp_connection);
1212                             log_info("HF answers call, accept call by GSM");
1213                             hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_CALL_ANSWERED);
1214                             break;
1215                         default:
1216                             break;
1217                     }
1218                     break;
1219                 default:
1220                     break;
1221             }
1222             break;
1223 
1224         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG:
1225             switch (hfp_gsm_call_status()){
1226                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1227                     switch (hfp_gsm_callsetup_status()){
1228                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1229                             hfp_gsm_handle_event(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG);
1230                             hfp_ag_response_and_hold_active = 1;
1231                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1232                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1233                             // as with regualr call
1234                             hfp_ag_set_call_indicator();
1235                             hfp_ag_set_callsetup_indicator();
1236                             hfp_ag_ag_accept_call();
1237                             log_info("AG response and hold - hold by AG");
1238                             break;
1239                         default:
1240                             break;
1241                     }
1242                     break;
1243                 default:
1244                     break;
1245             }
1246             break;
1247 
1248         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF:
1249             switch (hfp_gsm_call_status()){
1250                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1251                     switch (hfp_gsm_callsetup_status()){
1252                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1253                             hfp_gsm_handle_event(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF);
1254                             hfp_ag_response_and_hold_active = 1;
1255                             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD;
1256                             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1257                             // as with regualr call
1258                             hfp_ag_set_call_indicator();
1259                             hfp_ag_set_callsetup_indicator();
1260                             hfp_ag_hf_accept_call(hfp_connection);
1261                             log_info("AG response and hold - hold by HF");
1262                             break;
1263                         default:
1264                             break;
1265                     }
1266                     break;
1267                 default:
1268                     break;
1269             }
1270             break;
1271 
1272         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG:
1273         case HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF:
1274             if (!hfp_ag_response_and_hold_active) break;
1275             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1276             hfp_gsm_handle_event(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG);
1277             hfp_ag_response_and_hold_active = 0;
1278             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED;
1279             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1280             log_info("Held Call accepted and active");
1281             break;
1282 
1283         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG:
1284         case HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF:
1285             if (!hfp_ag_response_and_hold_active) break;
1286             if (hfp_ag_response_and_hold_state != HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD) break;
1287             hfp_gsm_handle_event(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG);
1288             hfp_ag_response_and_hold_active = 0;
1289             hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1290             hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1291             // from terminate by ag
1292             hfp_ag_set_call_indicator();
1293             hfp_ag_trigger_terminate_call();
1294             break;
1295 
1296         case HFP_AG_TERMINATE_CALL_BY_HF:
1297             switch (hfp_gsm_call_status()){
1298                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1299                     switch (hfp_gsm_callsetup_status()){
1300                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1301                             hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_HF);
1302                             hfp_ag_set_callsetup_indicator();
1303                             hfp_ag_transfer_callsetup_state();
1304                             hfp_ag_trigger_reject_call();
1305                             log_info("HF Rejected Incoming call, AG terminate call");
1306                             break;
1307                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1308                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1309                             hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_HF);
1310                             hfp_ag_set_callsetup_indicator();
1311                             hfp_ag_transfer_callsetup_state();
1312                             log_info("AG terminate outgoing call process");
1313                             break;
1314                         default:
1315                             break;
1316                     }
1317                     break;
1318                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1319                     hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_HF);
1320                     hfp_ag_set_call_indicator();
1321                     hfp_ag_transfer_call_state();
1322                     hfp_connection->call_state = HFP_CALL_IDLE;
1323                     log_info("AG terminate call");
1324                     break;
1325             }
1326             break;
1327 
1328         case HFP_AG_TERMINATE_CALL_BY_AG:
1329             switch (hfp_gsm_call_status()){
1330                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1331                     switch (hfp_gsm_callsetup_status()){
1332                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1333                             hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_AG);
1334                             hfp_ag_set_callsetup_indicator();
1335                             hfp_ag_trigger_reject_call();
1336                             log_info("AG Rejected Incoming call, AG terminate call");
1337                             break;
1338                         default:
1339                             break;
1340                     }
1341                     break;
1342                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1343                     hfp_gsm_handle_event(HFP_AG_TERMINATE_CALL_BY_AG);
1344                     hfp_ag_set_callsetup_indicator();
1345                     hfp_ag_set_call_indicator();
1346                     hfp_ag_trigger_terminate_call();
1347                     log_info("AG terminate call");
1348                     break;
1349                 default:
1350                     break;
1351             }
1352             break;
1353         case HFP_AG_CALL_DROPPED:
1354             switch (hfp_gsm_call_status()){
1355                 case HFP_CALL_STATUS_NO_HELD_OR_ACTIVE_CALLS:
1356                     switch (hfp_gsm_callsetup_status()){
1357                         case HFP_CALLSETUP_STATUS_INCOMING_CALL_SETUP_IN_PROGRESS:
1358                             hfp_ag_stop_ringing();
1359                             log_info("Incoming call interrupted");
1360                             break;
1361                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_DIALING_STATE:
1362                         case HFP_CALLSETUP_STATUS_OUTGOING_CALL_SETUP_IN_ALERTING_STATE:
1363                             log_info("Outgoing call interrupted\n");
1364                             log_info("AG notify call dropped\n");
1365                             break;
1366                         default:
1367                             break;
1368                     }
1369                     hfp_gsm_handle_event(HFP_AG_CALL_DROPPED);
1370                     hfp_ag_set_callsetup_indicator();
1371                     hfp_ag_transfer_callsetup_state();
1372                     break;
1373                 case HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT:
1374                     if (hfp_ag_response_and_hold_active) {
1375                         hfp_gsm_handle_event(HFP_AG_CALL_DROPPED);
1376                         hfp_ag_response_and_hold_state = HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED;
1377                         hfp_ag_send_response_and_hold_state(hfp_ag_response_and_hold_state);
1378                     }
1379                     hfp_gsm_handle_event(HFP_AG_CALL_DROPPED);
1380                     hfp_ag_set_callsetup_indicator();
1381                     hfp_ag_set_call_indicator();
1382                     hfp_ag_trigger_terminate_call();
1383                     log_info("AG notify call dropped");
1384                     break;
1385                 default:
1386                     break;
1387             }
1388             break;
1389 
1390         case HFP_AG_OUTGOING_CALL_INITIATED:
1391             // directly reject call if number of free slots is exceeded
1392             if (!hfp_gsm_call_possible()){
1393                 hfp_connection->send_error = 1;
1394                 hfp_run_for_context(hfp_connection);
1395                 break;
1396             }
1397             hfp_gsm_handle_event_with_call_number(HFP_AG_OUTGOING_CALL_INITIATED, (const char *) &hfp_connection->line_buffer[3]);
1398 
1399             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1400 
1401             hfp_emit_string_event(hfp_callback, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, (const char *) &hfp_connection->line_buffer[3]);
1402             break;
1403 
1404         case HFP_AG_OUTGOING_REDIAL_INITIATED:{
1405             // directly reject call if number of free slots is exceeded
1406             if (!hfp_gsm_call_possible()){
1407                 hfp_connection->send_error = 1;
1408                 hfp_run_for_context(hfp_connection);
1409                 break;
1410             }
1411 
1412             hfp_gsm_handle_event(HFP_AG_OUTGOING_REDIAL_INITIATED);
1413             hfp_connection->call_state = HFP_CALL_OUTGOING_INITIATED;
1414 
1415             log_info("Redial last number");
1416             char * last_dialed_number = hfp_gsm_last_dialed_number();
1417 
1418             if (strlen(last_dialed_number) > 0){
1419                 log_info("Last number exists: accept call");
1420                 hfp_emit_string_event(hfp_callback, HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER, last_dialed_number);
1421             } else {
1422                 log_info("log_infoLast number missing: reject call");
1423                 hfp_ag_outgoing_call_rejected();
1424             }
1425             break;
1426         }
1427         case HFP_AG_OUTGOING_CALL_REJECTED:
1428             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1429             if (!hfp_connection){
1430                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1431                 break;
1432             }
1433 
1434             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_REJECTED);
1435             hfp_connection->call_state = HFP_CALL_IDLE;
1436             hfp_connection->send_error = 1;
1437             hfp_run_for_context(hfp_connection);
1438             break;
1439 
1440         case HFP_AG_OUTGOING_CALL_ACCEPTED:{
1441             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_INITIATED);
1442             if (!hfp_connection){
1443                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in initiated state");
1444                 break;
1445             }
1446 
1447             hfp_connection->ok_pending = 1;
1448             hfp_connection->call_state = HFP_CALL_OUTGOING_DIALING;
1449 
1450             // trigger callsetup to be
1451             int put_call_on_hold = hfp_gsm_call_status() == HFP_CALL_STATUS_ACTIVE_OR_HELD_CALL_IS_PRESENT;
1452             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_ACCEPTED);
1453 
1454             hfp_ag_set_callsetup_indicator();
1455             indicator_index = get_ag_indicator_index_for_name("callsetup");
1456             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
1457 
1458             // put current call on hold if active
1459             if (put_call_on_hold){
1460                 log_info("AG putting current call on hold for new outgoing calllog_info");
1461                 hfp_ag_set_callheld_indicator();
1462                 indicator_index = get_ag_indicator_index_for_name("callheld");
1463                 hfp_ag_send_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[indicator_index]);
1464             }
1465 
1466             // start audio if needed
1467             hfp_ag_establish_audio_connection(hfp_connection->acl_handle);
1468             break;
1469         }
1470         case HFP_AG_OUTGOING_CALL_RINGING:
1471             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1472             if (!hfp_connection){
1473                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection in dialing state");
1474                 break;
1475             }
1476 
1477             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_RINGING);
1478             hfp_connection->call_state = HFP_CALL_OUTGOING_RINGING;
1479             hfp_ag_set_callsetup_indicator();
1480             hfp_ag_transfer_callsetup_state();
1481             break;
1482 
1483         case HFP_AG_OUTGOING_CALL_ESTABLISHED:{
1484             // get outgoing call
1485             hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_RINGING);
1486             if (!hfp_connection){
1487                 hfp_connection = hfp_ag_connection_for_call_state(HFP_CALL_OUTGOING_DIALING);
1488             }
1489             if (!hfp_connection){
1490                 log_info("hfp_ag_call_sm: did not find outgoing hfp_connection");
1491                 break;
1492             }
1493 
1494             int CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS = hfp_gsm_callheld_status() == HFP_CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS;
1495             hfp_gsm_handle_event(HFP_AG_OUTGOING_CALL_ESTABLISHED);
1496             hfp_connection->call_state = HFP_CALL_ACTIVE;
1497             hfp_ag_set_callsetup_indicator();
1498             hfp_ag_set_call_indicator();
1499             hfp_ag_transfer_call_state();
1500             hfp_ag_transfer_callsetup_state();
1501             if (CALLHELD_STATUS_CALL_ON_HOLD_AND_NO_ACTIVE_CALLS){
1502                 hfp_ag_set_callheld_indicator();
1503                 hfp_ag_transfer_callheld_state();
1504             }
1505             break;
1506         }
1507 
1508         case HFP_AG_CALL_HOLD_USER_BUSY:
1509             hfp_gsm_handle_event(HFP_AG_CALL_HOLD_USER_BUSY);
1510             hfp_ag_set_callsetup_indicator();
1511             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1512             hfp_connection->call_state = HFP_CALL_ACTIVE;
1513             log_info("AG: Call Waiting, User Busy");
1514             break;
1515 
1516         case HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1517             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1518             int call_held = hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD;
1519 
1520             // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1521             if (call_held || call_setup_in_progress){
1522                 hfp_gsm_handle_event_with_call_index(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index);
1523 
1524             }
1525 
1526             if (call_setup_in_progress){
1527                 log_info("AG: Call Dropped, Accept new call");
1528                 hfp_ag_set_callsetup_indicator();
1529                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1530             } else {
1531                 log_info("AG: Call Dropped, Resume held call");
1532             }
1533             if (call_held){
1534                 hfp_ag_set_callheld_indicator();
1535                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1536             }
1537 
1538             hfp_connection->call_state = HFP_CALL_ACTIVE;
1539             break;
1540         }
1541 
1542         case HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL:{
1543             // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1544             // only update if callsetup changed
1545             int call_setup_in_progress = hfp_gsm_callsetup_status() != HFP_CALLSETUP_STATUS_NO_CALL_SETUP_IN_PROGRESS;
1546             hfp_gsm_handle_event_with_call_index(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection->call_index);
1547 
1548             if (call_setup_in_progress){
1549                 log_info("AG: Call on Hold, Accept new call");
1550                 hfp_ag_set_callsetup_indicator();
1551                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callsetup_indicator_index, 1);
1552             } else {
1553                 log_info("AG: Swap calls");
1554             }
1555 
1556             hfp_ag_set_callheld_indicator();
1557             // hfp_ag_set_callheld_state(HFP_CALLHELD_STATUS_CALL_ON_HOLD_OR_SWAPPED);
1558             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1559             hfp_connection->call_state = HFP_CALL_ACTIVE;
1560             break;
1561         }
1562 
1563         case HFP_AG_CALL_HOLD_ADD_HELD_CALL:
1564             // Adds a held call to the conversation.
1565             if (hfp_gsm_callheld_status() != HFP_CALLHELD_STATUS_NO_CALLS_HELD){
1566                 log_info("AG: Join 3-way-call");
1567                 hfp_gsm_handle_event(HFP_AG_CALL_HOLD_ADD_HELD_CALL);
1568                 hfp_ag_set_callheld_indicator();
1569                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1570                 hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_CONFERENCE_CALL);
1571             }
1572             hfp_connection->call_state = HFP_CALL_ACTIVE;
1573             break;
1574         case HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS:
1575             // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer)
1576             hfp_gsm_handle_event(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS);
1577             log_info("AG: Transfer call -> Connect two calls and disconnect");
1578             hfp_ag_set_call_indicator();
1579             hfp_ag_set_callheld_indicator();
1580             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, call_indicator_index, 1);
1581             hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, callheld_indicator_index, 1);
1582             hfp_connection->call_state = HFP_CALL_IDLE;
1583             break;
1584 
1585         default:
1586             break;
1587     }
1588 
1589 
1590 }
1591 
1592 
1593 static void hfp_ag_send_call_status(hfp_connection_t * hfp_connection, int call_index){
1594     hfp_gsm_call_t * active_call = hfp_gsm_call(call_index);
1595     if (!active_call) return;
1596 
1597     int idx = active_call->index;
1598     hfp_enhanced_call_dir_t dir = active_call->direction;
1599     hfp_enhanced_call_status_t status = active_call->enhanced_status;
1600     hfp_enhanced_call_mode_t mode = active_call->mode;
1601     hfp_enhanced_call_mpty_t mpty = active_call->mpty;
1602     uint8_t type = active_call->clip_type;
1603     char * number = active_call->clip_number;
1604 
1605     char buffer[100];
1606     // TODO: check length of a buffer, to fit the MTU
1607     int offset = snprintf(buffer, sizeof(buffer), "\r\n%s: %d,%d,%d,%d,%d", HFP_LIST_CURRENT_CALLS, idx, dir, status, mode, mpty);
1608     if (number){
1609         offset += snprintf(buffer+offset, sizeof(buffer)-offset, ", \"%s\",%u", number, type);
1610     }
1611     snprintf(buffer+offset, sizeof(buffer)-offset, "\r\n");
1612     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,
1613        mode, mpty, type, number);
1614     send_str_over_rfcomm(hfp_connection->rfcomm_cid, buffer);
1615 }
1616 
1617 static void hfp_run_for_context(hfp_connection_t *hfp_connection){
1618 
1619     // log_info("hfp_run_for_context %p", hfp_connection);
1620 
1621     if (!hfp_connection) return;
1622 
1623     if (!hfp_connection->rfcomm_cid) return;
1624 
1625     if (!rfcomm_can_send_packet_now(hfp_connection->rfcomm_cid)) {
1626         log_info("hfp_run_for_context: request can send for 0x%02x", hfp_connection->rfcomm_cid);
1627         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1628         return;
1629     }
1630     if (hfp_connection->send_status_of_current_calls){
1631         hfp_connection->ok_pending = 0;
1632         if (hfp_connection->next_call_index < hfp_gsm_get_number_of_calls()){
1633             hfp_connection->next_call_index++;
1634             hfp_ag_send_call_status(hfp_connection, hfp_connection->next_call_index);
1635         } else {
1636             hfp_connection->next_call_index = 0;
1637             hfp_connection->ok_pending = 1;
1638             hfp_connection->send_status_of_current_calls = 0;
1639         }
1640         return;
1641     }
1642 
1643     if (hfp_connection->ag_notify_incoming_call_waiting){
1644         hfp_connection->ag_notify_incoming_call_waiting = 0;
1645         hfp_ag_send_call_waiting_notification(hfp_connection->rfcomm_cid);
1646         return;
1647     }
1648 
1649     if (hfp_connection->command == HFP_CMD_UNKNOWN){
1650         hfp_connection->ok_pending = 0;
1651         hfp_connection->send_error = 0;
1652         hfp_connection->command = HFP_CMD_NONE;
1653         hfp_ag_send_error(hfp_connection->rfcomm_cid);
1654         return;
1655     }
1656 
1657     if (hfp_connection->send_error){
1658         hfp_connection->send_error = 0;
1659         hfp_connection->command = HFP_CMD_NONE;
1660         hfp_ag_send_error(hfp_connection->rfcomm_cid);
1661         return;
1662     }
1663 
1664     // note: before update AG indicators and ok_pending
1665     if (hfp_connection->send_response_and_hold_status){
1666         int status = hfp_connection->send_response_and_hold_status - 1;
1667         hfp_connection->send_response_and_hold_status = 0;
1668         hfp_ag_send_set_response_and_hold(hfp_connection->rfcomm_cid, status);
1669         return;
1670     }
1671 
1672     if (hfp_connection->ok_pending){
1673         hfp_connection->ok_pending = 0;
1674         hfp_connection->command = HFP_CMD_NONE;
1675         hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1676         return;
1677     }
1678 
1679     // update AG indicators
1680     if (hfp_connection->ag_indicators_status_update_bitmap){
1681         int i;
1682         for (i=0;i<hfp_connection->ag_indicators_nr;i++){
1683             if (get_bit(hfp_connection->ag_indicators_status_update_bitmap, i)){
1684                 hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, i, 0);
1685                 if (!hfp_connection->enable_status_update_for_ag_indicators) {
1686                     log_info("+CMER:3,0,0,0 - not sending update for '%s'", hfp_ag_indicators[i].name);
1687                     break;
1688                 }
1689                 hfp_ag_send_transfer_ag_indicators_status_cmd(hfp_connection->rfcomm_cid, &hfp_ag_indicators[i]);
1690                 return;
1691             }
1692         }
1693     }
1694 
1695     if (hfp_connection->ag_ring){
1696         hfp_connection->ag_ring = 0;
1697         hfp_connection->command = HFP_CMD_NONE;
1698         hfp_ag_send_ring(hfp_connection->rfcomm_cid);
1699         return;
1700     }
1701 
1702     if (hfp_connection->ag_send_clip){
1703         hfp_connection->ag_send_clip = 0;
1704         hfp_connection->command = HFP_CMD_NONE;
1705         hfp_ag_send_clip(hfp_connection->rfcomm_cid);
1706         return;
1707     }
1708 
1709     if (hfp_connection->send_phone_number_for_voice_tag){
1710         hfp_connection->send_phone_number_for_voice_tag = 0;
1711         hfp_connection->command = HFP_CMD_NONE;
1712         hfp_connection->ok_pending = 1;
1713         hfp_ag_send_phone_number_for_voice_tag_cmd(hfp_connection->rfcomm_cid);
1714         return;
1715     }
1716 
1717     if (hfp_connection->send_subscriber_number){
1718         if (hfp_connection->next_subscriber_number_to_send < subscriber_numbers_count){
1719             hfp_phone_number_t phone = subscriber_numbers[hfp_connection->next_subscriber_number_to_send++];
1720             hfp_send_subscriber_number_cmd(hfp_connection->rfcomm_cid, phone.type, phone.number);
1721         } else {
1722             hfp_connection->send_subscriber_number = 0;
1723             hfp_connection->next_subscriber_number_to_send = 0;
1724             hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1725         }
1726         hfp_connection->command = HFP_CMD_NONE;
1727 
1728     }
1729 
1730     if (hfp_connection->send_microphone_gain){
1731         hfp_connection->send_microphone_gain = 0;
1732         hfp_connection->command = HFP_CMD_NONE;
1733         hfp_ag_send_set_microphone_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->microphone_gain);
1734         return;
1735     }
1736 
1737     if (hfp_connection->send_speaker_gain){
1738         hfp_connection->send_speaker_gain = 0;
1739         hfp_connection->command = HFP_CMD_NONE;
1740         hfp_ag_send_set_speaker_gain_cmd(hfp_connection->rfcomm_cid, hfp_connection->speaker_gain);
1741         return;
1742     }
1743 
1744     if (hfp_connection->send_ag_status_indicators){
1745         hfp_connection->send_ag_status_indicators = 0;
1746         hfp_ag_send_retrieve_indicators_status_cmd(hfp_connection->rfcomm_cid);
1747         return;
1748     }
1749 
1750     // trigger codec exchange if requested by app
1751     if (hfp_connection->trigger_codec_exchange){
1752         log_info("trigger codec, command %u, codec state %u", hfp_connection->command, hfp_connection->codecs_state);
1753     }
1754     if (hfp_connection->trigger_codec_exchange && hfp_connection->command == HFP_CMD_NONE){
1755         switch (hfp_connection->codecs_state){
1756             case HFP_CODECS_IDLE:
1757             case HFP_CODECS_RECEIVED_LIST:
1758             case HFP_CODECS_AG_RESEND_COMMON_CODEC:
1759             case HFP_CODECS_ERROR:
1760                 hfp_connection->trigger_codec_exchange = 0;
1761                 hfp_connection->command = HFP_CMD_AG_SEND_COMMON_CODEC;
1762                 break;
1763             default:
1764                 break;
1765         }
1766     }
1767 
1768     int cmd_sent = hfp_ag_run_for_context_service_level_connection(hfp_connection);
1769     if (!cmd_sent){
1770         cmd_sent = hfp_ag_run_for_context_service_level_connection_queries(hfp_connection);
1771     }
1772 
1773     if (!cmd_sent){
1774         cmd_sent = call_setup_state_machine(hfp_connection);
1775     }
1776 
1777     if (!cmd_sent){
1778         cmd_sent = hfp_ag_run_for_audio_connection(hfp_connection);
1779     }
1780 
1781     if (hfp_connection->command == HFP_CMD_NONE && !cmd_sent){
1782         // log_info("hfp_connection->command == HFP_CMD_NONE");
1783         switch(hfp_connection->state){
1784             case HFP_W2_DISCONNECT_RFCOMM:
1785                 hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED;
1786                 rfcomm_disconnect(hfp_connection->rfcomm_cid);
1787                 break;
1788             default:
1789                 break;
1790         }
1791     }
1792 
1793     if (cmd_sent){
1794         hfp_connection->command = HFP_CMD_NONE;
1795         rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
1796     }
1797 }
1798 
1799 static hfp_generic_status_indicator_t *get_hf_indicator_by_number(int number){
1800     int i;
1801     for (i=0;i< hfp_generic_status_indicators_nr;i++){
1802         hfp_generic_status_indicator_t * indicator = &hfp_generic_status_indicators[i];
1803         if (indicator->uuid == number){
1804             return indicator;
1805         }
1806     }
1807     return NULL;
1808 }
1809 
1810 static void hfp_handle_rfcomm_data(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1811     UNUSED(packet_type);    // ok: only called with RFCOMM_DATA_PACKET
1812 
1813     // assertion: size >= 1 as rfcomm.c does not deliver empty packets
1814     if (size < 1) return;
1815 
1816     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_rfcomm_cid(channel);
1817     if (!hfp_connection) return;
1818 
1819     // temp overwrite last byte (most likely \n for log_info)
1820     char last_char = packet[size-1];
1821     packet[size-1] = 0;
1822     log_info("HFP_RX %s", packet);
1823     packet[size-1] = last_char;
1824 
1825     // process messages byte-wise
1826     int pos;
1827     for (pos = 0; pos < size ; pos++){
1828         hfp_parse(hfp_connection, packet[pos], 0);
1829     }
1830     hfp_generic_status_indicator_t * indicator;
1831     int value;
1832     switch(hfp_connection->command){
1833         case HFP_CMD_RESPONSE_AND_HOLD_QUERY:
1834             if (hfp_ag_response_and_hold_active){
1835                 hfp_connection->send_response_and_hold_status = HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD + 1;
1836             }
1837             hfp_connection->ok_pending = 1;
1838             break;
1839         case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1840             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1841             log_info("HF Response and Hold: %u", value);
1842             switch(value){
1843                 case HFP_RESPONSE_AND_HOLD_INCOMING_ON_HOLD:
1844                     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_HF, hfp_connection);
1845                     break;
1846                 case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_ACCEPTED:
1847                     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_HF, hfp_connection);
1848                     break;
1849                 case HFP_RESPONSE_AND_HOLD_HELD_INCOMING_REJECTED:
1850                     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_HF, hfp_connection);
1851                     break;
1852                 default:
1853                     break;
1854             }
1855             hfp_connection->ok_pending = 1;
1856             break;
1857         case HFP_CMD_HF_INDICATOR_STATUS:
1858             hfp_connection->command = HFP_CMD_NONE;
1859             // find indicator by assigned number
1860             indicator = get_hf_indicator_by_number(hfp_connection->parser_indicator_index);
1861             if (!indicator){
1862                 hfp_connection->send_error = 1;
1863                 break;
1864             }
1865             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1866             switch (indicator->uuid){
1867                 case 1: // enhanced security
1868                     if (value > 1) {
1869                         hfp_connection->send_error = 1;
1870                         return;
1871                     }
1872                     log_info("HF Indicator 'enhanced security' set to %u", value);
1873                     break;
1874                 case 2: // battery level
1875                     if (value > 100){
1876                         hfp_connection->send_error = 1;
1877                         return;
1878                     }
1879                     log_info("HF Indicator 'battery' set to %u", value);
1880                     break;
1881                 default:
1882                     log_info("HF Indicator unknown set to %u", value);
1883                     break;
1884             }
1885             hfp_connection->ok_pending = 1;
1886             break;
1887         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1888             // expected by SLC state machine
1889             if (hfp_connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED) break;
1890             hfp_connection->send_ag_indicators_segment = 0;
1891             hfp_connection->send_ag_status_indicators = 1;
1892             break;
1893         case HFP_CMD_LIST_CURRENT_CALLS:
1894             hfp_connection->command = HFP_CMD_NONE;
1895             hfp_connection->next_call_index = 0;
1896             hfp_connection->send_status_of_current_calls = 1;
1897             break;
1898         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1899             if (subscriber_numbers_count == 0){
1900                 hfp_ag_send_ok(hfp_connection->rfcomm_cid);
1901                 break;
1902             }
1903             hfp_connection->next_subscriber_number_to_send = 0;
1904             hfp_connection->send_subscriber_number = 1;
1905             break;
1906         case HFP_CMD_TRANSMIT_DTMF_CODES:
1907             hfp_connection->command = HFP_CMD_NONE;
1908             hfp_emit_string_event(hfp_callback, HFP_SUBEVENT_TRANSMIT_DTMF_CODES, (const char *) &hfp_connection->line_buffer[0]);
1909             break;
1910         case HFP_CMD_HF_REQUEST_PHONE_NUMBER:
1911             hfp_connection->command = HFP_CMD_NONE;
1912             hfp_emit_simple_event(hfp_callback, HFP_SUBEVENT_ATTACH_NUMBER_TO_VOICE_TAG);
1913             break;
1914         case HFP_CMD_TURN_OFF_EC_AND_NR:
1915             hfp_connection->command = HFP_CMD_NONE;
1916             if (get_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION)){
1917                 hfp_connection->ok_pending = 1;
1918                 hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_EC_NR_FUNCTION, hfp_connection->ag_echo_and_noise_reduction);
1919                 log_info("AG: EC/NR = %u", hfp_connection->ag_echo_and_noise_reduction);
1920             } else {
1921                 hfp_connection->send_error = 1;
1922             }
1923             break;
1924         case HFP_CMD_CALL_ANSWERED:
1925             hfp_connection->command = HFP_CMD_NONE;
1926             log_info("HFP: ATA");
1927             hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_HF, hfp_connection);
1928             break;
1929         case HFP_CMD_HANG_UP_CALL:
1930             hfp_connection->command = HFP_CMD_NONE;
1931             hfp_connection->ok_pending = 1;
1932             hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_HF, hfp_connection);
1933             break;
1934         case HFP_CMD_CALL_HOLD: {
1935             // TODO: fully implement this
1936             log_error("HFP: unhandled call hold type %c", hfp_connection->line_buffer[0]);
1937             hfp_connection->command = HFP_CMD_NONE;
1938             hfp_connection->ok_pending = 1;
1939             hfp_connection->call_index = 0;
1940 
1941             if (hfp_connection->line_buffer[1] != '\0'){
1942                 hfp_connection->call_index = btstack_atoi((char *)&hfp_connection->line_buffer[1]);
1943             }
1944 
1945             switch (hfp_connection->line_buffer[0]){
1946                 case '0':
1947                     // Releases all held calls or sets User Determined User Busy (UDUB) for a waiting call.
1948                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_USER_BUSY, hfp_connection);
1949                     break;
1950                 case '1':
1951                     // Releases all active calls (if any exist) and accepts the other (held or waiting) call.
1952                     // Where both a held and a waiting call exist, the above procedures shall apply to the
1953                     // waiting call (i.e., not to the held call) in conflicting situation.
1954                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_RELEASE_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
1955                     break;
1956                 case '2':
1957                     // Places all active calls (if any exist) on hold and accepts the other (held or waiting) call.
1958                     // Where both a held and a waiting call exist, the above procedures shall apply to the
1959                     // waiting call (i.e., not to the held call) in conflicting situation.
1960                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_PARK_ACTIVE_ACCEPT_HELD_OR_WAITING_CALL, hfp_connection);
1961                     break;
1962                 case '3':
1963                     // Adds a held call to the conversation.
1964                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_ADD_HELD_CALL, hfp_connection);
1965                     break;
1966                 case '4':
1967                     // Connects the two calls and disconnects the subscriber from both calls (Explicit Call Transfer).
1968                     hfp_ag_call_sm(HFP_AG_CALL_HOLD_EXIT_AND_JOIN_CALLS, hfp_connection);
1969                     break;
1970                 default:
1971                     break;
1972             }
1973             break;
1974         }
1975         case HFP_CMD_CALL_PHONE_NUMBER:
1976             hfp_connection->command = HFP_CMD_NONE;
1977             hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_INITIATED, hfp_connection);
1978             break;
1979         case HFP_CMD_REDIAL_LAST_NUMBER:
1980             hfp_connection->command = HFP_CMD_NONE;
1981             hfp_ag_call_sm(HFP_AG_OUTGOING_REDIAL_INITIATED, hfp_connection);
1982             break;
1983         case HFP_CMD_ENABLE_CLIP:
1984             hfp_connection->command = HFP_CMD_NONE;
1985             hfp_connection->clip_enabled = hfp_connection->line_buffer[8] != '0';
1986             log_info("hfp: clip set, now: %u", hfp_connection->clip_enabled);
1987             hfp_connection->ok_pending = 1;
1988             break;
1989         case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1990             hfp_connection->command = HFP_CMD_NONE;
1991             hfp_connection->call_waiting_notification_enabled = hfp_connection->line_buffer[8] != '0';
1992             log_info("hfp: call waiting notification set, now: %u", hfp_connection->call_waiting_notification_enabled);
1993             hfp_connection->ok_pending = 1;
1994             break;
1995         case HFP_CMD_SET_SPEAKER_GAIN:
1996             hfp_connection->command = HFP_CMD_NONE;
1997             hfp_connection->ok_pending = 1;
1998             log_info("HF speaker gain = %u", hfp_connection->speaker_gain);
1999             break;
2000         case HFP_CMD_SET_MICROPHONE_GAIN:
2001             hfp_connection->command = HFP_CMD_NONE;
2002             hfp_connection->ok_pending = 1;
2003             log_info("HF microphone gain = %u", hfp_connection->microphone_gain);
2004             break;
2005         default:
2006             break;
2007     }
2008 }
2009 
2010 static void hfp_run(void){
2011     btstack_linked_list_iterator_t it;
2012     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2013     while (btstack_linked_list_iterator_has_next(&it)){
2014         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2015         hfp_run_for_context(hfp_connection);
2016     }
2017 }
2018 
2019 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2020     switch (packet_type){
2021         case RFCOMM_DATA_PACKET:
2022             hfp_handle_rfcomm_data(packet_type, channel, packet, size);
2023             break;
2024         case HCI_EVENT_PACKET:
2025             if (packet[0] == RFCOMM_EVENT_CAN_SEND_NOW){
2026                 uint16_t rfcomm_cid = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
2027                 hfp_run_for_context(get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid));
2028                 return;
2029             }
2030             hfp_handle_hci_event(packet_type, channel, packet, size);
2031             break;
2032         default:
2033             break;
2034     }
2035 
2036     hfp_run();
2037 }
2038 
2039 
2040 void hfp_ag_init_codecs(int codecs_nr, uint8_t * codecs){
2041     if (codecs_nr > HFP_MAX_NUM_CODECS){
2042         log_error("hfp_init: codecs_nr (%d) > HFP_MAX_NUM_CODECS (%d)", codecs_nr, HFP_MAX_NUM_CODECS);
2043         return;
2044     }
2045     int i;
2046     hfp_codecs_nr = codecs_nr;
2047     for (i=0; i < codecs_nr; i++){
2048         hfp_codecs[i] = codecs[i];
2049     }
2050 }
2051 
2052 void hfp_ag_init_supported_features(uint32_t supported_features){
2053     hfp_supported_features = supported_features;
2054 }
2055 
2056 void hfp_ag_init_ag_indicators(int ag_indicators_nr, hfp_ag_indicator_t * ag_indicators){
2057     hfp_ag_indicators_nr = ag_indicators_nr;
2058     memcpy(hfp_ag_indicators, ag_indicators, ag_indicators_nr * sizeof(hfp_ag_indicator_t));
2059 }
2060 
2061 void hfp_ag_init_hf_indicators(int hf_indicators_nr, hfp_generic_status_indicator_t * hf_indicators){
2062     if (hf_indicators_nr > HFP_MAX_NUM_HF_INDICATORS) return;
2063     hfp_generic_status_indicators_nr = hf_indicators_nr;
2064     memcpy(hfp_generic_status_indicators, hf_indicators, hf_indicators_nr * sizeof(hfp_generic_status_indicator_t));
2065 }
2066 
2067 void hfp_ag_init_call_hold_services(int call_hold_services_nr, const char * call_hold_services[]){
2068     hfp_ag_call_hold_services_nr = call_hold_services_nr;
2069     memcpy(hfp_ag_call_hold_services, call_hold_services, call_hold_services_nr * sizeof(char *));
2070 }
2071 
2072 
2073 void hfp_ag_init(uint16_t rfcomm_channel_nr){
2074     // register for HCI events
2075     hci_event_callback_registration.callback = &packet_handler;
2076     hci_add_event_handler(&hci_event_callback_registration);
2077 
2078     rfcomm_register_service(&packet_handler, rfcomm_channel_nr, 0xffff);
2079 
2080     hfp_ag_response_and_hold_active = 0;
2081     subscriber_numbers = NULL;
2082     subscriber_numbers_count = 0;
2083 
2084     hfp_set_packet_handler_for_rfcomm_connections(&packet_handler);
2085 
2086     hfp_gsm_init();
2087 }
2088 
2089 void hfp_ag_establish_service_level_connection(bd_addr_t bd_addr){
2090     hfp_establish_service_level_connection(bd_addr, BLUETOOTH_SERVICE_CLASS_HANDSFREE);
2091 }
2092 
2093 void hfp_ag_release_service_level_connection(hci_con_handle_t acl_handle){
2094     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2095     if (!hfp_connection){
2096         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2097         return;
2098     }
2099     hfp_release_service_level_connection(hfp_connection);
2100     hfp_run_for_context(hfp_connection);
2101 }
2102 
2103 void hfp_ag_report_extended_audio_gateway_error_result_code(hci_con_handle_t acl_handle, hfp_cme_error_t error){
2104     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2105     if (!hfp_connection){
2106         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2107         return;
2108     }
2109     hfp_connection->extended_audio_gateway_error = 0;
2110     if (!hfp_connection->enable_extended_audio_gateway_error_report){
2111         return;
2112     }
2113     hfp_connection->extended_audio_gateway_error = error;
2114     hfp_run_for_context(hfp_connection);
2115 }
2116 
2117 static void hfp_ag_setup_audio_connection(hfp_connection_t * hfp_connection){
2118     log_info("hfp_ag_setup_audio_connection state %u", hfp_connection->state);
2119     if (hfp_connection->state == HFP_AUDIO_CONNECTION_ESTABLISHED) return;
2120     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
2121 
2122     hfp_connection->establish_audio_connection = 1;
2123     if (!has_codec_negotiation_feature(hfp_connection)){
2124         log_info("hfp_ag_establish_audio_connection - no codec negotiation feature, using CVSD");
2125         hfp_connection->negotiated_codec = HFP_CODEC_CVSD;
2126         hfp_connection->codecs_state = HFP_CODECS_EXCHANGED;
2127         // now, pick link settings
2128         hfp_init_link_settings(hfp_connection);
2129         return;
2130     }
2131 
2132     hfp_connection->trigger_codec_exchange = 1;
2133 }
2134 
2135 void hfp_ag_establish_audio_connection(hci_con_handle_t acl_handle){
2136     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2137     if (!hfp_connection){
2138         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2139         return;
2140     }
2141     hfp_connection->trigger_codec_exchange = 0;
2142     hfp_connection->establish_audio_connection = 0;
2143     hfp_ag_setup_audio_connection(hfp_connection);
2144     hfp_run_for_context(hfp_connection);
2145 }
2146 
2147 void hfp_ag_release_audio_connection(hci_con_handle_t acl_handle){
2148     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2149     if (!hfp_connection){
2150         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2151         return;
2152     }
2153     hfp_release_audio_connection(hfp_connection);
2154     hfp_run_for_context(hfp_connection);
2155 }
2156 
2157 /**
2158  * @brief Enable in-band ring tone
2159  */
2160 void hfp_ag_set_use_in_band_ring_tone(int use_in_band_ring_tone){
2161     if (get_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE) == use_in_band_ring_tone){
2162         return;
2163     }
2164     hfp_supported_features = store_bit(hfp_supported_features, HFP_AGSF_IN_BAND_RING_TONE, use_in_band_ring_tone);
2165 
2166     btstack_linked_list_iterator_t it;
2167     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2168     while (btstack_linked_list_iterator_has_next(&it)){
2169         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2170         hfp_connection->command = HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING;
2171         hfp_run_for_context(hfp_connection);
2172     }
2173 }
2174 
2175 /**
2176  * @brief Called from GSM
2177  */
2178 void hfp_ag_incoming_call(void){
2179     hfp_ag_call_sm(HFP_AG_INCOMING_CALL, NULL);
2180 }
2181 
2182 /**
2183  * @brief number is stored.
2184  */
2185 void hfp_ag_set_clip(uint8_t type, const char * number){
2186     hfp_gsm_handle_event_with_clip(HFP_AG_SET_CLIP, type, number);
2187 }
2188 
2189 void hfp_ag_call_dropped(void){
2190     hfp_ag_call_sm(HFP_AG_CALL_DROPPED, NULL);
2191 }
2192 
2193 // call from AG UI
2194 void hfp_ag_answer_incoming_call(void){
2195     hfp_ag_call_sm(HFP_AG_INCOMING_CALL_ACCEPTED_BY_AG, NULL);
2196 }
2197 
2198 void hfp_ag_join_held_call(void){
2199     hfp_ag_call_sm(HFP_AG_HELD_CALL_JOINED_BY_AG, NULL);
2200 }
2201 
2202 void hfp_ag_terminate_call(void){
2203     hfp_ag_call_sm(HFP_AG_TERMINATE_CALL_BY_AG, NULL);
2204 }
2205 
2206 void hfp_ag_outgoing_call_ringing(void){
2207     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_RINGING, NULL);
2208 }
2209 
2210 void hfp_ag_outgoing_call_established(void){
2211     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ESTABLISHED, NULL);
2212 }
2213 
2214 void hfp_ag_outgoing_call_rejected(void){
2215     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_REJECTED, NULL);
2216 }
2217 
2218 void hfp_ag_outgoing_call_accepted(void){
2219     hfp_ag_call_sm(HFP_AG_OUTGOING_CALL_ACCEPTED, NULL);
2220 }
2221 
2222 void hfp_ag_hold_incoming_call(void){
2223     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_INCOMING_CALL_BY_AG, NULL);
2224 }
2225 
2226 void hfp_ag_accept_held_incoming_call(void) {
2227     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_ACCEPT_HELD_CALL_BY_AG, NULL);
2228 }
2229 
2230 void hfp_ag_reject_held_incoming_call(void){
2231     hfp_ag_call_sm(HFP_AG_RESPONSE_AND_HOLD_REJECT_HELD_CALL_BY_AG, NULL);
2232 }
2233 
2234 static void hfp_ag_set_ag_indicator(const char * name, int value){
2235     int indicator_index = get_ag_indicator_index_for_name(name);
2236     if (indicator_index < 0) return;
2237     hfp_ag_indicators[indicator_index].status = value;
2238 
2239 
2240     btstack_linked_list_iterator_t it;
2241     btstack_linked_list_iterator_init(&it, hfp_get_connections());
2242     while (btstack_linked_list_iterator_has_next(&it)){
2243         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
2244         if (! hfp_connection->ag_indicators[indicator_index].enabled) {
2245             log_info("AG indicator '%s' changed to %u but not enabled", hfp_ag_indicators[indicator_index].name, value);
2246             continue;
2247         }
2248         log_info("AG indicator '%s' changed to %u, request transfer statur", hfp_ag_indicators[indicator_index].name, value);
2249         hfp_connection->ag_indicators_status_update_bitmap = store_bit(hfp_connection->ag_indicators_status_update_bitmap, indicator_index, 1);
2250         hfp_run_for_context(hfp_connection);
2251     }
2252 }
2253 
2254 void hfp_ag_set_registration_status(int status){
2255     hfp_ag_set_ag_indicator("service", status);
2256 }
2257 
2258 void hfp_ag_set_signal_strength(int strength){
2259     hfp_ag_set_ag_indicator("signal", strength);
2260 }
2261 
2262 void hfp_ag_set_roaming_status(int status){
2263     hfp_ag_set_ag_indicator("roam", status);
2264 }
2265 
2266 void hfp_ag_set_battery_level(int level){
2267     hfp_ag_set_ag_indicator("battchg", level);
2268 }
2269 
2270 void hfp_ag_activate_voice_recognition(hci_con_handle_t acl_handle, int activate){
2271     if (!get_bit(hfp_supported_features, HFP_AGSF_VOICE_RECOGNITION_FUNCTION)) return;
2272     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2273     if (!hfp_connection){
2274         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2275         return;
2276     }
2277 
2278     if (!get_bit(hfp_connection->remote_supported_features, HFP_HFSF_VOICE_RECOGNITION_FUNCTION)) {
2279         log_info("AG cannot acivate voice recognition - not supported by HF");
2280         return;
2281     }
2282 
2283     if (activate){
2284         hfp_ag_establish_audio_connection(acl_handle);
2285     }
2286 
2287     hfp_connection->ag_activate_voice_recognition = activate;
2288     hfp_connection->command = HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION;
2289     hfp_run_for_context(hfp_connection);
2290 }
2291 
2292 void hfp_ag_set_microphone_gain(hci_con_handle_t acl_handle, int gain){
2293     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2294     if (!hfp_connection){
2295         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2296         return;
2297     }
2298     if (hfp_connection->microphone_gain != gain){
2299         hfp_connection->command = HFP_CMD_SET_MICROPHONE_GAIN;
2300         hfp_connection->microphone_gain = gain;
2301         hfp_connection->send_microphone_gain = 1;
2302     }
2303     hfp_run_for_context(hfp_connection);
2304 }
2305 
2306 void hfp_ag_set_speaker_gain(hci_con_handle_t acl_handle, int gain){
2307     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2308     if (!hfp_connection){
2309         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2310         return;
2311     }
2312     if (hfp_connection->speaker_gain != gain){
2313         hfp_connection->speaker_gain = gain;
2314         hfp_connection->send_speaker_gain = 1;
2315     }
2316     hfp_run_for_context(hfp_connection);
2317 }
2318 
2319 void hfp_ag_send_phone_number_for_voice_tag(hci_con_handle_t acl_handle, const char * number){
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_ag_set_clip(0, number);
2326     hfp_connection->send_phone_number_for_voice_tag = 1;
2327 }
2328 
2329 void hfp_ag_reject_phone_number_for_voice_tag(hci_con_handle_t acl_handle){
2330     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2331     if (!hfp_connection){
2332         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2333         return;
2334     }
2335     hfp_connection->send_error = 1;
2336 }
2337 
2338 void hfp_ag_send_dtmf_code_done(hci_con_handle_t acl_handle){
2339     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2340     if (!hfp_connection){
2341         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2342         return;
2343     }
2344     hfp_connection->ok_pending = 1;
2345 }
2346 
2347 void hfp_ag_set_subcriber_number_information(hfp_phone_number_t * numbers, int numbers_count){
2348     subscriber_numbers = numbers;
2349     subscriber_numbers_count = numbers_count;
2350 }
2351 
2352 void hfp_ag_clear_last_dialed_number(void){
2353     hfp_gsm_clear_last_dialed_number();
2354 }
2355 
2356 void hfp_ag_notify_incoming_call_waiting(hci_con_handle_t acl_handle){
2357     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_acl_handle(acl_handle);
2358     if (!hfp_connection){
2359         log_error("HFP AG: ACL connection 0x%2x is not found.", acl_handle);
2360         return;
2361     }
2362     if (!hfp_connection->call_waiting_notification_enabled) return;
2363 
2364     hfp_connection->ag_notify_incoming_call_waiting = 1;
2365     hfp_run_for_context(hfp_connection);
2366 }
2367 
2368