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