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