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