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