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