xref: /btstack/src/classic/hfp.c (revision 98451c7b102094e15e0a72ca2f7098d91aed2017)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "hfp.c"
39 
40 
41 #include "btstack_config.h"
42 
43 #include <stdint.h>
44 #include <string.h>
45 #include <inttypes.h>
46 
47 #include "bluetooth_sdp.h"
48 #include "btstack_debug.h"
49 #include "btstack_event.h"
50 #include "btstack_memory.h"
51 #include "btstack_run_loop.h"
52 #include "classic/core.h"
53 #include "classic/sdp_client_rfcomm.h"
54 #include "classic/sdp_server.h"
55 #include "classic/sdp_util.h"
56 #include "classic/sdp_client.h"
57 #include "hci.h"
58 #include "hci_cmd.h"
59 #include "hci_dump.h"
60 #include "l2cap.h"
61 
62 #if defined(ENABLE_CC256X_ASSISTED_HFP) && !defined(ENABLE_SCO_OVER_PCM)
63 #error "Assisted HFP is only possible over PCM/I2S. Please add define: ENABLE_SCO_OVER_PCM"
64 #endif
65 
66 #if defined(ENABLE_BCM_PCM_WBS) && !defined(ENABLE_SCO_OVER_PCM)
67 #error "WBS for PCM is only possible over PCM/I2S. Please add define: ENABLE_SCO_OVER_PCM"
68 #endif
69 
70 #define HFP_HF_FEATURES_SIZE 10
71 #define HFP_AG_FEATURES_SIZE 12
72 
73 typedef struct {
74     hfp_role_t local_role;
75     bd_addr_t  remote_address;
76 } hfp_sdp_query_context_t;
77 
78 // globals
79 
80 static hfp_sdp_query_context_t sdp_query_context;
81 static btstack_context_callback_registration_t hfp_handle_sdp_client_query_request;
82 
83 static btstack_linked_list_t hfp_connections ;
84 
85 static btstack_packet_handler_t hfp_hf_callback;
86 static btstack_packet_handler_t hfp_ag_callback;
87 
88 static btstack_packet_handler_t hfp_hf_rfcomm_packet_handler;
89 static btstack_packet_handler_t hfp_ag_rfcomm_packet_handler;
90 
91 static hfp_connection_t * sco_establishment_active;
92 
93 static uint16_t hfp_allowed_sco_packet_types;
94 
95 // prototypes
96 static hfp_link_settings_t hfp_next_link_setting_for_connection(hfp_link_settings_t current_setting, hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported);
97 static void parse_sequence(hfp_connection_t * context);
98 
99 
100 static const char * hfp_hf_features[] = {
101         "EC and/or NR function",
102         "Three-way calling",
103         "CLI presentation capability",
104         "Voice recognition activation",
105         "Remote volume control",
106 
107         "Enhanced call status",
108         "Enhanced call control",
109 
110         "Codec negotiation",
111 
112         "HF Indicators",
113         "eSCO S4 (and T2) Settings Supported",
114         "Reserved for future definition"
115 };
116 
117 static const char * hfp_ag_features[] = {
118         "Three-way calling",
119         "EC and/or NR function",
120         "Voice recognition function",
121         "In-band ring tone capability",
122         "Attach a number to a voice tag",
123         "Ability to reject a call",
124         "Enhanced call status",
125         "Enhanced call control",
126         "Extended Error Result Codes",
127         "Codec negotiation",
128         "HF Indicators",
129         "eSCO S4 (and T2) Settings Supported",
130         "Reserved for future definition"
131 };
132 
133 static const char * hfp_enhanced_call_dir[] = {
134         "outgoing",
135         "incoming"
136 };
137 
138 static const char * hfp_enhanced_call_status[] = {
139         "active",
140         "held",
141         "outgoing dialing",
142         "outgoing alerting",
143         "incoming",
144         "incoming waiting",
145         "call held by response and hold"
146 };
147 
148 static const char * hfp_enhanced_call_mode[] = {
149         "voice",
150         "data",
151         "fax"
152 };
153 
154 static const char * hfp_enhanced_call_mpty[] = {
155         "not a conference call",
156         "conference call"
157 };
158 
159 const char * hfp_enhanced_call_dir2str(uint16_t index){
160     if (index <= HFP_ENHANCED_CALL_DIR_INCOMING) return hfp_enhanced_call_dir[index];
161     return "not defined";
162 }
163 
164 const char * hfp_enhanced_call_status2str(uint16_t index){
165     if (index <= HFP_ENHANCED_CALL_STATUS_CALL_HELD_BY_RESPONSE_AND_HOLD) return hfp_enhanced_call_status[index];
166     return "not defined";
167 }
168 
169 const char * hfp_enhanced_call_mode2str(uint16_t index){
170     if (index <= HFP_ENHANCED_CALL_MODE_FAX) return hfp_enhanced_call_mode[index];
171     return "not defined";
172 }
173 
174 const char * hfp_enhanced_call_mpty2str(uint16_t index){
175     if (index <= HFP_ENHANCED_CALL_MPTY_CONFERENCE_CALL) return hfp_enhanced_call_mpty[index];
176     return "not defined";
177 }
178 
179 static uint16_t hfp_parse_indicator_index(hfp_connection_t * hfp_connection){
180     uint16_t index = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
181 
182     if (index > HFP_MAX_NUM_INDICATORS){
183         log_info("ignoring invalid indicator index bigger then HFP_MAX_NUM_INDICATORS");
184         return HFP_MAX_NUM_INDICATORS - 1;
185     }
186 
187     // indicator index enumeration starts with 1, we substract 1 to store in array with starting index 0
188     if (index > 0){
189         index -= 1;
190     } else {
191         log_info("ignoring invalid indicator index 0");
192         return 0;
193     }
194     return index;
195 }
196 
197 static void hfp_next_indicators_index(hfp_connection_t * hfp_connection){
198     if (hfp_connection->parser_item_index < HFP_MAX_NUM_INDICATORS - 1){
199         hfp_connection->parser_item_index++;
200     } else {
201         log_info("Ignoring additional indicator");
202     }
203 }
204 
205 static void hfp_next_codec_index(hfp_connection_t * hfp_connection){
206     if (hfp_connection->parser_item_index < HFP_MAX_NUM_CODECS - 1){
207         hfp_connection->parser_item_index++;
208     } else {
209         log_info("Ignoring additional codec index");
210     }
211 }
212 
213 static void hfp_next_remote_call_services_index(hfp_connection_t * hfp_connection){
214     if (hfp_connection->remote_call_services_index < HFP_MAX_NUM_CALL_SERVICES - 1){
215         hfp_connection->remote_call_services_index++;
216     } else {
217         log_info("Ignoring additional remote_call_services");
218     }
219 }
220 
221 const char * hfp_hf_feature(int index){
222     if (index > HFP_HF_FEATURES_SIZE){
223         return hfp_hf_features[HFP_HF_FEATURES_SIZE];
224     }
225     return hfp_hf_features[index];
226 }
227 
228 const char * hfp_ag_feature(int index){
229     if (index > HFP_AG_FEATURES_SIZE){
230         return hfp_ag_features[HFP_AG_FEATURES_SIZE];
231     }
232     return hfp_ag_features[index];
233 }
234 
235 int send_str_over_rfcomm(uint16_t cid, char * command){
236     if (!rfcomm_can_send_packet_now(cid)) return 1;
237     log_info("HFP_TX %s", command);
238     int err = rfcomm_send(cid, (uint8_t*) command, strlen(command));
239     if (err){
240         log_error("rfcomm_send -> error 0x%02x \n", err);
241     }
242 #ifdef ENABLE_HFP_AT_MESSAGES
243     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_rfcomm_cid(cid);
244     hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_SENT, command);
245 #endif
246     return 1;
247 }
248 
249 int hfp_supports_codec(uint8_t codec, int codecs_nr, uint8_t * codecs){
250 
251     // mSBC requires support for eSCO connections
252     if ((codec == HFP_CODEC_MSBC) && !hci_extended_sco_link_supported()) return 0;
253 
254     int i;
255     for (i = 0; i < codecs_nr; i++){
256         if (codecs[i] != codec) continue;
257         return 1;
258     }
259     return 0;
260 }
261 
262 void hfp_hf_drop_mSBC_if_eSCO_not_supported(uint8_t * codecs, uint8_t * codecs_nr){
263     if (hci_extended_sco_link_supported()) return;
264     uint8_t tmp_codecs[HFP_MAX_NUM_CODECS];
265     int i;
266     int tmp_codec_nr = 0;
267     for (i=0; i < *codecs_nr; i++){
268         if (codecs[i] == HFP_CODEC_MSBC) continue;
269         tmp_codecs[tmp_codec_nr++] = codecs[i];
270     }
271     *codecs_nr = tmp_codec_nr;
272     (void)memcpy(codecs, tmp_codecs, tmp_codec_nr);
273 }
274 
275 // UTILS
276 int get_bit(uint16_t bitmap, int position){
277     return (bitmap >> position) & 1;
278 }
279 
280 int store_bit(uint32_t bitmap, int position, uint8_t value){
281     if (value){
282         bitmap |= 1 << position;
283     } else {
284         bitmap &= ~ (1 << position);
285     }
286     return bitmap;
287 }
288 
289 int join(char * buffer, int buffer_size, uint8_t * values, int values_nr){
290     if (buffer_size < (values_nr * 3)) return 0;
291     int i;
292     int offset = 0;
293     for (i = 0; i < (values_nr-1); i++) {
294       offset += snprintf(buffer+offset, buffer_size-offset, "%d,", values[i]); // puts string into buffer
295     }
296     if (i<values_nr){
297         offset += snprintf(buffer+offset, buffer_size-offset, "%d", values[i]);
298     }
299     return offset;
300 }
301 
302 int join_bitmap(char * buffer, int buffer_size, uint32_t values, int values_nr){
303     if (buffer_size < (values_nr * 3)) return 0;
304 
305     int i;
306     int offset = 0;
307     for (i = 0; i < (values_nr-1); i++) {
308       offset += snprintf(buffer+offset, buffer_size-offset, "%d,", get_bit(values,i)); // puts string into buffer
309     }
310 
311     if (i<values_nr){
312         offset += snprintf(buffer+offset, buffer_size-offset, "%d", get_bit(values,i));
313     }
314     return offset;
315 }
316 
317 static void hfp_emit_event_for_context(hfp_connection_t * hfp_connection, uint8_t * packet, uint16_t size){
318     if (!hfp_connection) return;
319     btstack_packet_handler_t callback = NULL;
320     switch (hfp_connection->local_role){
321         case HFP_ROLE_HF:
322             callback = hfp_hf_callback;
323             break;
324         case HFP_ROLE_AG:
325             callback = hfp_ag_callback;
326             break;
327         default:
328             return;
329     }
330     (*callback)(HCI_EVENT_PACKET, 0, packet, size);
331 }
332 
333 void hfp_emit_simple_event(hfp_connection_t * hfp_connection, uint8_t event_subtype){
334     uint8_t event[3];
335     event[0] = HCI_EVENT_HFP_META;
336     event[1] = sizeof(event) - 2;
337     event[2] = event_subtype;
338     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
339 }
340 
341 void hfp_emit_event(hfp_connection_t * hfp_connection, uint8_t event_subtype, uint8_t value){
342     uint8_t event[4];
343     event[0] = HCI_EVENT_HFP_META;
344     event[1] = sizeof(event) - 2;
345     event[2] = event_subtype;
346     event[3] = value; // status 0 == OK
347     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
348 }
349 
350 void hfp_emit_slc_connection_event(hfp_connection_t * hfp_connection, uint8_t status, hci_con_handle_t con_handle, bd_addr_t addr){
351     uint8_t event[12];
352     int pos = 0;
353     event[pos++] = HCI_EVENT_HFP_META;
354     event[pos++] = sizeof(event) - 2;
355     event[pos++] = HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
356     event[pos++] = status; // status 0 == OK
357     little_endian_store_16(event, pos, con_handle);
358     pos += 2;
359     reverse_bd_addr(addr,&event[pos]);
360     pos += 6;
361     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
362 }
363 
364 void hfp_emit_sco_event(hfp_connection_t * hfp_connection, uint8_t status, hci_con_handle_t con_handle, bd_addr_t addr, uint8_t  negotiated_codec){
365     uint8_t event[13];
366     int pos = 0;
367     event[pos++] = HCI_EVENT_HFP_META;
368     event[pos++] = sizeof(event) - 2;
369     event[pos++] = HFP_SUBEVENT_AUDIO_CONNECTION_ESTABLISHED;
370     event[pos++] = status; // status 0 == OK
371     little_endian_store_16(event, pos, con_handle);
372     pos += 2;
373     reverse_bd_addr(addr,&event[pos]);
374     pos += 6;
375     event[pos++] = negotiated_codec;
376     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
377 }
378 
379 void hfp_emit_string_event(hfp_connection_t * hfp_connection, uint8_t event_subtype, const char * value){
380 #ifdef ENABLE_HFP_AT_MESSAGES
381     uint8_t event[256];
382 #else
383     uint8_t event[40];
384 #endif
385     event[0] = HCI_EVENT_HFP_META;
386     event[1] = sizeof(event) - 2;
387     event[2] = event_subtype;
388     uint16_t size = btstack_min(strlen(value), sizeof(event) - 4);
389     strncpy((char*)&event[3], value, size);
390     event[3 + size] = 0;
391     hfp_emit_event_for_context(hfp_connection, event, sizeof(event));
392 }
393 
394 btstack_linked_list_t * hfp_get_connections(void){
395     return (btstack_linked_list_t *) &hfp_connections;
396 }
397 
398 hfp_connection_t * get_hfp_connection_context_for_rfcomm_cid(uint16_t cid){
399     btstack_linked_list_iterator_t it;
400     btstack_linked_list_iterator_init(&it, hfp_get_connections());
401     while (btstack_linked_list_iterator_has_next(&it)){
402         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
403         if (hfp_connection->rfcomm_cid == cid){
404             return hfp_connection;
405         }
406     }
407     return NULL;
408 }
409 
410 hfp_connection_t * get_hfp_connection_context_for_bd_addr(bd_addr_t bd_addr, hfp_role_t hfp_role){
411     btstack_linked_list_iterator_t it;
412     btstack_linked_list_iterator_init(&it, hfp_get_connections());
413     while (btstack_linked_list_iterator_has_next(&it)){
414         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
415         if ((memcmp(hfp_connection->remote_addr, bd_addr, 6) == 0) && (hfp_connection->local_role == hfp_role)) {
416             return hfp_connection;
417         }
418     }
419     return NULL;
420 }
421 
422 hfp_connection_t * get_hfp_connection_context_for_sco_handle(uint16_t handle, hfp_role_t hfp_role){
423     btstack_linked_list_iterator_t it;
424     btstack_linked_list_iterator_init(&it, hfp_get_connections());
425     while (btstack_linked_list_iterator_has_next(&it)){
426         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
427         if ((hfp_connection->sco_handle == handle) && (hfp_connection->local_role == hfp_role)){
428             return hfp_connection;
429         }
430     }
431     return NULL;
432 }
433 
434 hfp_connection_t * get_hfp_connection_context_for_acl_handle(uint16_t handle, hfp_role_t hfp_role){
435     btstack_linked_list_iterator_t it;
436     btstack_linked_list_iterator_init(&it, hfp_get_connections());
437     while (btstack_linked_list_iterator_has_next(&it)){
438         hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
439         if ((hfp_connection->acl_handle == handle) && (hfp_connection->local_role == hfp_role)){
440             return hfp_connection;
441         }
442     }
443     return NULL;
444 }
445 
446 void hfp_reset_context_flags(hfp_connection_t * hfp_connection){
447     if (!hfp_connection) return;
448     hfp_connection->ok_pending = 0;
449     hfp_connection->send_error = 0;
450 
451     hfp_connection->found_equal_sign = false;
452 
453     hfp_connection->change_status_update_for_individual_ag_indicators = 0;
454     hfp_connection->operator_name_changed = 0;
455 
456     hfp_connection->enable_extended_audio_gateway_error_report = 0;
457     hfp_connection->extended_audio_gateway_error = 0;
458 
459     // establish codecs hfp_connection
460     hfp_connection->suggested_codec = 0;
461     hfp_connection->negotiated_codec = 0;
462     hfp_connection->codec_confirmed = 0;
463 
464     hfp_connection->establish_audio_connection = 0;
465     hfp_connection->call_waiting_notification_enabled = 0;
466     hfp_connection->command = HFP_CMD_NONE;
467     hfp_connection->enable_status_update_for_ag_indicators = 0xFF;
468 }
469 
470 static hfp_connection_t * create_hfp_connection_context(void){
471     hfp_connection_t * hfp_connection = btstack_memory_hfp_connection_get();
472     if (!hfp_connection) return NULL;
473 
474     hfp_connection->state = HFP_IDLE;
475     hfp_connection->call_state = HFP_CALL_IDLE;
476     hfp_connection->codecs_state = HFP_CODECS_IDLE;
477 
478     hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
479     hfp_connection->command = HFP_CMD_NONE;
480 
481     hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID;
482     hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID;
483 
484     hfp_reset_context_flags(hfp_connection);
485 
486     btstack_linked_list_add(&hfp_connections, (btstack_linked_item_t*)hfp_connection);
487     return hfp_connection;
488 }
489 
490 static void remove_hfp_connection_context(hfp_connection_t * hfp_connection){
491     btstack_linked_list_remove(&hfp_connections, (btstack_linked_item_t*) hfp_connection);
492     btstack_memory_hfp_connection_free(hfp_connection);
493 }
494 
495 static hfp_connection_t * provide_hfp_connection_context_for_bd_addr(bd_addr_t bd_addr, hfp_role_t local_role){
496     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(bd_addr, local_role);
497     if (hfp_connection) return  hfp_connection;
498     hfp_connection = create_hfp_connection_context();
499     (void)memcpy(hfp_connection->remote_addr, bd_addr, 6);
500     hfp_connection->local_role = local_role;
501     log_info("Create HFP context %p: role %u, addr %s", hfp_connection, local_role, bd_addr_to_str(bd_addr));
502 
503     return hfp_connection;
504 }
505 
506 /* @param network.
507  * 0 == no ability to reject a call.
508  * 1 == ability to reject a call.
509  */
510 
511 /* @param suported_features
512  * HF bit 0: EC and/or NR function (yes/no, 1 = yes, 0 = no)
513  * HF bit 1: Call waiting or three-way calling(yes/no, 1 = yes, 0 = no)
514  * HF bit 2: CLI presentation capability (yes/no, 1 = yes, 0 = no)
515  * HF bit 3: Voice recognition activation (yes/no, 1= yes, 0 = no)
516  * HF bit 4: Remote volume control (yes/no, 1 = yes, 0 = no)
517  * HF bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
518  */
519  /* Bit position:
520  * AG bit 0: Three-way calling (yes/no, 1 = yes, 0 = no)
521  * AG bit 1: EC and/or NR function (yes/no, 1 = yes, 0 = no)
522  * AG bit 2: Voice recognition function (yes/no, 1 = yes, 0 = no)
523  * AG bit 3: In-band ring tone capability (yes/no, 1 = yes, 0 = no)
524  * AG bit 4: Attach a phone number to a voice tag (yes/no, 1 = yes, 0 = no)
525  * AG bit 5: Wide band speech (yes/no, 1 = yes, 0 = no)
526  */
527 
528 void hfp_create_sdp_record(uint8_t * service, uint32_t service_record_handle, uint16_t service_uuid, int rfcomm_channel_nr, const char * name){
529     uint8_t* attribute;
530     de_create_sequence(service);
531 
532     // 0x0000 "Service Record Handle"
533     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
534     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
535 
536     // 0x0001 "Service Class ID List"
537     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
538     attribute = de_push_sequence(service);
539     {
540         //  "UUID for Service"
541         de_add_number(attribute, DE_UUID, DE_SIZE_16, service_uuid);
542         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_GENERIC_AUDIO);
543     }
544     de_pop_sequence(service, attribute);
545 
546     // 0x0004 "Protocol Descriptor List"
547     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
548     attribute = de_push_sequence(service);
549     {
550         uint8_t* l2cpProtocol = de_push_sequence(attribute);
551         {
552             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
553         }
554         de_pop_sequence(attribute, l2cpProtocol);
555 
556         uint8_t* rfcomm = de_push_sequence(attribute);
557         {
558             de_add_number(rfcomm,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_RFCOMM);  // rfcomm_service
559             de_add_number(rfcomm,  DE_UINT, DE_SIZE_8,  rfcomm_channel_nr);  // rfcomm channel
560         }
561         de_pop_sequence(attribute, rfcomm);
562     }
563     de_pop_sequence(service, attribute);
564 
565 
566     // 0x0005 "Public Browse Group"
567     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
568     attribute = de_push_sequence(service);
569     {
570         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
571     }
572     de_pop_sequence(service, attribute);
573 
574     // 0x0009 "Bluetooth Profile Descriptor List"
575     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
576     attribute = de_push_sequence(service);
577     {
578         uint8_t *sppProfile = de_push_sequence(attribute);
579         {
580             de_add_number(sppProfile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HANDSFREE);
581             de_add_number(sppProfile,  DE_UINT, DE_SIZE_16, 0x0107); // Verision 1.7
582         }
583         de_pop_sequence(attribute, sppProfile);
584     }
585     de_pop_sequence(service, attribute);
586 
587     // 0x0100 "Service Name"
588     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
589     de_add_data(service,  DE_STRING, strlen(name), (uint8_t *) name);
590 }
591 
592 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
593     UNUSED(packet_type);    // ok: handling own sdp events
594     UNUSED(channel);        // ok: no channel
595     UNUSED(size);           // ok: handling own sdp events
596 
597     hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(sdp_query_context.remote_address, sdp_query_context.local_role);
598     if (hfp_connection == NULL) {
599         log_info("connection with %s and local role %d not found", sdp_query_context.remote_address, sdp_query_context.local_role);
600         return;
601     }
602 
603     switch (hci_event_packet_get_type(packet)){
604         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
605             hfp_connection->rfcomm_channel_nr = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
606             break;
607         case SDP_EVENT_QUERY_COMPLETE:
608             if (hfp_connection->rfcomm_channel_nr > 0){
609                 hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
610                 btstack_packet_handler_t packet_handler;
611                 switch (hfp_connection->local_role){
612                     case HFP_ROLE_AG:
613                         packet_handler = hfp_ag_rfcomm_packet_handler;
614                         break;
615                     case HFP_ROLE_HF:
616                         packet_handler = hfp_hf_rfcomm_packet_handler;
617                         break;
618                     default:
619                         btstack_assert(false);
620                         return;
621                 }
622 
623                 rfcomm_create_channel(packet_handler, hfp_connection->remote_addr, hfp_connection->rfcomm_channel_nr, NULL);
624 
625             } else {
626                 hfp_connection->state = HFP_IDLE;
627                 uint8_t status = sdp_event_query_complete_get_status(packet);
628                 if (status == ERROR_CODE_SUCCESS){
629                     // report service not found
630                     status = SDP_SERVICE_NOT_FOUND;
631                 }
632                 hfp_emit_slc_connection_event(hfp_connection, status, HCI_CON_HANDLE_INVALID, hfp_connection->remote_addr);
633                 log_info("rfcomm service not found, status 0x%02x", status);
634             }
635 
636             // register the SDP Query request to check if there is another connection waiting for the query
637             // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
638             (void) sdp_client_register_query_callback(&hfp_handle_sdp_client_query_request);
639             break;
640         default:
641             break;
642     }
643 }
644 
645 // returns 0 if unexpected error or no other link options remained, otherwise 1
646 static int hfp_handle_failed_sco_connection(uint8_t status){
647 
648     if (!sco_establishment_active){
649         log_info("(e)SCO Connection failed but not started by us");
650         return 0;
651     }
652 
653     log_info("(e)SCO Connection failed 0x%02x", status);
654     switch (status){
655         case ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE:
656         case ERROR_CODE_UNSPECIFIED_ERROR:
657         case ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES:
658             break;
659         default:
660             return 0;
661     }
662 
663     // note: eSCO_S4 supported flag not available, but it's only relevant for highest CVSD link setting (and the current failed)
664     hfp_link_settings_t next_setting = hfp_next_link_setting_for_connection(sco_establishment_active->link_setting, sco_establishment_active, false);
665 
666     // handle no valid setting found
667     if (next_setting == HFP_LINK_SETTINGS_NONE) {
668         if (sco_establishment_active->negotiated_codec == HFP_CODEC_MSBC){
669             log_info("T2/T1 failed, fallback to CVSD - D1");
670             sco_establishment_active->negotiated_codec = HFP_CODEC_CVSD;
671             sco_establishment_active->sco_for_msbc_failed = 1;
672             sco_establishment_active->command = HFP_CMD_AG_SEND_COMMON_CODEC;
673             sco_establishment_active->link_setting = HFP_LINK_SETTINGS_D1;
674         } else {
675             // no other options
676             return 0;
677         }
678     }
679 
680     log_info("e)SCO Connection: try new link_setting %d", next_setting);
681     sco_establishment_active->establish_audio_connection = 1;
682     sco_establishment_active->link_setting = next_setting;
683     sco_establishment_active = NULL;
684     return 1;
685 }
686 
687 
688 void hfp_handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
689     UNUSED(packet_type);
690     UNUSED(channel);    // ok: no channel
691     UNUSED(size);
692 
693     bd_addr_t event_addr;
694     hci_con_handle_t handle;
695     hfp_connection_t * hfp_connection = NULL;
696     uint8_t status;
697 
698     log_debug("HFP HCI event handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
699 
700     switch (hci_event_packet_get_type(packet)) {
701 
702         case HCI_EVENT_CONNECTION_REQUEST:
703             switch(hci_event_connection_request_get_link_type(packet)){
704                 case 0: //  SCO
705                 case 2: // eSCO
706                     hci_event_connection_request_get_bd_addr(packet, event_addr);
707                     hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
708                     if (!hfp_connection) break;
709                     if (hci_event_connection_request_get_link_type(packet) == 2){
710                         hfp_connection->hf_accept_sco = 2;
711                     } else {
712                         hfp_connection->hf_accept_sco = 1;
713                     }
714 #ifdef ENABLE_CC256X_ASSISTED_HFP
715                     hfp_cc256x_prepare_for_sco(hfp_connection);
716 #endif
717 #ifdef ENABLE_BCM_PCM_WBS
718                     hfp_bcm_prepare_for_sco(hfp_connection);
719 #endif
720                     log_info("hf accept sco %u\n", hfp_connection->hf_accept_sco);
721                     sco_establishment_active = hfp_connection;
722                     break;
723                 default:
724                     break;
725             }
726             break;
727 
728         case HCI_EVENT_COMMAND_STATUS:
729             if (hci_event_command_status_get_command_opcode(packet) == hci_setup_synchronous_connection.opcode) {
730                 if (sco_establishment_active == NULL) break;
731                 status = hci_event_command_status_get_status(packet);
732                 if (status == ERROR_CODE_SUCCESS) break;
733 
734                 hfp_connection = sco_establishment_active;
735                 if (hfp_handle_failed_sco_connection(status)) break;
736                 hfp_connection->establish_audio_connection = 0;
737                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
738                 hfp_emit_sco_event(hfp_connection, status, 0, hfp_connection->remote_addr, hfp_connection->negotiated_codec);
739             }
740             break;
741 
742         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
743             if (sco_establishment_active == NULL) break;
744             hci_event_synchronous_connection_complete_get_bd_addr(packet, event_addr);
745             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
746             if (!hfp_connection) {
747                 log_error("HFP: connection does not exist for remote with addr %s.", bd_addr_to_str(event_addr));
748                 return;
749             }
750 
751             status = hci_event_synchronous_connection_complete_get_status(packet);
752             if (status != ERROR_CODE_SUCCESS){
753                 hfp_connection->hf_accept_sco = 0;
754                 if (hfp_handle_failed_sco_connection(status)) break;
755 
756                 hfp_connection->establish_audio_connection = 0;
757                 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
758                 hfp_emit_sco_event(hfp_connection, status, 0, event_addr, hfp_connection->negotiated_codec);
759                 break;
760             }
761 
762             uint16_t sco_handle = hci_event_synchronous_connection_complete_get_handle(packet);
763             uint8_t  link_type = hci_event_synchronous_connection_complete_get_link_type(packet);
764             uint8_t  transmission_interval = hci_event_synchronous_connection_complete_get_transmission_interval(packet);  // measured in slots
765             uint8_t  retransmission_interval = hci_event_synchronous_connection_complete_get_retransmission_interval(packet);// measured in slots
766             uint16_t rx_packet_length = hci_event_synchronous_connection_complete_get_rx_packet_length(packet); // measured in bytes
767             uint16_t tx_packet_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet); // measured in bytes
768 
769             switch (link_type){
770                 case 0x00:
771                     log_info("SCO Connection established.");
772                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
773                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
774                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
775                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
776                     break;
777                 case 0x02:
778                     log_info("eSCO Connection established. \n");
779                     break;
780                 default:
781                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
782                     break;
783             }
784 
785             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
786                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)\n", sco_handle,
787                  bd_addr_to_str(event_addr), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length,
788                  hci_event_synchronous_connection_complete_get_air_mode(packet));
789 
790             if (hfp_connection->state == HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){
791                 log_info("SCO about to disconnect: HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN");
792                 hfp_connection->state = HFP_W2_DISCONNECT_SCO;
793                 break;
794             }
795             hfp_connection->sco_handle = sco_handle;
796             hfp_connection->establish_audio_connection = 0;
797             hfp_connection->state = HFP_AUDIO_CONNECTION_ESTABLISHED;
798             hfp_emit_sco_event(hfp_connection, status, sco_handle, event_addr, hfp_connection->negotiated_codec);
799             break;
800         }
801 
802         case HCI_EVENT_DISCONNECTION_COMPLETE:
803             handle = little_endian_read_16(packet,3);
804             hfp_connection = get_hfp_connection_context_for_sco_handle(handle, local_role);
805 
806             if (!hfp_connection) break;
807 
808 #ifdef ENABLE_CC256X_ASSISTED_HFP
809             hfp_connection->cc256x_send_wbs_disassociate = true;
810 #endif
811 #ifdef ENABLE_BCM_PCM_WBS
812             hfp_connection->bcm_send_disable_wbs = true;
813 #endif
814             hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID;
815             hfp_connection->release_audio_connection = 0;
816             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
817             hfp_emit_event(hfp_connection, HFP_SUBEVENT_AUDIO_CONNECTION_RELEASED, 0);
818 
819             if (hfp_connection->release_slc_connection){
820                 hfp_connection->release_slc_connection = 0;
821                 log_info("SCO disconnected, w2 disconnect RFCOMM\n");
822                 hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
823             }
824             break;
825 
826         default:
827             break;
828     }
829 }
830 
831 
832 void hfp_handle_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){
833     UNUSED(packet_type);
834     UNUSED(channel);    // ok: no channel
835     UNUSED(size);
836 
837     bd_addr_t event_addr;
838     uint16_t rfcomm_cid;
839     hfp_connection_t * hfp_connection = NULL;
840     uint8_t status;
841 
842     log_debug("HFP packet_handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size);
843 
844     switch (hci_event_packet_get_type(packet)) {
845 
846         case RFCOMM_EVENT_INCOMING_CONNECTION:
847             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
848             rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
849             hfp_connection = provide_hfp_connection_context_for_bd_addr(event_addr, local_role);
850             if (!hfp_connection){
851                 log_info("hfp: no memory to accept incoming connection - decline");
852                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
853                 return;
854             }
855             if (hfp_connection->state != HFP_IDLE) {
856                 log_error("hfp: incoming connection but not idle, reject");
857                 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet));
858                 return;
859             }
860 
861             hfp_connection->rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
862             hfp_connection->state = HFP_W4_RFCOMM_CONNECTED;
863             rfcomm_accept_connection(hfp_connection->rfcomm_cid);
864             break;
865 
866         case RFCOMM_EVENT_CHANNEL_OPENED:
867             // data: event(8), len(8), status (8), address (48), handle(16), server channel(8), rfcomm_cid(16), max frame size(16)
868 
869             rfcomm_event_channel_opened_get_bd_addr(packet, event_addr);
870             status = rfcomm_event_channel_opened_get_status(packet);
871 
872             hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role);
873             if (!hfp_connection || (hfp_connection->state != HFP_W4_RFCOMM_CONNECTED)) return;
874 
875             if (status) {
876                 hfp_emit_slc_connection_event(hfp_connection, status, rfcomm_event_channel_opened_get_con_handle(packet), event_addr);
877                 remove_hfp_connection_context(hfp_connection);
878             } else {
879                 hfp_connection->acl_handle = rfcomm_event_channel_opened_get_con_handle(packet);
880                 hfp_connection->rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
881                 bd_addr_copy(hfp_connection->remote_addr, event_addr);
882 
883                 switch (hfp_connection->state){
884                     case HFP_W4_RFCOMM_CONNECTED:
885                         hfp_connection->state = HFP_EXCHANGE_SUPPORTED_FEATURES;
886                         break;
887                     case HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN:
888                         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
889                         break;
890                     default:
891                         break;
892                 }
893                 rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid);
894             }
895             break;
896 
897         case RFCOMM_EVENT_CHANNEL_CLOSED:
898             rfcomm_cid = little_endian_read_16(packet,2);
899             hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid);
900             if (!hfp_connection) break;
901             if (hfp_connection->state == HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART){
902                 hfp_connection->state = HFP_IDLE;
903                 hfp_establish_service_level_connection(hfp_connection->remote_addr, hfp_connection->service_uuid, local_role);
904                 break;
905             }
906 
907             hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0);
908             remove_hfp_connection_context(hfp_connection);
909             break;
910 
911         default:
912             break;
913     }
914 }
915 // translates command string into hfp_command_t CMD
916 
917 typedef struct {
918     const char * command;
919     hfp_command_t command_id;
920 } hfp_command_entry_t;
921 
922 static hfp_command_entry_t hfp_ag_commmand_table[] = {
923     { "AT+BAC=",   HFP_CMD_AVAILABLE_CODECS },
924     { "AT+BCC",    HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP },
925     { "AT+BCS=",   HFP_CMD_HF_CONFIRMED_CODEC },
926     { "AT+BIA=",   HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE, }, // +BIA:<enabled>,,<enabled>,,,<enabled>
927     { "AT+BIEV=",  HFP_CMD_HF_INDICATOR_STATUS },
928     { "AT+BIND=",  HFP_CMD_LIST_GENERIC_STATUS_INDICATORS },
929     { "AT+BIND=?", HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS },
930     { "AT+BIND?",  HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE },
931     { "AT+BINP",   HFP_CMD_HF_REQUEST_PHONE_NUMBER },
932     { "AT+BLDN",   HFP_CMD_REDIAL_LAST_NUMBER },
933     { "AT+BRSF=",  HFP_CMD_SUPPORTED_FEATURES },
934     { "AT+BTRH=",  HFP_CMD_RESPONSE_AND_HOLD_COMMAND },
935     { "AT+BTRH?",  HFP_CMD_RESPONSE_AND_HOLD_QUERY },
936     { "AT+BVRA=",  HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION },
937     { "AT+CCWA=",  HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION},
938     { "AT+CHLD=",  HFP_CMD_CALL_HOLD },
939     { "AT+CHLD=?", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
940     { "AT+CHUP",   HFP_CMD_HANG_UP_CALL },
941     { "AT+CIND=?", HFP_CMD_RETRIEVE_AG_INDICATORS },
942     { "AT+CIND?",  HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS },
943     { "AT+CLCC",   HFP_CMD_LIST_CURRENT_CALLS },
944     { "AT+CLIP=",  HFP_CMD_ENABLE_CLIP},
945     { "AT+CMEE=",  HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR},
946     { "AT+CMER=",  HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE },
947     { "AT+CNUM",   HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION },
948     { "AT+COPS=",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT },
949     { "AT+COPS?",  HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
950     { "AT+NREC=",  HFP_CMD_TURN_OFF_EC_AND_NR, },
951     { "AT+VGM=",   HFP_CMD_SET_MICROPHONE_GAIN },
952     { "AT+VGS=",   HFP_CMD_SET_SPEAKER_GAIN },
953     { "AT+VTS:",   HFP_CMD_TRANSMIT_DTMF_CODES },
954     { "ATA",       HFP_CMD_CALL_ANSWERED },
955 };
956 
957 static hfp_command_entry_t hfp_hf_commmand_table[] = {
958     { "+BCS:",  HFP_CMD_AG_SUGGESTED_CODEC },
959     { "+BIND:", HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS },
960     { "+BINP",  HFP_CMD_AG_SENT_PHONE_NUMBER },
961     { "+BRSF:", HFP_CMD_SUPPORTED_FEATURES },
962     { "+BSIR:", HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING },
963     { "+BTRH:", HFP_CMD_RESPONSE_AND_HOLD_STATUS },
964     { "+BVRA:", HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION },
965     { "+CCWA:", HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE, },
966     { "+CHLD:", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES },
967     { "+CIEV:", HFP_CMD_TRANSFER_AG_INDICATOR_STATUS},
968     { "+CIND:", HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC },
969     { "+CLCC:", HFP_CMD_LIST_CURRENT_CALLS },
970     { "+CLIP:", HFP_CMD_AG_SENT_CLIP_INFORMATION },
971     { "+CME ERROR:", HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR },
972     { "+CNUM:", HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION},
973     { "+COPS:", HFP_CMD_QUERY_OPERATOR_SELECTION_NAME },
974     { "+VGM:",  HFP_CMD_SET_MICROPHONE_GAIN },
975     { "+VGS:",  HFP_CMD_SET_SPEAKER_GAIN},
976     { "ERROR",  HFP_CMD_ERROR},
977     { "NOP",    HFP_CMD_NONE}, // dummy command used by unit tests
978     { "OK",     HFP_CMD_OK },
979     { "RING",   HFP_CMD_RING },
980 };
981 
982 static hfp_command_t parse_command(const char * line_buffer, int isHandsFree){
983 
984     // table lookup based on role
985     uint16_t num_entries;
986     hfp_command_entry_t * table;
987     if (isHandsFree == 0){
988         table = hfp_ag_commmand_table;
989         num_entries = sizeof(hfp_ag_commmand_table) / sizeof(hfp_command_entry_t);
990     } else {
991         table = hfp_hf_commmand_table;
992         num_entries = sizeof(hfp_hf_commmand_table) / sizeof(hfp_command_entry_t);
993     }
994     // binary search
995     uint16_t left = 0;
996     uint16_t right = num_entries - 1;
997     while (left <= right){
998         uint16_t middle = left + (right - left) / 2;
999         hfp_command_entry_t *entry = &table[middle];
1000         int match = strcmp(line_buffer, entry->command);
1001         if (match < 0){
1002             // search term is lower than middle element
1003             if (right == 0) break;
1004             right = middle - 1;
1005         } else if (match == 0){
1006             return entry->command_id;
1007         } else {
1008             // search term is higher than middle element
1009             left = middle + 1;
1010         }
1011     }
1012 
1013     // note: if parser in CMD_HEADER state would treats digits and maybe '+' as separator, match on "ATD" would work.
1014     // note: phone number is currently expected in line_buffer[3..]
1015     // prefix match on 'ATD', AG only
1016     if ((isHandsFree == 0) && (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0)){
1017         return HFP_CMD_CALL_PHONE_NUMBER;
1018     }
1019 
1020     // Valid looking, but unknown commands/responses
1021     if ((isHandsFree == 0) && (strncmp(line_buffer, "AT+", 3) == 0)){
1022         return HFP_CMD_UNKNOWN;
1023     }
1024 
1025     if ((isHandsFree != 0) && (strncmp(line_buffer, "+", 1) == 0)){
1026         return HFP_CMD_UNKNOWN;
1027     }
1028 
1029     return HFP_CMD_NONE;
1030 }
1031 
1032 static void hfp_parser_store_byte(hfp_connection_t * hfp_connection, uint8_t byte){
1033     if ((hfp_connection->line_size + 1 ) >= HFP_MAX_INDICATOR_DESC_SIZE) return;
1034     hfp_connection->line_buffer[hfp_connection->line_size++] = byte;
1035     hfp_connection->line_buffer[hfp_connection->line_size] = 0;
1036 }
1037 static int hfp_parser_is_buffer_empty(hfp_connection_t * hfp_connection){
1038     return hfp_connection->line_size == 0;
1039 }
1040 
1041 static int hfp_parser_is_end_of_line(uint8_t byte){
1042     return (byte == '\n') || (byte == '\r');
1043 }
1044 
1045 static void hfp_parser_reset_line_buffer(hfp_connection_t *hfp_connection) {
1046     hfp_connection->line_size = 0;
1047 }
1048 
1049 static void hfp_parser_store_if_token(hfp_connection_t * hfp_connection, uint8_t byte){
1050     switch (byte){
1051         case ',':
1052 		case '-':
1053         case ';':
1054         case '(':
1055         case ')':
1056         case '\n':
1057         case '\r':
1058             break;
1059         default:
1060             hfp_parser_store_byte(hfp_connection, byte);
1061             break;
1062     }
1063 }
1064 
1065 static bool hfp_parser_is_separator( uint8_t byte){
1066     switch (byte){
1067         case ',':
1068 		case '-':
1069         case ';':
1070         case '\n':
1071         case '\r':
1072             return true;
1073         default:
1074             return false;
1075     }
1076 }
1077 
1078 static bool hfp_parse_byte(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1079 
1080     // handle doubles quotes
1081     if (byte == '"'){
1082         hfp_connection->parser_quoted = !hfp_connection->parser_quoted;
1083         return true;
1084     }
1085     if (hfp_connection->parser_quoted) {
1086         hfp_parser_store_byte(hfp_connection, byte);
1087         return true;
1088     }
1089 
1090     // ignore spaces outside command or double quotes (required e.g. for '+CME ERROR:..") command
1091     if ((byte == ' ') && (hfp_connection->parser_state != HFP_PARSER_CMD_HEADER)) return true;
1092 
1093     bool processed = true;
1094 
1095     switch (hfp_connection->parser_state) {
1096         case HFP_PARSER_CMD_HEADER:
1097             switch (byte) {
1098                 case '\n':
1099                 case '\r':
1100                 case ';':
1101                     // ignore separator
1102                     break;
1103                 case ':':
1104                 case '?':
1105                     // store separator
1106                     hfp_parser_store_byte(hfp_connection, byte);
1107                     break;
1108                 case '=':
1109                     // equal sign: remember and wait for next char to decided between '=?' and '=\?'
1110                     hfp_connection->found_equal_sign = true;
1111                     hfp_parser_store_byte(hfp_connection, byte);
1112                     return true;
1113                 default:
1114                     // store if not lookahead
1115                     if (!hfp_connection->found_equal_sign) {
1116                         hfp_parser_store_byte(hfp_connection, byte);
1117                         return true;
1118                     }
1119                     // mark as lookahead
1120                     processed = false;
1121                     break;
1122             }
1123 
1124             // ignore empty tokens
1125             if (hfp_parser_is_buffer_empty(hfp_connection)) return true;
1126 
1127             // parse
1128             hfp_connection->command = parse_command((char *)hfp_connection->line_buffer, isHandsFree);
1129 
1130             // pick +CIND version based on connection state: descriptions during SLC vs. states later
1131             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC){
1132                 switch(hfp_connection->state){
1133                     case HFP_W4_RETRIEVE_INDICATORS_STATUS:
1134                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS;
1135                         break;
1136                     case HFP_W4_RETRIEVE_INDICATORS:
1137                         hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS;
1138                         break;
1139                     default:
1140                         hfp_connection->command = HFP_CMD_UNKNOWN;
1141                         break;
1142                 }
1143             }
1144 
1145             log_info("command string '%s', handsfree %u -> cmd id %u", (char *)hfp_connection->line_buffer, isHandsFree, hfp_connection->command);
1146 
1147             // next state
1148             hfp_connection->found_equal_sign = false;
1149             hfp_parser_reset_line_buffer(hfp_connection);
1150             hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1151 
1152             return processed;
1153 
1154         case HFP_PARSER_CMD_SEQUENCE:
1155             // handle empty fields
1156             if ((byte == ',' ) && (hfp_connection->line_size == 0)){
1157                 hfp_connection->line_buffer[0] = 0;
1158                 hfp_connection->ignore_value = 1;
1159                 parse_sequence(hfp_connection);
1160                 return true;
1161             }
1162 
1163             hfp_parser_store_if_token(hfp_connection, byte);
1164             if (!hfp_parser_is_separator(byte)) return true;
1165 
1166             // ignore empty tokens
1167             if (hfp_parser_is_buffer_empty(hfp_connection) && (hfp_connection->ignore_value == 0)) return true;
1168 
1169             parse_sequence(hfp_connection);
1170 
1171             hfp_parser_reset_line_buffer(hfp_connection);
1172 
1173             switch (hfp_connection->command){
1174                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1175                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1176                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1177                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1178                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1179                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1180                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1181                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1182                 case HFP_CMD_HF_INDICATOR_STATUS:
1183                     hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM;
1184                     break;
1185                 default:
1186                     break;
1187             }
1188             return true;
1189 
1190         case HFP_PARSER_SECOND_ITEM:
1191 
1192             hfp_parser_store_if_token(hfp_connection, byte);
1193             if (!hfp_parser_is_separator(byte)) return true;
1194 
1195             switch (hfp_connection->command){
1196                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1197                     log_info("format %s, ", hfp_connection->line_buffer);
1198                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1199                     break;
1200                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1201                     log_info("format %s \n", hfp_connection->line_buffer);
1202                     hfp_connection->network_operator.format =  btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1203                     break;
1204                 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1205                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1206                 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1207                     hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1208                     break;
1209                 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1210                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1211                     log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status);
1212                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1;
1213                     break;
1214                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1215                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer);
1216                     log_info("%s, ", hfp_connection->line_buffer);
1217                     break;
1218                 case HFP_CMD_AG_SENT_PHONE_NUMBER:
1219                 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1220                 case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1221                     hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1222                     break;
1223                 case HFP_CMD_HF_INDICATOR_STATUS:
1224                     hfp_connection->parser_indicator_value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1225                     break;
1226                 default:
1227                     break;
1228             }
1229 
1230             hfp_parser_reset_line_buffer(hfp_connection);
1231 
1232             hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM;
1233 
1234             return true;
1235 
1236         case HFP_PARSER_THIRD_ITEM:
1237 
1238             hfp_parser_store_if_token(hfp_connection, byte);
1239             if (!hfp_parser_is_separator(byte)) return true;
1240 
1241             switch (hfp_connection->command){
1242                 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1243                     strncpy(hfp_connection->network_operator.name, (char *)hfp_connection->line_buffer, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE);
1244                     hfp_connection->network_operator.name[HFP_MAX_NETWORK_OPERATOR_NAME_SIZE - 1] = 0;
1245                     log_info("name %s\n", hfp_connection->line_buffer);
1246                     break;
1247                 case HFP_CMD_RETRIEVE_AG_INDICATORS:
1248                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer);
1249                     hfp_next_indicators_index(hfp_connection);
1250                     hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index;
1251                     log_info("%s)\n", hfp_connection->line_buffer);
1252                     break;
1253                 default:
1254                     break;
1255             }
1256 
1257             hfp_parser_reset_line_buffer(hfp_connection);
1258 
1259             if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){
1260                 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE;
1261             } else {
1262                 hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1263             }
1264             return true;
1265 
1266         default:
1267             btstack_assert(false);
1268             return true;
1269     }
1270 }
1271 
1272 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){
1273     bool processed = false;
1274     while (!processed){
1275         processed = hfp_parse_byte(hfp_connection, byte, isHandsFree);
1276     }
1277     // reset parser state on end-of-line
1278     if (hfp_parser_is_end_of_line(byte)){
1279         hfp_connection->parser_item_index = 0;
1280         hfp_connection->parser_state = HFP_PARSER_CMD_HEADER;
1281     }
1282 }
1283 
1284 static void parse_sequence(hfp_connection_t * hfp_connection){
1285     int value;
1286     switch (hfp_connection->command){
1287         case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS:
1288             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1289             int i;
1290             switch (hfp_connection->parser_item_index){
1291                 case 0:
1292                     for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){
1293                         if (hfp_connection->generic_status_indicators[i].uuid == value){
1294                             hfp_connection->parser_indicator_index = i;
1295                             break;
1296                         }
1297                     }
1298                     break;
1299                 case 1:
1300                     if (hfp_connection->parser_indicator_index <0) break;
1301                     hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value;
1302                     log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n",
1303                      hfp_connection->parser_item_index, value);
1304                     break;
1305                 default:
1306                     break;
1307             }
1308             hfp_next_indicators_index(hfp_connection);
1309             break;
1310 
1311         case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION:
1312             switch(hfp_connection->parser_item_index){
1313                 case 0:
1314                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1315                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1316                     break;
1317                 case 1:
1318                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1319                     hfp_connection->bnip_type = value;
1320                     break;
1321                 default:
1322                     break;
1323             }
1324             // index > 2 are ignored in switch above
1325             hfp_connection->parser_item_index++;
1326             break;
1327         case HFP_CMD_LIST_CURRENT_CALLS:
1328             switch(hfp_connection->parser_item_index){
1329                 case 0:
1330                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1331                     hfp_connection->clcc_idx = value;
1332                     break;
1333                 case 1:
1334                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1335                     hfp_connection->clcc_dir = value;
1336                     break;
1337                 case 2:
1338                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1339                     hfp_connection->clcc_status = value;
1340                     break;
1341                 case 3:
1342                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1343                     hfp_connection->clcc_mode = value;
1344                     break;
1345                 case 4:
1346                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1347                     hfp_connection->clcc_mpty = value;
1348                     break;
1349                 case 5:
1350                     strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1351                     hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1352                     break;
1353                 case 6:
1354                     value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1355                     hfp_connection->bnip_type = value;
1356                     break;
1357                 default:
1358                     break;
1359             }
1360             // index > 6 are ignored in switch above
1361             hfp_connection->parser_item_index++;
1362             break;
1363         case HFP_CMD_SET_MICROPHONE_GAIN:
1364             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1365             hfp_connection->microphone_gain = value;
1366             log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value);
1367             break;
1368         case HFP_CMD_SET_SPEAKER_GAIN:
1369             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1370             hfp_connection->speaker_gain = value;
1371             log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value);
1372             break;
1373         case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION:
1374             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1375             hfp_connection->ag_activate_voice_recognition = value;
1376             log_info("hfp parse HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION %d\n", value);
1377             break;
1378         case HFP_CMD_TURN_OFF_EC_AND_NR:
1379             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1380             hfp_connection->ag_echo_and_noise_reduction = value;
1381             log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value);
1382             break;
1383         case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING:
1384             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1385             hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value);
1386             log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value);
1387             break;
1388         case HFP_CMD_HF_CONFIRMED_CODEC:
1389             hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer);
1390             log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed);
1391             break;
1392         case HFP_CMD_AG_SUGGESTED_CODEC:
1393             hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer);
1394             log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec);
1395             break;
1396         case HFP_CMD_SUPPORTED_FEATURES:
1397             hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer);
1398             log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features);
1399             break;
1400         case HFP_CMD_AVAILABLE_CODECS:
1401             log_info("Parsed codec %s\n", hfp_connection->line_buffer);
1402             hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1403             hfp_next_codec_index(hfp_connection);
1404             hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index;
1405             break;
1406         case HFP_CMD_RETRIEVE_AG_INDICATORS:
1407             strncpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name,  (char *)hfp_connection->line_buffer, HFP_MAX_INDICATOR_DESC_SIZE);
1408             hfp_connection->ag_indicators[hfp_connection->parser_item_index].name[HFP_MAX_INDICATOR_DESC_SIZE-1] = 0;
1409             hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1;
1410             log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer);
1411             break;
1412         case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS:
1413             log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer);
1414             hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer);
1415             hfp_next_indicators_index(hfp_connection);
1416             break;
1417         case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE:
1418             hfp_next_indicators_index(hfp_connection);
1419             if (hfp_connection->parser_item_index != 4) break;
1420             log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer);
1421             value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1422             hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value;
1423             break;
1424         case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES:
1425             log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer);
1426             if (hfp_connection->line_size > 2 ) break;
1427             memcpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE-1);
1428             hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name[HFP_CALL_SERVICE_SIZE - 1] = 0;
1429             hfp_next_remote_call_services_index(hfp_connection);
1430             break;
1431         case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS:
1432         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS:
1433             log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer);
1434             hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer);
1435             hfp_next_indicators_index(hfp_connection);
1436             hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index;
1437             break;
1438         case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE:
1439             // HF parses inital AG gen. ind. state
1440             log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer);
1441             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1442             break;
1443         case HFP_CMD_HF_INDICATOR_STATUS:
1444             hfp_connection->parser_indicator_index = hfp_parse_indicator_index(hfp_connection);
1445             log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index);
1446             break;
1447         case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE:
1448             // AG parses new gen. ind. state
1449             if (hfp_connection->ignore_value){
1450                 hfp_connection->ignore_value = 0;
1451                 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index,
1452                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled);
1453             }
1454             else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){
1455                 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n",
1456                     hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name);
1457             } else {
1458                 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1459                 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value;
1460                 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index,
1461                     hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value);
1462             }
1463             hfp_next_indicators_index(hfp_connection);
1464             break;
1465         case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS:
1466             // indicators are indexed starting with 1
1467             hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection);
1468             log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index);
1469             break;
1470         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME:
1471             hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1472             log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode);
1473             break;
1474         case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT:
1475             if (hfp_connection->line_buffer[0] == '3'){
1476                 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer);
1477                 break;
1478             }
1479             // TODO emit ERROR, wrong format
1480             log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer);
1481             break;
1482         case HFP_CMD_ERROR:
1483             break;
1484         case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR:
1485             hfp_connection->extended_audio_gateway_error = 1;
1486             hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1487             break;
1488         case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR:
1489             hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer);
1490             hfp_connection->ok_pending = 1;
1491             hfp_connection->extended_audio_gateway_error = 0;
1492             break;
1493         case HFP_CMD_AG_SENT_PHONE_NUMBER:
1494         case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE:
1495         case HFP_CMD_AG_SENT_CLIP_INFORMATION:
1496             strncpy(hfp_connection->bnip_number, (char *)hfp_connection->line_buffer, sizeof(hfp_connection->bnip_number));
1497             hfp_connection->bnip_number[sizeof(hfp_connection->bnip_number)-1] = 0;
1498             break;
1499         case HFP_CMD_CALL_HOLD:
1500             hfp_connection->ag_call_hold_action = hfp_connection->line_buffer[0] - '0';
1501             if (hfp_connection->line_buffer[1] != '\0'){
1502                 hfp_connection->call_index = btstack_atoi((char *)&hfp_connection->line_buffer[1]);
1503             }
1504             break;
1505         case HFP_CMD_RESPONSE_AND_HOLD_COMMAND:
1506             hfp_connection->ag_response_and_hold_action = btstack_atoi((char *)&hfp_connection->line_buffer[0]);
1507             break;
1508         case HFP_CMD_TRANSMIT_DTMF_CODES:
1509             hfp_connection->ag_dtmf_code = hfp_connection->line_buffer[0];
1510             break;
1511         case HFP_CMD_ENABLE_CLIP:
1512             hfp_connection->clip_enabled = hfp_connection->line_buffer[0] != '0';
1513             break;
1514         case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION:
1515             hfp_connection->call_waiting_notification_enabled = hfp_connection->line_buffer[0] != '0';
1516             break;
1517         default:
1518             break;
1519     }
1520 }
1521 
1522 static void hfp_handle_start_sdp_client_query(void * context){
1523     UNUSED(context);
1524 
1525     btstack_linked_list_iterator_t it;
1526     btstack_linked_list_iterator_init(&it, &hfp_connections);
1527     while (btstack_linked_list_iterator_has_next(&it)){
1528         hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it);
1529 
1530         if (connection->state != HFP_W2_SEND_SDP_QUERY) continue;
1531 
1532         connection->state = HFP_W4_SDP_QUERY_COMPLETE;
1533         sdp_query_context.local_role = connection->local_role;
1534         (void)memcpy(sdp_query_context.remote_address, connection->remote_addr, 6);
1535         sdp_client_query_rfcomm_channel_and_name_for_service_class_uuid(&handle_query_rfcomm_event, connection->remote_addr, connection->service_uuid);
1536         return;
1537     }
1538 }
1539 
1540 void hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){
1541     hfp_connection_t * hfp_connection = provide_hfp_connection_context_for_bd_addr(bd_addr, local_role);
1542     log_info("hfp_connect %s, hfp_connection %p", bd_addr_to_str(bd_addr), hfp_connection);
1543 
1544     if (!hfp_connection) {
1545         log_error("hfp_establish_service_level_connection for addr %s failed", bd_addr_to_str(bd_addr));
1546         return;
1547     }
1548     switch (hfp_connection->state){
1549         case HFP_W2_DISCONNECT_RFCOMM:
1550             hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED;
1551             return;
1552         case HFP_W4_RFCOMM_DISCONNECTED:
1553             hfp_connection->state = HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART;
1554             return;
1555         case HFP_IDLE:
1556             (void)memcpy(hfp_connection->remote_addr, bd_addr, 6);
1557             hfp_connection->state = HFP_W2_SEND_SDP_QUERY;
1558             hfp_connection->service_uuid = service_uuid;
1559 
1560             hfp_handle_sdp_client_query_request.callback = &hfp_handle_start_sdp_client_query;
1561             // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
1562             (void) sdp_client_register_query_callback(&hfp_handle_sdp_client_query_request);
1563             break;
1564         default:
1565             break;
1566     }
1567 }
1568 
1569 void hfp_release_service_level_connection(hfp_connection_t * hfp_connection){
1570     if (!hfp_connection) return;
1571     hfp_release_audio_connection(hfp_connection);
1572 
1573     if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){
1574         hfp_connection->state = HFP_IDLE;
1575         return;
1576     }
1577 
1578     if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){
1579         hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
1580         return;
1581     }
1582 
1583     if (hfp_connection->state < HFP_W4_SCO_CONNECTED){
1584         hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM;
1585         return;
1586     }
1587 
1588     if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){
1589         hfp_connection->state = HFP_W2_DISCONNECT_SCO;
1590         return;
1591     }
1592 
1593     // HFP_W4_SCO_DISCONNECTED or later
1594     hfp_connection->release_slc_connection = 1;
1595 }
1596 
1597 void hfp_release_audio_connection(hfp_connection_t * hfp_connection){
1598     if (!hfp_connection) return;
1599     if (hfp_connection->state >= HFP_W2_DISCONNECT_SCO) return;
1600     hfp_connection->release_audio_connection = 1;
1601 }
1602 
1603 static const struct link_settings {
1604     const uint16_t max_latency;
1605     const uint8_t  retransmission_effort;
1606     const uint16_t packet_types;
1607     const bool     eSCO;
1608     const uint8_t  codec;
1609 } hfp_link_settings [] = {
1610     { 0xffff, 0xff, SCO_PACKET_TYPES_HV1,  false, HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_D0
1611     { 0xffff, 0xff, SCO_PACKET_TYPES_HV3,  false, HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_D1
1612     { 0x0007, 0x01, SCO_PACKET_TYPES_EV3,  true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S1
1613     { 0x0007, 0x01, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S2
1614     { 0x000a, 0x01, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S3
1615     { 0x000c, 0x02, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_CVSD }, // HFP_LINK_SETTINGS_S4
1616     { 0x0008, 0x02, SCO_PACKET_TYPES_EV3,  true,  HFP_CODEC_MSBC }, // HFP_LINK_SETTINGS_T1
1617     { 0x000d, 0x02, SCO_PACKET_TYPES_2EV3, true,  HFP_CODEC_MSBC }  // HFP_LINK_SETTINGS_T2
1618 };
1619 
1620 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){
1621     // all packet types, fixed bandwidth
1622     int setting = hfp_connection->link_setting;
1623     log_info("hfp_setup_synchronous_connection using setting nr %u", setting);
1624     sco_establishment_active = hfp_connection;
1625     uint16_t sco_voice_setting = hci_get_sco_voice_setting();
1626     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1627 #ifdef ENABLE_BCM_PCM_WBS
1628         sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers
1629 #else
1630         sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise
1631 #endif
1632     }
1633     // get packet types - bits 6-9 are 'don't allow'
1634     uint16_t packet_types = hfp_link_settings[setting].packet_types ^ 0x03c0;
1635     hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency,
1636         sco_voice_setting, hfp_link_settings[setting].retransmission_effort, packet_types);
1637 }
1638 
1639 #ifdef ENABLE_CC256X_ASSISTED_HFP
1640 void hfp_cc256x_prepare_for_sco(hfp_connection_t * hfp_connection){
1641     hfp_connection->cc256x_send_write_codec_config = true;
1642     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1643         hfp_connection->cc256x_send_wbs_associate = true;
1644     }
1645 }
1646 
1647 void hfp_cc256x_write_codec_config(hfp_connection_t * hfp_connection){
1648     uint32_t sample_rate_hz;
1649     uint16_t clock_rate_khz;
1650     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1651         clock_rate_khz = 512;
1652         sample_rate_hz = 16000;
1653     } else {
1654         clock_rate_khz = 256;
1655         sample_rate_hz = 8000;
1656     }
1657     uint8_t clock_direction = 0;        // master
1658     uint16_t frame_sync_duty_cycle = 0; // i2s with 50%
1659     uint8_t  frame_sync_edge = 1;       // rising edge
1660     uint8_t  frame_sync_polarity = 0;   // active high
1661     uint8_t  reserved = 0;
1662     uint16_t size = 16;
1663     uint16_t chan_1_offset = 1;
1664     uint16_t chan_2_offset = chan_1_offset + size;
1665     uint8_t  out_edge = 1;              // rising
1666     uint8_t  in_edge = 0;               // falling
1667     hci_send_cmd(&hci_ti_write_codec_config, clock_rate_khz, clock_direction, sample_rate_hz, frame_sync_duty_cycle,
1668                  frame_sync_edge, frame_sync_polarity, reserved,
1669                  size, chan_1_offset, out_edge, size, chan_1_offset, in_edge, reserved,
1670                  size, chan_2_offset, out_edge, size, chan_2_offset, in_edge, reserved);
1671 }
1672 #endif
1673 
1674 #ifdef ENABLE_BCM_PCM_WBS
1675 void hfp_bcm_prepare_for_sco(hfp_connection_t * hfp_connection){
1676     hfp_connection->bcm_send_write_i2spcm_interface_param = true;
1677     if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){
1678         hfp_connection->bcm_send_enable_wbs = true;
1679     }
1680 }
1681 void hfp_bcm_write_i2spcm_interface_param(hfp_connection_t * hfp_connection){
1682     uint8_t sample_rate = (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? 1 : 0;
1683     // i2s enable, master, 8/16 kHz, 512 kHz
1684     hci_send_cmd(&hci_bcm_write_i2spcm_interface_paramhci_bcm_write_i2spcm_interface_param, 1, 1, sample_rate, 2);
1685 }
1686 #endif
1687 
1688 void hfp_set_hf_callback(btstack_packet_handler_t callback){
1689     hfp_hf_callback = callback;
1690 }
1691 
1692 void hfp_set_ag_callback(btstack_packet_handler_t callback){
1693     hfp_ag_callback = callback;
1694 }
1695 
1696 void hfp_set_ag_rfcomm_packet_handler(btstack_packet_handler_t handler){
1697     hfp_ag_rfcomm_packet_handler = handler;
1698 }
1699 
1700 void hfp_set_hf_rfcomm_packet_handler(btstack_packet_handler_t handler){
1701     hfp_hf_rfcomm_packet_handler = handler;
1702 }
1703 
1704 void hfp_init(void){
1705     hfp_allowed_sco_packet_types = SCO_PACKET_TYPES_ALL;
1706 }
1707 
1708 void hfp_deinit(void){
1709     hfp_connections = NULL;
1710     hfp_hf_callback = NULL;
1711     hfp_ag_callback = NULL;
1712     hfp_hf_rfcomm_packet_handler = NULL;
1713     hfp_ag_rfcomm_packet_handler = NULL;
1714     sco_establishment_active = NULL;
1715     (void) memset(&sdp_query_context, 0, sizeof(hfp_sdp_query_context_t));
1716     (void) memset(&hfp_handle_sdp_client_query_request, 0, sizeof(btstack_context_callback_registration_t));
1717 }
1718 
1719 void hfp_set_sco_packet_types(uint16_t packet_types){
1720     hfp_allowed_sco_packet_types = packet_types;
1721 }
1722 
1723 uint16_t hfp_get_sco_packet_types(void){
1724     return hfp_allowed_sco_packet_types;
1725 }
1726 
1727 hfp_link_settings_t hfp_next_link_setting(hfp_link_settings_t current_setting, bool local_eSCO_supported, bool remote_eSCO_supported, bool eSCO_S4_supported, uint8_t negotiated_codec){
1728     int8_t setting = (int8_t) current_setting;
1729     bool can_use_eSCO = local_eSCO_supported && remote_eSCO_supported;
1730     while (setting > 0){
1731         setting--;
1732         // skip if eSCO required but not available
1733         if (hfp_link_settings[setting].eSCO && !can_use_eSCO) continue;
1734         // skip if S4 but not supported
1735         if ((setting == (int8_t) HFP_LINK_SETTINGS_S4) && !eSCO_S4_supported) continue;
1736         // skip wrong codec
1737         if ( hfp_link_settings[setting].codec != negotiated_codec) continue;
1738         // skip disabled packet types
1739         uint16_t required_packet_types = hfp_link_settings[setting].packet_types;
1740         uint16_t allowed_packet_types  = hfp_allowed_sco_packet_types;
1741         if ((required_packet_types & allowed_packet_types) == 0) continue;
1742 
1743         // found matching setting
1744         return (hfp_link_settings_t) setting;
1745     }
1746     return HFP_LINK_SETTINGS_NONE;
1747 }
1748 
1749 static hfp_link_settings_t hfp_next_link_setting_for_connection(hfp_link_settings_t current_setting, hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported){
1750     bool local_eSCO_supported  = hci_extended_sco_link_supported();
1751     bool remote_eSCO_supported = hci_remote_esco_supported(hfp_connection->acl_handle);
1752     uint8_t negotiated_codec   = hfp_connection->negotiated_codec;
1753     return  hfp_next_link_setting(current_setting, local_eSCO_supported, remote_eSCO_supported, eSCO_S4_supported, negotiated_codec);
1754 }
1755 
1756 void hfp_init_link_settings(hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported){
1757     // get highest possible link setting
1758     hfp_connection->link_setting = hfp_next_link_setting_for_connection(HFP_LINK_SETTINGS_NONE, hfp_connection, eSCO_S4_supported);
1759     log_info("hfp_init_link_settings: %u", hfp_connection->link_setting);
1760 }
1761 
1762 #define HFP_HF_RX_DEBUG_PRINT_LINE 80
1763 
1764 void hfp_log_rfcomm_message(const char * tag, uint8_t * packet, uint16_t size){
1765 #ifdef ENABLE_LOG_INFO
1766     // encode \n\r
1767     char printable[HFP_HF_RX_DEBUG_PRINT_LINE+2];
1768     int i = 0;
1769     int pos;
1770     for (pos=0 ; (pos < size) && (i < (HFP_HF_RX_DEBUG_PRINT_LINE - 3)) ; pos++){
1771         switch (packet[pos]){
1772             case '\n':
1773                 printable[i++] = '\\';
1774                 printable[i++] = 'n';
1775                 break;
1776             case '\r':
1777                 printable[i++] = '\\';
1778                 printable[i++] = 'r';
1779                 break;
1780             default:
1781                 printable[i++] = packet[pos];
1782                 break;
1783         }
1784     }
1785     printable[i] = 0;
1786     log_info("%s: '%s'", tag, printable);
1787 #endif
1788 }
1789