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