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