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 BLUEKITCHEN 24 * GMBH 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 <stdio.h> 45 #include <string.h> 46 #include <inttypes.h> 47 48 #include "bluetooth_sdp.h" 49 #include "btstack_debug.h" 50 #include "btstack_event.h" 51 #include "btstack_memory.h" 52 #include "btstack_run_loop.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 61 #if defined(ENABLE_CC256X_ASSISTED_HFP) && !defined(ENABLE_SCO_OVER_PCM) 62 #error "Assisted HFP is only possible over PCM/I2S. Please add define: ENABLE_SCO_OVER_PCM" 63 #endif 64 65 #if defined(ENABLE_BCM_PCM_WBS) && !defined(ENABLE_SCO_OVER_PCM) 66 #error "WBS for PCM is only possible over PCM/I2S. Please add define: ENABLE_SCO_OVER_PCM" 67 #endif 68 69 #define HFP_HF_FEATURES_SIZE 10 70 #define HFP_AG_FEATURES_SIZE 12 71 72 typedef struct { 73 hfp_role_t local_role; 74 bd_addr_t remote_address; 75 } hfp_sdp_query_context_t; 76 77 // globals 78 79 static btstack_linked_list_t hfp_connections ; 80 81 static btstack_packet_handler_t hfp_hf_callback; 82 static btstack_packet_handler_t hfp_ag_callback; 83 84 static btstack_packet_handler_t hfp_hf_rfcomm_packet_handler; 85 static btstack_packet_handler_t hfp_ag_rfcomm_packet_handler; 86 87 static uint16_t hfp_allowed_sco_packet_types; 88 static hfp_connection_t * hfp_sco_establishment_active; 89 90 static hfp_sdp_query_context_t hfp_sdp_query_context; 91 static btstack_context_callback_registration_t hfp_sdp_query_request; 92 93 94 95 96 97 // custom commands 98 static btstack_linked_list_t hfp_custom_commands_ag; 99 static btstack_linked_list_t hfp_custom_commands_hf; 100 101 // prototypes 102 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); 103 static void parse_sequence(hfp_connection_t * context); 104 105 106 #define CODEC_MASK_CVSD (1 << HFP_CODEC_CVSD) 107 #define CODEC_MASK_OTHER ((1 << HFP_CODEC_MSBC) | (1 << HFP_CODEC_LC3_SWB)) 108 109 static const struct { 110 const uint16_t max_latency; 111 const uint8_t retransmission_effort; 112 const uint16_t packet_types; 113 const uint8_t codec_mask; 114 } hfp_link_settings [] = { 115 {0x0004, 0xff, SCO_PACKET_TYPES_HV1, CODEC_MASK_CVSD }, // HFP_LINK_SETTINGS_D0 116 {0x0005, 0xff, SCO_PACKET_TYPES_HV3, CODEC_MASK_CVSD }, // HFP_LINK_SETTINGS_D1 117 {0x0007, 0x01, SCO_PACKET_TYPES_EV3, CODEC_MASK_CVSD }, // HFP_LINK_SETTINGS_S1 118 {0x0007, 0x01, SCO_PACKET_TYPES_2EV3, CODEC_MASK_CVSD }, // HFP_LINK_SETTINGS_S2 119 {0x000a, 0x01, SCO_PACKET_TYPES_2EV3, CODEC_MASK_CVSD }, // HFP_LINK_SETTINGS_S3 120 {0x000c, 0x02, SCO_PACKET_TYPES_2EV3, CODEC_MASK_CVSD }, // HFP_LINK_SETTINGS_S4 121 {0x0008, 0x02, SCO_PACKET_TYPES_EV3, CODEC_MASK_OTHER}, // HFP_LINK_SETTINGS_T1 122 {0x000d, 0x02, SCO_PACKET_TYPES_2EV3, CODEC_MASK_OTHER} // HFP_LINK_SETTINGS_T2 123 }; 124 125 #ifdef ENABLE_HFP_HF_SAFE_SETTINGS 126 // HFP v1.9, table 6.10 'mandatory safe settings' for eSCO + similar entries for SCO 127 static const struct hfp_mandatory_safe_setting { 128 const uint8_t codec_mask; 129 const bool secure_connection_in_use; 130 hfp_link_settings_t link_setting; 131 } hfp_mandatory_safe_settings[] = { 132 { CODEC_MASK_CVSD, false, HFP_LINK_SETTINGS_D1}, 133 { CODEC_MASK_CVSD, true, HFP_LINK_SETTINGS_D1}, 134 { CODEC_MASK_CVSD, false, HFP_LINK_SETTINGS_S1}, 135 { CODEC_MASK_CVSD, true, HFP_LINK_SETTINGS_S4}, 136 { CODEC_MASK_OTHER, false, HFP_LINK_SETTINGS_T1}, 137 { CODEC_MASK_OTHER, true, HFP_LINK_SETTINGS_T2}, 138 }; 139 #endif 140 141 static const char * hfp_hf_features[] = { 142 "EC and/or NR function", 143 "Three-way calling", 144 "CLI presentation capability", 145 "Voice recognition activation", 146 "Remote volume control", 147 148 "Enhanced call status", 149 "Enhanced call control", 150 151 "Codec negotiation", 152 153 "HF Indicators", 154 "eSCO S4 (and T2) Settings Supported", 155 "Reserved for future definition" 156 }; 157 158 static const char * hfp_ag_features[] = { 159 "Three-way calling", 160 "EC and/or NR function", 161 "Voice recognition function", 162 "In-band ring tone capability", 163 "Attach a number to a voice tag", 164 "Ability to reject a call", 165 "Enhanced call status", 166 "Enhanced call control", 167 "Extended Error Result Codes", 168 "Codec negotiation", 169 "HF Indicators", 170 "eSCO S4 (and T2) Settings Supported", 171 "Reserved for future definition" 172 }; 173 174 static const char * hfp_enhanced_call_dir[] = { 175 "outgoing", 176 "incoming" 177 }; 178 179 static const char * hfp_enhanced_call_status[] = { 180 "active", 181 "held", 182 "outgoing dialing", 183 "outgoing alerting", 184 "incoming", 185 "incoming waiting", 186 "call held by response and hold" 187 }; 188 189 static const char * hfp_enhanced_call_mode[] = { 190 "voice", 191 "data", 192 "fax" 193 }; 194 195 static const char * hfp_enhanced_call_mpty[] = { 196 "not a conference call", 197 "conference call" 198 }; 199 200 const char * hfp_enhanced_call_dir2str(uint16_t index){ 201 if (index <= HFP_ENHANCED_CALL_DIR_INCOMING) return hfp_enhanced_call_dir[index]; 202 return "not defined"; 203 } 204 205 const char * hfp_enhanced_call_status2str(uint16_t index){ 206 if (index <= HFP_ENHANCED_CALL_STATUS_CALL_HELD_BY_RESPONSE_AND_HOLD) return hfp_enhanced_call_status[index]; 207 return "not defined"; 208 } 209 210 const char * hfp_enhanced_call_mode2str(uint16_t index){ 211 if (index <= HFP_ENHANCED_CALL_MODE_FAX) return hfp_enhanced_call_mode[index]; 212 return "not defined"; 213 } 214 215 const char * hfp_enhanced_call_mpty2str(uint16_t index){ 216 if (index <= HFP_ENHANCED_CALL_MPTY_CONFERENCE_CALL) return hfp_enhanced_call_mpty[index]; 217 return "not defined"; 218 } 219 220 static uint16_t hfp_parse_indicator_index(hfp_connection_t * hfp_connection){ 221 uint16_t index = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 222 223 if (index > HFP_MAX_NUM_INDICATORS){ 224 log_info("ignoring invalid indicator index bigger then HFP_MAX_NUM_INDICATORS"); 225 return HFP_MAX_NUM_INDICATORS - 1; 226 } 227 228 // indicator index enumeration starts with 1, we substract 1 to store in array with starting index 0 229 if (index > 0){ 230 index -= 1; 231 } else { 232 log_info("ignoring invalid indicator index 0"); 233 return 0; 234 } 235 return index; 236 } 237 238 static void hfp_next_indicators_index(hfp_connection_t * hfp_connection){ 239 if (hfp_connection->parser_item_index < HFP_MAX_NUM_INDICATORS - 1){ 240 hfp_connection->parser_item_index++; 241 } else { 242 log_info("Ignoring additional indicator"); 243 } 244 } 245 246 static void hfp_next_codec_index(hfp_connection_t * hfp_connection){ 247 if (hfp_connection->parser_item_index < HFP_MAX_NUM_CODECS - 1){ 248 hfp_connection->parser_item_index++; 249 } else { 250 log_info("Ignoring additional codec index"); 251 } 252 } 253 254 static void hfp_next_remote_call_services_index(hfp_connection_t * hfp_connection){ 255 if (hfp_connection->remote_call_services_index < HFP_MAX_NUM_CALL_SERVICES - 1){ 256 hfp_connection->remote_call_services_index++; 257 } else { 258 log_info("Ignoring additional remote_call_services"); 259 } 260 } 261 262 const char * hfp_hf_feature(int index){ 263 if (index > HFP_HF_FEATURES_SIZE){ 264 return hfp_hf_features[HFP_HF_FEATURES_SIZE]; 265 } 266 return hfp_hf_features[index]; 267 } 268 269 const char * hfp_ag_feature(int index){ 270 if (index > HFP_AG_FEATURES_SIZE){ 271 return hfp_ag_features[HFP_AG_FEATURES_SIZE]; 272 } 273 return hfp_ag_features[index]; 274 } 275 276 int send_str_over_rfcomm(uint16_t cid, const char * command){ 277 if (!rfcomm_can_send_packet_now(cid)) return 1; 278 log_info("HFP_TX %s", command); 279 int err = rfcomm_send(cid, (uint8_t*) command, (uint16_t) strlen(command)); 280 if (err){ 281 log_error("rfcomm_send -> error 0x%02x \n", err); 282 } 283 #ifdef ENABLE_HFP_AT_MESSAGES 284 hfp_connection_t * hfp_connection = get_hfp_connection_context_for_rfcomm_cid(cid); 285 hfp_emit_string_event(hfp_connection, HFP_SUBEVENT_AT_MESSAGE_SENT, command); 286 #endif 287 return 1; 288 } 289 290 int hfp_supports_codec(uint8_t codec, int codecs_nr, uint8_t * codecs){ 291 292 // mSBC requires support for eSCO connections 293 if ((codec == HFP_CODEC_MSBC) && !hci_extended_sco_link_supported()) return 0; 294 295 int i; 296 for (i = 0; i < codecs_nr; i++){ 297 if (codecs[i] != codec) continue; 298 return 1; 299 } 300 return 0; 301 } 302 303 void hfp_hf_drop_mSBC_if_eSCO_not_supported(uint8_t * codecs, uint8_t * codecs_nr){ 304 if (hci_extended_sco_link_supported()) return; 305 uint8_t i; 306 int filtered_codec_count = 0; 307 for (i=0; i < *codecs_nr; i++){ 308 if (codecs[i] != HFP_CODEC_MSBC) { 309 codecs[filtered_codec_count++] = codecs[i]; 310 } 311 } 312 *codecs_nr = filtered_codec_count; 313 } 314 315 // UTILS 316 int get_bit(uint16_t bitmap, int position){ 317 return (bitmap >> position) & 1; 318 } 319 320 int store_bit(uint32_t bitmap, int position, uint8_t value){ 321 if (value){ 322 bitmap |= 1 << position; 323 } else { 324 bitmap &= ~ (1 << position); 325 } 326 return bitmap; 327 } 328 329 int join(char * buffer, int buffer_size, uint8_t * values, int values_nr){ 330 if (buffer_size < (values_nr * 3)) return 0; 331 int i; 332 int offset = 0; 333 for (i = 0; i < (values_nr-1); i++) { 334 offset += snprintf(buffer+offset, buffer_size-offset, "%d,", values[i]); // puts string into buffer 335 } 336 if (i<values_nr){ 337 offset += snprintf(buffer+offset, buffer_size-offset, "%d", values[i]); 338 } 339 return offset; 340 } 341 342 int join_bitmap(char * buffer, int buffer_size, uint32_t values, int values_nr){ 343 if (buffer_size < (values_nr * 3)) return 0; 344 345 int i; 346 int offset = 0; 347 for (i = 0; i < (values_nr-1); i++) { 348 offset += snprintf(buffer+offset, buffer_size-offset, "%d,", get_bit(values,i)); // puts string into buffer 349 } 350 351 if (i<values_nr){ 352 offset += snprintf(buffer+offset, buffer_size-offset, "%d", get_bit(values,i)); 353 } 354 return offset; 355 } 356 static void hfp_emit_event_for_role(hfp_role_t local_role, uint8_t * packet, uint16_t size){ 357 switch (local_role){ 358 case HFP_ROLE_HF: 359 (*hfp_hf_callback)(HCI_EVENT_PACKET, 0, packet, size); 360 break; 361 case HFP_ROLE_AG: 362 (*hfp_ag_callback)(HCI_EVENT_PACKET, 0, packet, size); 363 break; 364 default: 365 btstack_unreachable(); 366 break; 367 } 368 } 369 370 static void hfp_emit_event_for_context(hfp_connection_t * hfp_connection, uint8_t * packet, uint16_t size){ 371 if (!hfp_connection) return; 372 hfp_emit_event_for_role(hfp_connection->local_role, packet, size); 373 } 374 375 void hfp_emit_simple_event(hfp_connection_t * hfp_connection, uint8_t event_subtype){ 376 hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID; 377 uint8_t event[5]; 378 event[0] = HCI_EVENT_HFP_META; 379 event[1] = sizeof(event) - 2; 380 event[2] = event_subtype; 381 little_endian_store_16(event, 3, acl_handle); 382 hfp_emit_event_for_context(hfp_connection, event, sizeof(event)); 383 } 384 385 void hfp_emit_event(hfp_connection_t * hfp_connection, uint8_t event_subtype, uint8_t value){ 386 hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID; 387 uint8_t event[6]; 388 event[0] = HCI_EVENT_HFP_META; 389 event[1] = sizeof(event) - 2; 390 event[2] = event_subtype; 391 little_endian_store_16(event, 3, acl_handle); 392 event[5] = value; // status 0 == OK 393 hfp_emit_event_for_context(hfp_connection, event, sizeof(event)); 394 } 395 396 void hfp_emit_voice_recognition_enabled(hfp_connection_t * hfp_connection, uint8_t status){ 397 btstack_assert(hfp_connection != NULL); 398 399 uint8_t event[7]; 400 event[0] = HCI_EVENT_HFP_META; 401 event[1] = sizeof(event) - 2; 402 event[2] = HFP_SUBEVENT_VOICE_RECOGNITION_ACTIVATED; 403 404 little_endian_store_16(event, 3, hfp_connection->acl_handle); 405 event[5] = status; // 0:success 406 event[6] = hfp_connection->enhanced_voice_recognition_enabled ? 1 : 0; 407 hfp_emit_event_for_context(hfp_connection, event, sizeof(event)); 408 } 409 410 void hfp_emit_voice_recognition_disabled(hfp_connection_t * hfp_connection, uint8_t status){ 411 btstack_assert(hfp_connection != NULL); 412 413 uint8_t event[6]; 414 event[0] = HCI_EVENT_HFP_META; 415 event[1] = sizeof(event) - 2; 416 event[2] = HFP_SUBEVENT_VOICE_RECOGNITION_DEACTIVATED; 417 418 little_endian_store_16(event, 3, hfp_connection->acl_handle); 419 event[5] = status; // 0:success 420 hfp_emit_event_for_context(hfp_connection, event, sizeof(event)); 421 } 422 423 void hfp_emit_enhanced_voice_recognition_hf_ready_for_audio_event(hfp_connection_t * hfp_connection, uint8_t status){ 424 hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID; 425 426 uint8_t event[6]; 427 event[0] = HCI_EVENT_HFP_META; 428 event[1] = sizeof(event) - 2; 429 event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_HF_READY_FOR_AUDIO; 430 little_endian_store_16(event, 3, acl_handle); 431 event[5] = status; 432 hfp_emit_event_for_context(hfp_connection, event, sizeof(event)); 433 } 434 435 void hfp_emit_enhanced_voice_recognition_state_event(hfp_connection_t * hfp_connection, uint8_t status){ 436 hci_con_handle_t acl_handle = (hfp_connection != NULL) ? hfp_connection->acl_handle : HCI_CON_HANDLE_INVALID; 437 438 uint8_t event[6]; 439 event[0] = HCI_EVENT_HFP_META; 440 event[1] = sizeof(event) - 2; 441 switch (hfp_connection->ag_vra_state){ 442 case HFP_VOICE_RECOGNITION_STATE_AG_READY_TO_ACCEPT_AUDIO_INPUT: 443 event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_AG_READY_TO_ACCEPT_AUDIO_INPUT; 444 break; 445 case HFP_VOICE_RECOGNITION_STATE_AG_IS_STARTING_SOUND: 446 event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_AG_IS_STARTING_SOUND; 447 break; 448 case HFP_VOICE_RECOGNITION_STATE_AG_IS_PROCESSING_AUDIO_INPUT: 449 event[2] = HFP_SUBEVENT_ENHANCED_VOICE_RECOGNITION_AG_IS_PROCESSING_AUDIO_INPUT; 450 break; 451 default: 452 btstack_unreachable(); 453 break; 454 } 455 456 little_endian_store_16(event, 3, acl_handle); 457 event[5] = status; 458 hfp_emit_event_for_context(hfp_connection, event, sizeof(event)); 459 } 460 461 void hfp_emit_slc_connection_event(hfp_role_t local_role, uint8_t status, hci_con_handle_t con_handle, bd_addr_t addr){ 462 uint8_t event[12]; 463 int pos = 0; 464 event[pos++] = HCI_EVENT_HFP_META; 465 event[pos++] = sizeof(event) - 2; 466 event[pos++] = HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_ESTABLISHED; 467 little_endian_store_16(event, pos, con_handle); 468 pos += 2; 469 event[pos++] = status; // status 0 == OK 470 reverse_bd_addr(addr,&event[pos]); 471 pos += 6; 472 hfp_emit_event_for_role(local_role, event, sizeof(event)); 473 } 474 475 static void hfp_emit_audio_connection_released(hfp_connection_t * hfp_connection, hci_con_handle_t sco_handle){ 476 btstack_assert(hfp_connection != NULL); 477 uint8_t event[7]; 478 int pos = 0; 479 event[pos++] = HCI_EVENT_HFP_META; 480 event[pos++] = sizeof(event) - 2; 481 event[pos++] = HFP_SUBEVENT_AUDIO_CONNECTION_RELEASED; 482 little_endian_store_16(event, pos, hfp_connection->acl_handle); 483 pos += 2; 484 little_endian_store_16(event, pos, sco_handle); 485 pos += 2; 486 hfp_emit_event_for_context(hfp_connection, event, sizeof(event)); 487 } 488 489 void hfp_emit_sco_connection_established(hfp_connection_t *hfp_connection, uint8_t status, uint8_t negotiated_codec, 490 uint16_t rx_packet_length, uint16_t tx_packet_length) { 491 btstack_assert(hfp_connection != NULL); 492 uint8_t event[21]; 493 int pos = 0; 494 event[pos++] = HCI_EVENT_HFP_META; 495 event[pos++] = sizeof(event) - 2; 496 event[pos++] = HFP_SUBEVENT_AUDIO_CONNECTION_ESTABLISHED; 497 little_endian_store_16(event, pos, hfp_connection->acl_handle); 498 pos += 2; 499 event[pos++] = status; // status 0 == OK 500 little_endian_store_16(event, pos, hfp_connection->sco_handle); 501 pos += 2; 502 reverse_bd_addr(hfp_connection->remote_addr,&event[pos]); 503 pos += 6; 504 event[pos++] = negotiated_codec; 505 little_endian_store_16(event, pos, hfp_connection->packet_types); 506 pos += 2; 507 little_endian_store_16(event, pos, rx_packet_length); 508 pos += 2; 509 little_endian_store_16(event, pos, tx_packet_length); 510 pos += 2; 511 hfp_emit_event_for_context(hfp_connection, event, sizeof(event)); 512 } 513 514 void hfp_emit_string_event(hfp_connection_t * hfp_connection, uint8_t event_subtype, const char * value){ 515 btstack_assert(hfp_connection != NULL); 516 #ifdef ENABLE_HFP_AT_MESSAGES 517 uint8_t event[256]; 518 #else 519 uint8_t event[40]; 520 #endif 521 uint16_t string_len = btstack_min((uint16_t) strlen(value), sizeof(event) - 6); 522 event[0] = HCI_EVENT_HFP_META; 523 event[1] = 4 + string_len; 524 event[2] = event_subtype; 525 little_endian_store_16(event, 3, hfp_connection->acl_handle); 526 memcpy((char*)&event[5], value, string_len); 527 event[5 + string_len] = 0; 528 hfp_emit_event_for_context(hfp_connection, event, 6 + string_len); 529 } 530 531 btstack_linked_list_t * hfp_get_connections(void){ 532 return (btstack_linked_list_t *) &hfp_connections; 533 } 534 535 hfp_connection_t * get_hfp_connection_context_for_rfcomm_cid(uint16_t cid){ 536 btstack_linked_list_iterator_t it; 537 btstack_linked_list_iterator_init(&it, hfp_get_connections()); 538 while (btstack_linked_list_iterator_has_next(&it)){ 539 hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it); 540 if (hfp_connection->rfcomm_cid == cid){ 541 return hfp_connection; 542 } 543 } 544 return NULL; 545 } 546 547 hfp_connection_t * get_hfp_connection_context_for_bd_addr(bd_addr_t bd_addr, hfp_role_t hfp_role){ 548 btstack_linked_list_iterator_t it; 549 btstack_linked_list_iterator_init(&it, hfp_get_connections()); 550 while (btstack_linked_list_iterator_has_next(&it)){ 551 hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it); 552 if ((memcmp(hfp_connection->remote_addr, bd_addr, 6) == 0) && (hfp_connection->local_role == hfp_role)) { 553 return hfp_connection; 554 } 555 } 556 return NULL; 557 } 558 559 hfp_connection_t * get_hfp_connection_context_for_sco_handle(uint16_t handle, hfp_role_t hfp_role){ 560 btstack_linked_list_iterator_t it; 561 btstack_linked_list_iterator_init(&it, hfp_get_connections()); 562 while (btstack_linked_list_iterator_has_next(&it)){ 563 hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it); 564 if ((hfp_connection->sco_handle == handle) && (hfp_connection->local_role == hfp_role)){ 565 return hfp_connection; 566 } 567 } 568 return NULL; 569 } 570 571 hfp_connection_t * get_hfp_connection_context_for_acl_handle(uint16_t handle, hfp_role_t hfp_role){ 572 btstack_linked_list_iterator_t it; 573 btstack_linked_list_iterator_init(&it, hfp_get_connections()); 574 while (btstack_linked_list_iterator_has_next(&it)){ 575 hfp_connection_t * hfp_connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it); 576 if ((hfp_connection->acl_handle == handle) && (hfp_connection->local_role == hfp_role)){ 577 return hfp_connection; 578 } 579 } 580 return NULL; 581 } 582 583 584 static void hfp_reset_voice_recognition(hfp_connection_t * hfp_connection){ 585 btstack_assert(hfp_connection != NULL); 586 hfp_voice_recognition_activation_status_t current_vra_state = hfp_connection->vra_state; 587 hfp_connection->vra_state = HFP_VRA_VOICE_RECOGNITION_OFF; 588 589 if (current_vra_state != HFP_VRA_VOICE_RECOGNITION_OFF){ 590 hfp_emit_voice_recognition_disabled(hfp_connection, ERROR_CODE_SUCCESS); 591 } else if (hfp_connection->vra_state_requested != HFP_VRA_VOICE_RECOGNITION_OFF){ 592 hfp_emit_voice_recognition_disabled(hfp_connection, ERROR_CODE_SUCCESS); 593 } 594 595 hfp_connection->vra_state_requested = HFP_VRA_VOICE_RECOGNITION_OFF; 596 hfp_connection->activate_voice_recognition = false; 597 hfp_connection->deactivate_voice_recognition = false; 598 hfp_connection->enhanced_voice_recognition_enabled = false; 599 hfp_connection->ag_vra_status = 0; 600 hfp_connection->ag_vra_state = HFP_VOICE_RECOGNITION_STATE_AG_READY; 601 } 602 603 void hfp_reset_context_flags(hfp_connection_t * hfp_connection){ 604 if (!hfp_connection) return; 605 hfp_connection->ok_pending = 0; 606 hfp_connection->send_error = 0; 607 608 hfp_connection->found_equal_sign = false; 609 610 hfp_connection->change_status_update_for_individual_ag_indicators = 0; 611 hfp_connection->operator_name_changed = 0; 612 613 hfp_connection->enable_extended_audio_gateway_error_report = 0; 614 hfp_connection->extended_audio_gateway_error = 0; 615 616 // establish codecs hfp_connection 617 hfp_connection->suggested_codec = 0; 618 hfp_connection->negotiated_codec = 0; 619 hfp_connection->codec_confirmed = 0; 620 621 hfp_connection->establish_audio_connection = 0; 622 hfp_connection->call_waiting_notification_enabled = 0; 623 hfp_connection->command = HFP_CMD_NONE; 624 hfp_connection->enable_status_update_for_ag_indicators = 0xFF; 625 hfp_connection->clip_have_alpha = false; 626 hfp_reset_voice_recognition(hfp_connection); 627 } 628 629 static hfp_connection_t * create_hfp_connection_context(void){ 630 hfp_connection_t * hfp_connection = btstack_memory_hfp_connection_get(); 631 if (!hfp_connection) return NULL; 632 633 hfp_connection->state = HFP_IDLE; 634 hfp_connection->call_state = HFP_CALL_IDLE; 635 hfp_connection->codecs_state = HFP_CODECS_IDLE; 636 637 hfp_connection->parser_state = HFP_PARSER_CMD_HEADER; 638 639 hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID; 640 hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID; 641 642 hfp_reset_context_flags(hfp_connection); 643 644 btstack_linked_list_add(&hfp_connections, (btstack_linked_item_t*)hfp_connection); 645 return hfp_connection; 646 } 647 648 void hfp_finalize_connection_context(hfp_connection_t * hfp_connection){ 649 btstack_linked_list_remove(&hfp_connections, (btstack_linked_item_t*) hfp_connection); 650 btstack_memory_hfp_connection_free(hfp_connection); 651 } 652 653 static hfp_connection_t * hfp_create_connection(bd_addr_t bd_addr, hfp_role_t local_role){ 654 hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(bd_addr, local_role); 655 if (hfp_connection) return hfp_connection; 656 hfp_connection = create_hfp_connection_context(); 657 if (!hfp_connection) { 658 return NULL; 659 } 660 (void)memcpy(hfp_connection->remote_addr, bd_addr, 6); 661 hfp_connection->local_role = local_role; 662 log_info("Create HFP context %p: role %u, addr %s", hfp_connection, local_role, bd_addr_to_str(bd_addr)); 663 664 #ifdef ENABLE_NXP_PCM_WBS 665 hfp_connection->nxp_start_audio_handle = HCI_CON_HANDLE_INVALID; 666 hfp_connection->nxp_stop_audio_handle = HCI_CON_HANDLE_INVALID; 667 #endif 668 669 return hfp_connection; 670 } 671 672 /* @param network. 673 * 0 == no ability to reject a call. 674 * 1 == ability to reject a call. 675 */ 676 677 /* @param suported_features 678 * HF bit 0: EC and/or NR function (yes/no, 1 = yes, 0 = no) 679 * HF bit 1: Call waiting or three-way calling(yes/no, 1 = yes, 0 = no) 680 * HF bit 2: CLI presentation capability (yes/no, 1 = yes, 0 = no) 681 * HF bit 3: Voice recognition activation (yes/no, 1= yes, 0 = no) 682 * HF bit 4: Remote volume control (yes/no, 1 = yes, 0 = no) 683 * HF bit 5: Wide band speech (yes/no, 1 = yes, 0 = no) 684 */ 685 /* Bit position: 686 * AG bit 0: Three-way calling (yes/no, 1 = yes, 0 = no) 687 * AG bit 1: EC and/or NR function (yes/no, 1 = yes, 0 = no) 688 * AG bit 2: Voice recognition function (yes/no, 1 = yes, 0 = no) 689 * AG bit 3: In-band ring tone capability (yes/no, 1 = yes, 0 = no) 690 * AG bit 4: Attach a phone number to a voice tag (yes/no, 1 = yes, 0 = no) 691 * AG bit 5: Wide band speech (yes/no, 1 = yes, 0 = no) 692 */ 693 694 void hfp_create_sdp_record(uint8_t * service, uint32_t service_record_handle, uint16_t service_uuid, int rfcomm_channel_nr, const char * name){ 695 uint8_t* attribute; 696 de_create_sequence(service); 697 698 // 0x0000 "Service Record Handle" 699 de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE); 700 de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle); 701 702 // 0x0001 "Service Class ID List" 703 de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST); 704 attribute = de_push_sequence(service); 705 { 706 // "UUID for Service" 707 de_add_number(attribute, DE_UUID, DE_SIZE_16, service_uuid); 708 de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_GENERIC_AUDIO); 709 } 710 de_pop_sequence(service, attribute); 711 712 // 0x0004 "Protocol Descriptor List" 713 de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST); 714 attribute = de_push_sequence(service); 715 { 716 uint8_t* l2cpProtocol = de_push_sequence(attribute); 717 { 718 de_add_number(l2cpProtocol, DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP); 719 } 720 de_pop_sequence(attribute, l2cpProtocol); 721 722 uint8_t* rfcomm = de_push_sequence(attribute); 723 { 724 de_add_number(rfcomm, DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_RFCOMM); // rfcomm_service 725 de_add_number(rfcomm, DE_UINT, DE_SIZE_8, rfcomm_channel_nr); // rfcomm channel 726 } 727 de_pop_sequence(attribute, rfcomm); 728 } 729 de_pop_sequence(service, attribute); 730 731 732 // 0x0005 "Public Browse Group" 733 de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group 734 attribute = de_push_sequence(service); 735 { 736 de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT); 737 } 738 de_pop_sequence(service, attribute); 739 740 // 0x0009 "Bluetooth Profile Descriptor List" 741 de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST); 742 attribute = de_push_sequence(service); 743 { 744 uint8_t *sppProfile = de_push_sequence(attribute); 745 { 746 de_add_number(sppProfile, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HANDSFREE); 747 de_add_number(sppProfile, DE_UINT, DE_SIZE_16, 0x0109); // Version 1.9 748 } 749 de_pop_sequence(attribute, sppProfile); 750 } 751 de_pop_sequence(service, attribute); 752 753 // 0x0100 "Service Name" 754 if (strlen(name) > 0){ 755 de_add_number(service, DE_UINT, DE_SIZE_16, 0x0100); 756 de_add_data(service, DE_STRING, (uint16_t) strlen(name), (uint8_t *) name); 757 } 758 } 759 760 static void hfp_handle_slc_setup_error(hfp_connection_t * hfp_connection, uint8_t status){ 761 // cache fields for event 762 hfp_role_t local_role = hfp_connection->local_role; 763 bd_addr_t remote_addr; 764 // cppcheck-suppress uninitvar ; remote_addr is reported as uninitialized although it's the destination of the memcpy 765 (void)memcpy(remote_addr, hfp_connection->remote_addr, 6); 766 // finalize connection struct 767 hfp_finalize_connection_context(hfp_connection); 768 // emit event 769 hfp_emit_slc_connection_event(local_role, status, HCI_CON_HANDLE_INVALID, remote_addr); 770 } 771 772 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 773 UNUSED(packet_type); // ok: handling own sdp events 774 UNUSED(channel); // ok: no channel 775 UNUSED(size); // ok: handling own sdp events 776 777 hfp_connection_t * hfp_connection = get_hfp_connection_context_for_bd_addr(hfp_sdp_query_context.remote_address, hfp_sdp_query_context.local_role); 778 if (hfp_connection == NULL) { 779 log_info("connection with %s and local role %d not found", hfp_sdp_query_context.remote_address, hfp_sdp_query_context.local_role); 780 return; 781 } 782 783 switch (hci_event_packet_get_type(packet)){ 784 case SDP_EVENT_QUERY_RFCOMM_SERVICE: 785 hfp_connection->rfcomm_channel_nr = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet); 786 break; 787 case SDP_EVENT_QUERY_COMPLETE: 788 if (hfp_connection->rfcomm_channel_nr > 0){ 789 hfp_connection->state = HFP_W4_RFCOMM_CONNECTED; 790 btstack_packet_handler_t packet_handler; 791 switch (hfp_connection->local_role){ 792 case HFP_ROLE_AG: 793 packet_handler = hfp_ag_rfcomm_packet_handler; 794 break; 795 case HFP_ROLE_HF: 796 packet_handler = hfp_hf_rfcomm_packet_handler; 797 break; 798 default: 799 btstack_assert(false); 800 return; 801 } 802 803 rfcomm_create_channel(packet_handler, hfp_connection->remote_addr, hfp_connection->rfcomm_channel_nr, NULL); 804 805 } else { 806 uint8_t status = sdp_event_query_complete_get_status(packet); 807 if (status == ERROR_CODE_SUCCESS){ 808 // report service not found 809 status = SDP_SERVICE_NOT_FOUND; 810 } 811 hfp_handle_slc_setup_error(hfp_connection, status); 812 log_info("rfcomm service not found, status 0x%02x", status); 813 } 814 815 // register the SDP Query request to check if there is another connection waiting for the query 816 // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback 817 (void) sdp_client_register_query_callback(&hfp_sdp_query_request); 818 break; 819 default: 820 break; 821 } 822 } 823 824 // returns 0 if unexpected error or no other link options remained, otherwise 1 825 static int hfp_handle_failed_sco_connection(uint8_t status){ 826 827 if (hfp_sco_establishment_active->accept_sco != 0){ 828 log_info("(e)SCO Connection failed but not started by us"); 829 return 0; 830 } 831 832 log_info("(e)SCO Connection failed 0x%02x", status); 833 switch (status){ 834 case ERROR_CODE_INVALID_LMP_PARAMETERS_INVALID_LL_PARAMETERS: 835 case ERROR_CODE_SCO_AIR_MODE_REJECTED: 836 case ERROR_CODE_SCO_INTERVAL_REJECTED: 837 case ERROR_CODE_SCO_OFFSET_REJECTED: 838 case ERROR_CODE_UNSPECIFIED_ERROR: 839 case ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE: 840 case ERROR_CODE_UNSUPPORTED_REMOTE_FEATURE_UNSUPPORTED_LMP_FEATURE: 841 break; 842 default: 843 return 0; 844 } 845 846 // note: eSCO_S4 supported flag not available, but it's only relevant for highest CVSD link setting (and the current failed) 847 hfp_link_settings_t next_setting = hfp_next_link_setting_for_connection(hfp_sco_establishment_active->link_setting, hfp_sco_establishment_active, false); 848 849 // handle no valid setting found 850 if (next_setting == HFP_LINK_SETTINGS_NONE) { 851 if (hfp_sco_establishment_active->negotiated_codec == HFP_CODEC_MSBC){ 852 log_info("T2/T1 failed, fallback to CVSD - D1"); 853 hfp_sco_establishment_active->negotiated_codec = HFP_CODEC_CVSD; 854 hfp_sco_establishment_active->sco_for_msbc_failed = 1; 855 hfp_sco_establishment_active->ag_send_common_codec = true; 856 hfp_sco_establishment_active->link_setting = HFP_LINK_SETTINGS_D1; 857 } else { 858 // no other options 859 return 0; 860 } 861 } 862 863 log_info("e)SCO Connection: try new link_setting %d", next_setting); 864 hfp_sco_establishment_active->establish_audio_connection = 1; 865 hfp_sco_establishment_active->link_setting = next_setting; 866 hfp_sco_establishment_active->accept_sco = 0; 867 hfp_sco_establishment_active = NULL; 868 return 1; 869 } 870 871 void hfp_handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){ 872 UNUSED(packet_type); 873 UNUSED(channel); // ok: no channel 874 UNUSED(size); 875 876 bd_addr_t event_addr; 877 hci_con_handle_t handle; 878 hfp_connection_t * hfp_connection = NULL; 879 uint8_t status; 880 881 log_debug("HFP HCI event handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size); 882 883 switch (hci_event_packet_get_type(packet)) { 884 885 case HCI_EVENT_CONNECTION_REQUEST: 886 switch(hci_event_connection_request_get_link_type(packet)){ 887 case 0: // SCO 888 case 2: // eSCO 889 hci_event_connection_request_get_bd_addr(packet, event_addr); 890 hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role); 891 if (!hfp_connection) break; 892 if (hci_event_connection_request_get_link_type(packet) == 2){ 893 hfp_connection->accept_sco = 2; 894 } else { 895 hfp_connection->accept_sco = 1; 896 } 897 // configure SBC coded if needed 898 hfp_prepare_for_sco(hfp_connection); 899 log_info("accept sco %u\n", hfp_connection->accept_sco); 900 break; 901 default: 902 break; 903 } 904 break; 905 906 case HCI_EVENT_COMMAND_STATUS: 907 if (hci_event_command_status_get_command_opcode(packet) == hci_setup_synchronous_connection.opcode) { 908 if (hfp_sco_establishment_active == NULL) break; 909 status = hci_event_command_status_get_status(packet); 910 if (status == ERROR_CODE_SUCCESS) break; 911 912 hfp_connection = hfp_sco_establishment_active; 913 if (hfp_handle_failed_sco_connection(status)) break; 914 915 hfp_connection->accept_sco = 0; 916 hfp_connection->establish_audio_connection = 0; 917 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED; 918 hfp_sco_establishment_active = NULL; 919 hfp_emit_sco_connection_established(hfp_connection, status, 920 hfp_connection->negotiated_codec, 0, 0); 921 } 922 break; 923 924 case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{ 925 if (hfp_sco_establishment_active == NULL) break; 926 927 hfp_connection = hfp_sco_establishment_active; 928 929 status = hci_event_synchronous_connection_complete_get_status(packet); 930 if (status != ERROR_CODE_SUCCESS){ 931 if (hfp_handle_failed_sco_connection(status)) break; 932 933 hfp_connection->accept_sco = 0; 934 hfp_connection->establish_audio_connection = 0; 935 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED; 936 hfp_sco_establishment_active = NULL; 937 hfp_emit_sco_connection_established(hfp_connection, status, 938 hfp_connection->negotiated_codec, 0, 0); 939 break; 940 } 941 942 uint16_t sco_handle = hci_event_synchronous_connection_complete_get_handle(packet); 943 uint8_t link_type = hci_event_synchronous_connection_complete_get_link_type(packet); 944 uint8_t transmission_interval = hci_event_synchronous_connection_complete_get_transmission_interval(packet); // measured in slots 945 uint8_t retransmission_interval = hci_event_synchronous_connection_complete_get_retransmission_interval(packet);// measured in slots 946 uint16_t rx_packet_length = hci_event_synchronous_connection_complete_get_rx_packet_length(packet); // measured in bytes 947 uint16_t tx_packet_length = hci_event_synchronous_connection_complete_get_tx_packet_length(packet); // measured in bytes 948 949 switch (link_type){ 950 case 0x00: 951 log_info("SCO Connection established."); 952 if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval); 953 if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval); 954 if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length); 955 if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length); 956 break; 957 case 0x02: 958 log_info("eSCO Connection established. \n"); 959 break; 960 default: 961 log_error("(e)SCO reserved link_type 0x%2x", link_type); 962 break; 963 } 964 965 log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, " 966 " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)\n", sco_handle, 967 bd_addr_to_str(event_addr), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length, 968 hci_event_synchronous_connection_complete_get_air_mode(packet)); 969 970 if (hfp_connection->state == HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){ 971 log_info("SCO about to disconnect: HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN"); 972 hfp_connection->state = HFP_W2_DISCONNECT_SCO; 973 break; 974 } 975 hfp_connection->sco_handle = sco_handle; 976 hfp_connection->accept_sco = 0; 977 hfp_connection->establish_audio_connection = 0; 978 979 hfp_connection->state = HFP_AUDIO_CONNECTION_ESTABLISHED; 980 981 switch (hfp_connection->vra_state){ 982 case HFP_VRA_VOICE_RECOGNITION_ACTIVATED: 983 hfp_connection->ag_audio_connection_opened_before_vra = false; 984 break; 985 default: 986 hfp_connection->ag_audio_connection_opened_before_vra = true; 987 break; 988 } 989 990 hfp_sco_establishment_active = NULL; 991 992 hfp_emit_sco_connection_established(hfp_connection, status, 993 hfp_connection->negotiated_codec, rx_packet_length, tx_packet_length); 994 995 #ifdef ENABLE_NXP_PCM_WBS 996 hfp_connection->nxp_start_audio_handle = hfp_connection->sco_handle; 997 #endif 998 break; 999 } 1000 1001 case HCI_EVENT_DISCONNECTION_COMPLETE: 1002 handle = little_endian_read_16(packet,3); 1003 hfp_connection = get_hfp_connection_context_for_sco_handle(handle, local_role); 1004 1005 if (!hfp_connection) break; 1006 1007 #ifdef ENABLE_CC256X_ASSISTED_HFP 1008 hfp_connection->cc256x_send_wbs_disassociate = true; 1009 #endif 1010 #ifdef ENABLE_BCM_PCM_WBS 1011 hfp_connection->bcm_send_disable_wbs = true; 1012 #endif 1013 #ifdef ENABLE_NXP_PCM_WBS 1014 hfp_connection->nxp_stop_audio_handle = hfp_connection->sco_handle; 1015 #endif 1016 1017 if (hfp_connection->sco_handle == handle){ 1018 hfp_connection->sco_handle = HCI_CON_HANDLE_INVALID; 1019 hfp_connection->release_audio_connection = 0; 1020 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED; 1021 hfp_emit_audio_connection_released(hfp_connection, handle); 1022 1023 hfp_connection->ag_audio_connection_opened_before_vra = false; 1024 1025 if (hfp_connection->acl_handle == HCI_CON_HANDLE_INVALID){ 1026 hfp_reset_voice_recognition(hfp_connection); 1027 hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0); 1028 hfp_finalize_connection_context(hfp_connection); 1029 break; 1030 } else if (hfp_connection->release_slc_connection == 1){ 1031 hfp_connection->release_slc_connection = 0; 1032 hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM; 1033 rfcomm_disconnect(hfp_connection->acl_handle); 1034 } 1035 } 1036 1037 if (hfp_connection->state == HFP_W4_SCO_DISCONNECTED_TO_SHUTDOWN){ 1038 // RFCOMM already closed -> remote power off 1039 #if defined(ENABLE_CC256X_ASSISTED_HFP) || defined (ENABLE_BCM_PCM_WBS) 1040 hfp_connection->state = HFP_W4_WBS_SHUTDOWN; 1041 #else 1042 hfp_finalize_connection_context(hfp_connection); 1043 #endif 1044 break; 1045 } 1046 break; 1047 1048 default: 1049 break; 1050 } 1051 } 1052 1053 1054 void hfp_handle_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size, hfp_role_t local_role){ 1055 UNUSED(packet_type); 1056 UNUSED(channel); // ok: no channel 1057 UNUSED(size); 1058 1059 bd_addr_t event_addr; 1060 uint16_t rfcomm_cid; 1061 hfp_connection_t * hfp_connection = NULL; 1062 uint8_t status; 1063 1064 log_debug("HFP packet_handler type %u, event type %x, size %u", packet_type, hci_event_packet_get_type(packet), size); 1065 1066 switch (hci_event_packet_get_type(packet)) { 1067 1068 case RFCOMM_EVENT_INCOMING_CONNECTION: 1069 // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16) 1070 rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr); 1071 hfp_connection = hfp_create_connection(event_addr, local_role); 1072 if (!hfp_connection){ 1073 log_info("hfp: no memory to accept incoming connection - decline"); 1074 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet)); 1075 return; 1076 } 1077 if (hfp_connection->state != HFP_IDLE) { 1078 log_error("hfp: incoming connection but not idle, reject"); 1079 rfcomm_decline_connection(rfcomm_event_incoming_connection_get_rfcomm_cid(packet)); 1080 return; 1081 } 1082 1083 hfp_connection->rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet); 1084 hfp_connection->state = HFP_W4_RFCOMM_CONNECTED; 1085 rfcomm_accept_connection(hfp_connection->rfcomm_cid); 1086 break; 1087 1088 case RFCOMM_EVENT_CHANNEL_OPENED: 1089 rfcomm_event_channel_opened_get_bd_addr(packet, event_addr); 1090 1091 hfp_connection = get_hfp_connection_context_for_bd_addr(event_addr, local_role); 1092 btstack_assert(hfp_connection != NULL); 1093 1094 if (hfp_connection->state != HFP_W4_RFCOMM_CONNECTED){ 1095 break; 1096 } 1097 1098 status = rfcomm_event_channel_opened_get_status(packet); 1099 if (status != ERROR_CODE_SUCCESS) { 1100 hfp_handle_slc_setup_error(hfp_connection, status); 1101 break; 1102 } 1103 1104 hfp_connection->acl_handle = rfcomm_event_channel_opened_get_con_handle(packet); 1105 hfp_connection->rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet); 1106 hfp_connection->rfcomm_mtu = rfcomm_event_channel_opened_get_max_frame_size(packet); 1107 bd_addr_copy(hfp_connection->remote_addr, event_addr); 1108 hfp_connection->state = HFP_EXCHANGE_SUPPORTED_FEATURES; 1109 1110 rfcomm_request_can_send_now_event(hfp_connection->rfcomm_cid); 1111 break; 1112 1113 case RFCOMM_EVENT_CHANNEL_CLOSED: 1114 rfcomm_cid = little_endian_read_16(packet,2); 1115 hfp_connection = get_hfp_connection_context_for_rfcomm_cid(rfcomm_cid); 1116 if (!hfp_connection) break; 1117 switch (hfp_connection->state){ 1118 case HFP_W4_RFCOMM_DISCONNECTED_AND_RESTART: 1119 hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID; 1120 hfp_connection->state = HFP_IDLE; 1121 hfp_establish_service_level_connection(hfp_connection->remote_addr, hfp_connection->service_uuid, local_role); 1122 break; 1123 1124 case HFP_AUDIO_CONNECTION_ESTABLISHED: 1125 // service connection was released, this implicitly releases audio connection as well 1126 hfp_connection->release_audio_connection = 0; 1127 hfp_connection->acl_handle = HCI_CON_HANDLE_INVALID; 1128 hfp_connection->state = HFP_W4_SCO_DISCONNECTED_TO_SHUTDOWN; 1129 gap_disconnect(hfp_connection->sco_handle); 1130 break; 1131 1132 default: 1133 // regular case 1134 hfp_reset_voice_recognition(hfp_connection); 1135 hfp_emit_event(hfp_connection, HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED, 0); 1136 hfp_finalize_connection_context(hfp_connection); 1137 break; 1138 } 1139 break; 1140 1141 default: 1142 break; 1143 } 1144 } 1145 // translates command string into hfp_command_t CMD 1146 1147 typedef struct { 1148 const char * command; 1149 hfp_command_t command_id; 1150 } hfp_command_entry_t; 1151 1152 static hfp_command_entry_t hfp_ag_command_table[] = { 1153 { "AT+BAC=", HFP_CMD_AVAILABLE_CODECS }, 1154 { "AT+BCC", HFP_CMD_TRIGGER_CODEC_CONNECTION_SETUP }, 1155 { "AT+BCS=", HFP_CMD_HF_CONFIRMED_CODEC }, 1156 { "AT+BIA=", HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE, }, // +BIA:<enabled>,,<enabled>,,,<enabled> 1157 { "AT+BIEV=", HFP_CMD_HF_INDICATOR_STATUS }, 1158 { "AT+BIND=", HFP_CMD_LIST_GENERIC_STATUS_INDICATORS }, 1159 { "AT+BIND=?", HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS }, 1160 { "AT+BIND?", HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE }, 1161 { "AT+BINP=", HFP_CMD_HF_REQUEST_PHONE_NUMBER }, 1162 { "AT+BLDN", HFP_CMD_REDIAL_LAST_NUMBER }, 1163 { "AT+BRSF=", HFP_CMD_SUPPORTED_FEATURES }, 1164 { "AT+BTRH=", HFP_CMD_RESPONSE_AND_HOLD_COMMAND }, 1165 { "AT+BTRH?", HFP_CMD_RESPONSE_AND_HOLD_QUERY }, 1166 { "AT+BVRA=", HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION }, 1167 { "AT+CCWA=", HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION}, 1168 { "AT+CHLD=", HFP_CMD_CALL_HOLD }, 1169 { "AT+CHLD=?", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES }, 1170 { "AT+CHUP", HFP_CMD_HANG_UP_CALL }, 1171 { "AT+CIND=?", HFP_CMD_RETRIEVE_AG_INDICATORS }, 1172 { "AT+CIND?", HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS }, 1173 { "AT+CLCC", HFP_CMD_LIST_CURRENT_CALLS }, 1174 { "AT+CLIP=", HFP_CMD_ENABLE_CLIP}, 1175 { "AT+CMEE=", HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR}, 1176 { "AT+CMER=", HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE }, 1177 { "AT+CNUM", HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION }, 1178 { "AT+COPS=", HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT }, 1179 { "AT+COPS?", HFP_CMD_QUERY_OPERATOR_SELECTION_NAME }, 1180 { "AT+NREC=", HFP_CMD_TURN_OFF_EC_AND_NR, }, 1181 { "AT+VGM=", HFP_CMD_SET_MICROPHONE_GAIN }, 1182 { "AT+VGS=", HFP_CMD_SET_SPEAKER_GAIN }, 1183 { "AT+VTS=", HFP_CMD_TRANSMIT_DTMF_CODES }, 1184 { "ATA", HFP_CMD_CALL_ANSWERED }, 1185 }; 1186 1187 static hfp_command_entry_t hfp_hf_command_table[] = { 1188 { "+BCS:", HFP_CMD_AG_SUGGESTED_CODEC }, 1189 { "+BIND:", HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS }, 1190 { "+BINP:", HFP_CMD_AG_SENT_PHONE_NUMBER }, 1191 { "+BRSF:", HFP_CMD_SUPPORTED_FEATURES }, 1192 { "+BSIR:", HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING }, 1193 { "+BTRH:", HFP_CMD_RESPONSE_AND_HOLD_STATUS }, 1194 { "+BVRA:", HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION }, 1195 { "+CCWA:", HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE, }, 1196 { "+CHLD:", HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES }, 1197 { "+CIEV:", HFP_CMD_TRANSFER_AG_INDICATOR_STATUS}, 1198 { "+CIND:", HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC }, 1199 { "+CLCC:", HFP_CMD_LIST_CURRENT_CALLS }, 1200 { "+CLIP:", HFP_CMD_AG_SENT_CLIP_INFORMATION }, 1201 { "+CME ERROR:", HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR }, 1202 { "+CNUM:", HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION}, 1203 { "+COPS:", HFP_CMD_QUERY_OPERATOR_SELECTION_NAME }, 1204 { "+VGM:", HFP_CMD_SET_MICROPHONE_GAIN }, 1205 { "+VGM=", HFP_CMD_SET_MICROPHONE_GAIN }, 1206 { "+VGS:", HFP_CMD_SET_SPEAKER_GAIN}, 1207 { "+VGS=", HFP_CMD_SET_SPEAKER_GAIN}, 1208 { "ERROR", HFP_CMD_ERROR}, 1209 { "NOP", HFP_CMD_NONE}, // dummy command used by unit tests 1210 { "OK", HFP_CMD_OK }, 1211 { "RING", HFP_CMD_RING }, 1212 }; 1213 1214 static const hfp_custom_at_command_t * 1215 hfp_custom_command_lookup(bool isHandsFree, const char *text) { 1216 btstack_linked_list_t * custom_commands = isHandsFree ? &hfp_custom_commands_hf : &hfp_custom_commands_ag; 1217 btstack_linked_list_iterator_t it; 1218 btstack_linked_list_iterator_init(&it, custom_commands); 1219 while (btstack_linked_list_iterator_has_next(&it)) { 1220 hfp_custom_at_command_t *at_command = (hfp_custom_at_command_t *) btstack_linked_list_iterator_next(&it); 1221 int match = strcmp(text, at_command->command); 1222 if (match == 0) { 1223 return at_command; 1224 } 1225 } 1226 return NULL; 1227 } 1228 1229 static hfp_command_t parse_command(const char * line_buffer, int isHandsFree){ 1230 1231 // check for custom commands, AG only 1232 const hfp_custom_at_command_t * custom_at_command = hfp_custom_command_lookup(isHandsFree, line_buffer); 1233 if (custom_at_command != NULL){ 1234 return HFP_CMD_CUSTOM_MESSAGE; 1235 } 1236 1237 // table lookup based on role 1238 uint16_t num_entries; 1239 hfp_command_entry_t * table; 1240 if (isHandsFree == 0){ 1241 table = hfp_ag_command_table; 1242 num_entries = sizeof(hfp_ag_command_table) / sizeof(hfp_command_entry_t); 1243 } else { 1244 table = hfp_hf_command_table; 1245 num_entries = sizeof(hfp_hf_command_table) / sizeof(hfp_command_entry_t); 1246 } 1247 // binary search 1248 uint16_t left = 0; 1249 uint16_t right = num_entries - 1; 1250 while (left <= right){ 1251 uint16_t middle = left + (right - left) / 2; 1252 hfp_command_entry_t *entry = &table[middle]; 1253 int match = strcmp(line_buffer, entry->command); 1254 if (match < 0){ 1255 // search term is lower than middle element 1256 if (right == 0) break; 1257 right = middle - 1; 1258 } else if (match == 0){ 1259 return entry->command_id; 1260 } else { 1261 // search term is higher than middle element 1262 left = middle + 1; 1263 } 1264 } 1265 1266 // note: if parser in CMD_HEADER state would treats digits and maybe '+' as separator, match on "ATD" would work. 1267 // note: phone number is currently expected in line_buffer[3..] 1268 // prefix match on 'ATD', AG only 1269 if ((isHandsFree == 0) && (strncmp(line_buffer, HFP_CALL_PHONE_NUMBER, strlen(HFP_CALL_PHONE_NUMBER)) == 0)){ 1270 return HFP_CMD_CALL_PHONE_NUMBER; 1271 } 1272 1273 // Valid looking, but unknown commands/responses 1274 if ((isHandsFree == 0) && (strncmp(line_buffer, "AT+", 3) == 0)){ 1275 return HFP_CMD_UNKNOWN; 1276 } 1277 1278 if ((isHandsFree != 0) && (strncmp(line_buffer, "+", 1) == 0)){ 1279 return HFP_CMD_UNKNOWN; 1280 } 1281 1282 return HFP_CMD_NONE; 1283 } 1284 1285 static void hfp_parser_store_byte(hfp_connection_t * hfp_connection, uint8_t byte){ 1286 if ((hfp_connection->line_size + 1) >= HFP_MAX_VR_TEXT_SIZE) return; 1287 hfp_connection->line_buffer[hfp_connection->line_size++] = byte; 1288 hfp_connection->line_buffer[hfp_connection->line_size] = 0; 1289 } 1290 static int hfp_parser_is_buffer_empty(hfp_connection_t * hfp_connection){ 1291 return hfp_connection->line_size == 0; 1292 } 1293 1294 static int hfp_parser_is_end_of_line(uint8_t byte){ 1295 return (byte == '\n') || (byte == '\r'); 1296 } 1297 1298 void hfp_parser_reset_line_buffer(hfp_connection_t *hfp_connection) { 1299 hfp_connection->line_size = 0; 1300 // we don't set the first byte to '\0' to allow access to last argument e.g. in hfp_hf_handle_rfcommand 1301 } 1302 1303 static void hfp_parser_store_if_token(hfp_connection_t * hfp_connection, uint8_t byte){ 1304 switch (byte){ 1305 case ',': 1306 case '-': 1307 case ';': 1308 case '(': 1309 case ')': 1310 case '\n': 1311 case '\r': 1312 break; 1313 default: 1314 hfp_parser_store_byte(hfp_connection, byte); 1315 break; 1316 } 1317 } 1318 1319 static bool hfp_parser_is_separator( uint8_t byte){ 1320 switch (byte){ 1321 case ',': 1322 case '-': 1323 case ';': 1324 case '\n': 1325 case '\r': 1326 return true; 1327 default: 1328 return false; 1329 } 1330 } 1331 1332 // returns true if received bytes was processed. Otherwise, functions will be called with same byte again 1333 // this is used to for a one byte lookahead, where an unexpected byte is pushed back by returning false 1334 static bool hfp_parse_byte(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){ 1335 1336 #ifdef HFP_DEBUG 1337 if (byte >= ' '){ 1338 printf("Parse '%c' - state %u, buffer %s\n", byte, hfp_connection->parser_state, hfp_connection->line_buffer); 1339 } else { 1340 printf("Parse 0x%02x - state %u, buffer %s\n", byte, hfp_connection->parser_state, hfp_connection->line_buffer); 1341 } 1342 #endif 1343 1344 // handle doubles quotes 1345 if (byte == '"'){ 1346 hfp_connection->parser_quoted = !hfp_connection->parser_quoted; 1347 return true; 1348 } 1349 if (hfp_connection->parser_quoted) { 1350 hfp_parser_store_byte(hfp_connection, byte); 1351 return true; 1352 } 1353 1354 // ignore spaces outside command or double quotes (required e.g. for '+CME ERROR:..") command 1355 if ((byte == ' ') && (hfp_connection->parser_state != HFP_PARSER_CMD_HEADER)) return true; 1356 1357 bool processed = true; 1358 1359 switch (hfp_connection->parser_state) { 1360 case HFP_PARSER_CMD_HEADER: 1361 switch (byte) { 1362 case '\n': 1363 case '\r': 1364 case ';': 1365 // ignore separator 1366 break; 1367 case ':': 1368 case '?': 1369 // store separator 1370 hfp_parser_store_byte(hfp_connection, byte); 1371 break; 1372 case '=': 1373 // equal sign: remember and wait for next char to decided between '=?' and '=\?' 1374 hfp_connection->found_equal_sign = true; 1375 hfp_parser_store_byte(hfp_connection, byte); 1376 return true; 1377 default: 1378 // store if not lookahead 1379 if (!hfp_connection->found_equal_sign) { 1380 hfp_parser_store_byte(hfp_connection, byte); 1381 return true; 1382 } 1383 // mark as lookahead 1384 processed = false; 1385 break; 1386 } 1387 1388 // ignore empty tokens 1389 if (hfp_parser_is_buffer_empty(hfp_connection)) return true; 1390 1391 // parse 1392 hfp_connection->command = parse_command((char *)hfp_connection->line_buffer, isHandsFree); 1393 1394 // pick +CIND version based on connection state: descriptions during SLC vs. states later 1395 if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS_GENERIC){ 1396 switch(hfp_connection->state){ 1397 case HFP_W4_RETRIEVE_INDICATORS_STATUS: 1398 hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS; 1399 break; 1400 case HFP_W4_RETRIEVE_INDICATORS: 1401 hfp_connection->command = HFP_CMD_RETRIEVE_AG_INDICATORS; 1402 break; 1403 default: 1404 hfp_connection->command = HFP_CMD_UNKNOWN; 1405 break; 1406 } 1407 } 1408 1409 log_info("command string '%s', handsfree %u -> cmd id %u", (char *)hfp_connection->line_buffer, isHandsFree, hfp_connection->command); 1410 1411 // store command id for custom command and just store rest of line 1412 if (hfp_connection->command == HFP_CMD_CUSTOM_MESSAGE){ 1413 const hfp_custom_at_command_t * at_command = hfp_custom_command_lookup(isHandsFree, (const char *) hfp_connection->line_buffer); 1414 hfp_connection->custom_at_command_id = at_command->command_id; 1415 hfp_connection->parser_state = HFP_PARSER_CUSTOM_COMMAND; 1416 return processed; 1417 } 1418 1419 // next state 1420 hfp_parser_reset_line_buffer(hfp_connection); 1421 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE; 1422 1423 return processed; 1424 1425 case HFP_PARSER_CMD_SEQUENCE: 1426 // handle empty fields 1427 if ((byte == ',' ) && (hfp_connection->line_size == 0)){ 1428 hfp_connection->line_buffer[0] = 0; 1429 hfp_connection->ignore_value = 1; 1430 parse_sequence(hfp_connection); 1431 return true; 1432 } 1433 1434 hfp_parser_store_if_token(hfp_connection, byte); 1435 if (!hfp_parser_is_separator(byte)) return true; 1436 1437 // ignore empty tokens 1438 switch (hfp_connection->command){ 1439 case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION: 1440 // don't ignore empty string 1441 break; 1442 default: 1443 if (hfp_parser_is_buffer_empty(hfp_connection) && (hfp_connection->ignore_value == 0)) { 1444 return true; 1445 } 1446 break; 1447 } 1448 1449 parse_sequence(hfp_connection); 1450 1451 hfp_parser_reset_line_buffer(hfp_connection); 1452 1453 switch (hfp_connection->command){ 1454 case HFP_CMD_AG_SENT_PHONE_NUMBER: 1455 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE: 1456 case HFP_CMD_AG_SENT_CLIP_INFORMATION: 1457 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS: 1458 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME: 1459 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT: 1460 case HFP_CMD_RETRIEVE_AG_INDICATORS: 1461 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE: 1462 case HFP_CMD_HF_INDICATOR_STATUS: 1463 hfp_connection->parser_state = HFP_PARSER_SECOND_ITEM; 1464 break; 1465 default: 1466 break; 1467 } 1468 return true; 1469 1470 case HFP_PARSER_SECOND_ITEM: 1471 1472 hfp_parser_store_if_token(hfp_connection, byte); 1473 if (!hfp_parser_is_separator(byte)) return true; 1474 1475 switch (hfp_connection->command){ 1476 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME: 1477 log_info("format %s, ", hfp_connection->line_buffer); 1478 hfp_connection->network_operator.format = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1479 break; 1480 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT: 1481 log_info("format %s \n", hfp_connection->line_buffer); 1482 hfp_connection->network_operator.format = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1483 break; 1484 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS: 1485 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS: 1486 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE: 1487 hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].state = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer); 1488 break; 1489 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS: 1490 hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer); 1491 log_info("%d \n", hfp_connection->ag_indicators[hfp_connection->parser_item_index].status); 1492 hfp_connection->ag_indicators[hfp_connection->parser_item_index].status_changed = 1; 1493 break; 1494 case HFP_CMD_RETRIEVE_AG_INDICATORS: 1495 hfp_connection->ag_indicators[hfp_connection->parser_item_index].min_range = btstack_atoi((char *)hfp_connection->line_buffer); 1496 log_info("%s, ", hfp_connection->line_buffer); 1497 break; 1498 case HFP_CMD_AG_SENT_PHONE_NUMBER: 1499 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE: 1500 case HFP_CMD_AG_SENT_CLIP_INFORMATION: 1501 hfp_connection->bnip_type = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer); 1502 break; 1503 case HFP_CMD_HF_INDICATOR_STATUS: 1504 hfp_connection->parser_indicator_value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1505 break; 1506 default: 1507 break; 1508 } 1509 1510 hfp_parser_reset_line_buffer(hfp_connection); 1511 1512 hfp_connection->parser_state = HFP_PARSER_THIRD_ITEM; 1513 1514 return true; 1515 1516 case HFP_PARSER_THIRD_ITEM: 1517 1518 hfp_parser_store_if_token(hfp_connection, byte); 1519 if (!hfp_parser_is_separator(byte)) return true; 1520 1521 switch (hfp_connection->command){ 1522 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME: 1523 btstack_strcpy(hfp_connection->network_operator.name, HFP_MAX_NETWORK_OPERATOR_NAME_SIZE, (char *)hfp_connection->line_buffer); 1524 break; 1525 case HFP_CMD_RETRIEVE_AG_INDICATORS: 1526 hfp_connection->ag_indicators[hfp_connection->parser_item_index].max_range = btstack_atoi((char *)hfp_connection->line_buffer); 1527 hfp_next_indicators_index(hfp_connection); 1528 hfp_connection->ag_indicators_nr = hfp_connection->parser_item_index; 1529 break; 1530 case HFP_CMD_AG_SENT_CLIP_INFORMATION: 1531 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE: 1532 // track if last argument exists 1533 hfp_connection->clip_have_alpha = hfp_connection->line_size != 0; 1534 break; 1535 default: 1536 break; 1537 } 1538 1539 hfp_parser_reset_line_buffer(hfp_connection); 1540 1541 if (hfp_connection->command == HFP_CMD_RETRIEVE_AG_INDICATORS){ 1542 hfp_connection->parser_state = HFP_PARSER_CMD_SEQUENCE; 1543 } 1544 return true; 1545 1546 case HFP_PARSER_CUSTOM_COMMAND: 1547 if (hfp_parser_is_end_of_line(byte) == false){ 1548 hfp_parser_store_byte(hfp_connection, byte); 1549 } 1550 return true; 1551 1552 default: 1553 btstack_assert(false); 1554 return true; 1555 } 1556 } 1557 1558 void hfp_parse(hfp_connection_t * hfp_connection, uint8_t byte, int isHandsFree){ 1559 bool processed = false; 1560 while (!processed){ 1561 processed = hfp_parse_byte(hfp_connection, byte, isHandsFree); 1562 } 1563 // reset parser state on end-of-line 1564 if (hfp_parser_is_end_of_line(byte)){ 1565 hfp_connection->found_equal_sign = false; 1566 hfp_connection->parser_item_index = 0; 1567 hfp_connection->parser_state = HFP_PARSER_CMD_HEADER; 1568 } 1569 } 1570 1571 static void parse_sequence(hfp_connection_t * hfp_connection){ 1572 int value; 1573 switch (hfp_connection->command){ 1574 case HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS: 1575 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1576 int i; 1577 switch (hfp_connection->parser_item_index){ 1578 case 0: 1579 for (i=0;i<hfp_connection->generic_status_indicators_nr;i++){ 1580 if (hfp_connection->generic_status_indicators[i].uuid == value){ 1581 hfp_connection->parser_indicator_index = i; 1582 break; 1583 } 1584 } 1585 break; 1586 case 1: 1587 if (hfp_connection->parser_indicator_index <0) break; 1588 hfp_connection->generic_status_indicators[hfp_connection->parser_indicator_index].state = value; 1589 log_info("HFP_CMD_SET_GENERIC_STATUS_INDICATOR_STATUS set indicator at index %u, to %u\n", 1590 hfp_connection->parser_item_index, value); 1591 break; 1592 default: 1593 break; 1594 } 1595 hfp_next_indicators_index(hfp_connection); 1596 break; 1597 1598 case HFP_CMD_GET_SUBSCRIBER_NUMBER_INFORMATION: 1599 switch(hfp_connection->parser_item_index){ 1600 case 0: 1601 // <alpha>: This optional field is not supported, and shall be left blank. 1602 break; 1603 case 1: 1604 // <number>: Quoted string containing the phone number in the format specified by <type>. 1605 btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer); 1606 break; 1607 case 2: 1608 /* 1609 <type> field specifies the format of the phone number provided, and can be one of the following values: 1610 - values 128-143: The phone number format may be a national or international format, and may contain prefix and/or escape digits. No changes on the number presentation are required. 1611 - values 144-159: The phone number format is an international number, including the country code prefix. If the plus sign ("+") is not included as part of the number and shall be added by the AG as needed. 1612 - values 160-175: National number. No prefix nor escape digits included. 1613 */ 1614 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1615 hfp_connection->bnip_type = value; 1616 break; 1617 case 3: 1618 // <speed>: This optional field is not supported, and shall be left blank. 1619 break; 1620 case 4: 1621 // <service>: Indicates which service this phone number relates to. Shall be either 4 (voice) or 5 (fax). 1622 default: 1623 break; 1624 } 1625 // index > 2 are ignored in switch above 1626 hfp_connection->parser_item_index++; 1627 break; 1628 case HFP_CMD_LIST_CURRENT_CALLS: 1629 switch(hfp_connection->parser_item_index){ 1630 case 0: 1631 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1632 hfp_connection->clcc_idx = value; 1633 break; 1634 case 1: 1635 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1636 hfp_connection->clcc_dir = value; 1637 break; 1638 case 2: 1639 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1640 hfp_connection->clcc_status = value; 1641 break; 1642 case 3: 1643 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1644 hfp_connection->clcc_mode = value; 1645 break; 1646 case 4: 1647 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1648 hfp_connection->clcc_mpty = value; 1649 break; 1650 case 5: 1651 btstack_strcpy(hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer); 1652 break; 1653 case 6: 1654 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1655 hfp_connection->bnip_type = value; 1656 break; 1657 default: 1658 break; 1659 } 1660 // index > 6 are ignored in switch above 1661 hfp_connection->parser_item_index++; 1662 break; 1663 case HFP_CMD_SET_MICROPHONE_GAIN: 1664 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1665 hfp_connection->microphone_gain = value; 1666 log_info("hfp parse HFP_CMD_SET_MICROPHONE_GAIN %d\n", value); 1667 break; 1668 case HFP_CMD_SET_SPEAKER_GAIN: 1669 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1670 hfp_connection->speaker_gain = value; 1671 log_info("hfp parse HFP_CMD_SET_SPEAKER_GAIN %d\n", value); 1672 break; 1673 case HFP_CMD_TURN_OFF_EC_AND_NR: 1674 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1675 hfp_connection->ag_echo_and_noise_reduction = value; 1676 log_info("hfp parse HFP_CMD_TURN_OFF_EC_AND_NR %d\n", value); 1677 break; 1678 case HFP_CMD_CHANGE_IN_BAND_RING_TONE_SETTING: 1679 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1680 hfp_connection->remote_supported_features = store_bit(hfp_connection->remote_supported_features, HFP_AGSF_IN_BAND_RING_TONE, value); 1681 log_info("hfp parse HFP_CHANGE_IN_BAND_RING_TONE_SETTING %d\n", value); 1682 break; 1683 case HFP_CMD_HF_CONFIRMED_CODEC: 1684 hfp_connection->codec_confirmed = btstack_atoi((char*)hfp_connection->line_buffer); 1685 log_info("hfp parse HFP_CMD_HF_CONFIRMED_CODEC %d\n", hfp_connection->codec_confirmed); 1686 break; 1687 case HFP_CMD_AG_SUGGESTED_CODEC: 1688 hfp_connection->suggested_codec = btstack_atoi((char*)hfp_connection->line_buffer); 1689 log_info("hfp parse HFP_CMD_AG_SUGGESTED_CODEC %d\n", hfp_connection->suggested_codec); 1690 break; 1691 case HFP_CMD_SUPPORTED_FEATURES: 1692 hfp_connection->remote_supported_features = btstack_atoi((char*)hfp_connection->line_buffer); 1693 log_info("Parsed supported feature %d\n", (int) hfp_connection->remote_supported_features); 1694 break; 1695 case HFP_CMD_AVAILABLE_CODECS: 1696 log_info("Parsed codec %s\n", hfp_connection->line_buffer); 1697 hfp_connection->remote_codecs[hfp_connection->parser_item_index] = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer); 1698 hfp_next_codec_index(hfp_connection); 1699 hfp_connection->remote_codecs_nr = hfp_connection->parser_item_index; 1700 break; 1701 case HFP_CMD_RETRIEVE_AG_INDICATORS: 1702 btstack_strcpy((char *)hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, HFP_MAX_INDICATOR_DESC_SIZE, (char *)hfp_connection->line_buffer); 1703 hfp_connection->ag_indicators[hfp_connection->parser_item_index].index = hfp_connection->parser_item_index+1; 1704 log_info("Indicator %d: %s (", hfp_connection->ag_indicators_nr+1, hfp_connection->line_buffer); 1705 break; 1706 case HFP_CMD_RETRIEVE_AG_INDICATORS_STATUS: 1707 log_info("Parsed Indicator %d with status: %s\n", hfp_connection->parser_item_index+1, hfp_connection->line_buffer); 1708 hfp_connection->ag_indicators[hfp_connection->parser_item_index].status = btstack_atoi((char *) hfp_connection->line_buffer); 1709 hfp_next_indicators_index(hfp_connection); 1710 break; 1711 case HFP_CMD_ENABLE_INDICATOR_STATUS_UPDATE: 1712 hfp_next_indicators_index(hfp_connection); 1713 if (hfp_connection->parser_item_index != 4) break; 1714 log_info("Parsed Enable indicators: %s\n", hfp_connection->line_buffer); 1715 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1716 hfp_connection->enable_status_update_for_ag_indicators = (uint8_t) value; 1717 break; 1718 case HFP_CMD_SUPPORT_CALL_HOLD_AND_MULTIPARTY_SERVICES: 1719 log_info("Parsed Support call hold: %s\n", hfp_connection->line_buffer); 1720 if (hfp_connection->line_size > 2 ) break; 1721 memcpy((char *)hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name, (char *)hfp_connection->line_buffer, HFP_CALL_SERVICE_SIZE-1); 1722 hfp_connection->remote_call_services[hfp_connection->remote_call_services_index].name[HFP_CALL_SERVICE_SIZE - 1] = 0; 1723 hfp_next_remote_call_services_index(hfp_connection); 1724 break; 1725 case HFP_CMD_LIST_GENERIC_STATUS_INDICATORS: 1726 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS: 1727 log_info("Parsed Generic status indicator: %s\n", hfp_connection->line_buffer); 1728 hfp_connection->generic_status_indicators[hfp_connection->parser_item_index].uuid = (uint16_t)btstack_atoi((char*)hfp_connection->line_buffer); 1729 hfp_next_indicators_index(hfp_connection); 1730 hfp_connection->generic_status_indicators_nr = hfp_connection->parser_item_index; 1731 break; 1732 case HFP_CMD_RETRIEVE_GENERIC_STATUS_INDICATORS_STATE: 1733 // HF parses inital AG gen. ind. state 1734 log_info("Parsed List generic status indicator %s state: ", hfp_connection->line_buffer); 1735 hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection); 1736 break; 1737 case HFP_CMD_HF_INDICATOR_STATUS: 1738 hfp_connection->parser_indicator_index = hfp_parse_indicator_index(hfp_connection); 1739 log_info("Parsed HF indicator index %u", hfp_connection->parser_indicator_index); 1740 break; 1741 case HFP_CMD_ENABLE_INDIVIDUAL_AG_INDICATOR_STATUS_UPDATE: 1742 // AG parses new gen. ind. state 1743 if (hfp_connection->ignore_value){ 1744 hfp_connection->ignore_value = 0; 1745 log_info("Parsed Enable AG indicator pos %u('%s') - unchanged (stays %u)\n", hfp_connection->parser_item_index, 1746 hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled); 1747 } 1748 else if (hfp_connection->ag_indicators[hfp_connection->parser_item_index].mandatory){ 1749 log_info("Parsed Enable AG indicator pos %u('%s') - ignore (mandatory)\n", 1750 hfp_connection->parser_item_index, hfp_connection->ag_indicators[hfp_connection->parser_item_index].name); 1751 } else { 1752 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1753 hfp_connection->ag_indicators[hfp_connection->parser_item_index].enabled = value; 1754 log_info("Parsed Enable AG indicator pos %u('%s'): %u\n", hfp_connection->parser_item_index, 1755 hfp_connection->ag_indicators[hfp_connection->parser_item_index].name, value); 1756 } 1757 hfp_next_indicators_index(hfp_connection); 1758 break; 1759 case HFP_CMD_TRANSFER_AG_INDICATOR_STATUS: 1760 // indicators are indexed starting with 1 1761 hfp_connection->parser_item_index = hfp_parse_indicator_index(hfp_connection); 1762 log_info("Parsed status of the AG indicator %d, status ", hfp_connection->parser_item_index); 1763 break; 1764 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME: 1765 hfp_connection->network_operator.mode = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1766 log_info("Parsed network operator mode: %d, ", hfp_connection->network_operator.mode); 1767 break; 1768 case HFP_CMD_QUERY_OPERATOR_SELECTION_NAME_FORMAT: 1769 if (hfp_connection->line_buffer[0] == '3'){ 1770 log_info("Parsed Set network operator format : %s, ", hfp_connection->line_buffer); 1771 break; 1772 } 1773 // TODO emit ERROR, wrong format 1774 log_info("ERROR Set network operator format: index %s not supported\n", hfp_connection->line_buffer); 1775 break; 1776 case HFP_CMD_ERROR: 1777 break; 1778 case HFP_CMD_EXTENDED_AUDIO_GATEWAY_ERROR: 1779 hfp_connection->extended_audio_gateway_error = 1; 1780 hfp_connection->extended_audio_gateway_error_value = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer); 1781 break; 1782 case HFP_CMD_ENABLE_EXTENDED_AUDIO_GATEWAY_ERROR: 1783 hfp_connection->enable_extended_audio_gateway_error_report = (uint8_t)btstack_atoi((char*)hfp_connection->line_buffer); 1784 hfp_connection->extended_audio_gateway_error = 0; 1785 break; 1786 case HFP_CMD_AG_SENT_PHONE_NUMBER: 1787 case HFP_CMD_AG_SENT_CALL_WAITING_NOTIFICATION_UPDATE: 1788 case HFP_CMD_AG_SENT_CLIP_INFORMATION: 1789 btstack_strcpy((char *)hfp_connection->bnip_number, sizeof(hfp_connection->bnip_number), (char *)hfp_connection->line_buffer); 1790 break; 1791 case HFP_CMD_CALL_HOLD: 1792 hfp_connection->ag_call_hold_action = hfp_connection->line_buffer[0] - '0'; 1793 if (hfp_connection->line_buffer[1] != '\0'){ 1794 hfp_connection->call_index = btstack_atoi((char *)&hfp_connection->line_buffer[1]); 1795 } 1796 break; 1797 case HFP_CMD_RESPONSE_AND_HOLD_COMMAND: 1798 hfp_connection->ag_response_and_hold_action = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1799 break; 1800 case HFP_CMD_TRANSMIT_DTMF_CODES: 1801 hfp_connection->ag_dtmf_code = hfp_connection->line_buffer[0]; 1802 break; 1803 case HFP_CMD_ENABLE_CLIP: 1804 hfp_connection->clip_enabled = hfp_connection->line_buffer[0] != '0'; 1805 break; 1806 case HFP_CMD_ENABLE_CALL_WAITING_NOTIFICATION: 1807 hfp_connection->call_waiting_notification_enabled = hfp_connection->line_buffer[0] != '0'; 1808 break; 1809 case HFP_CMD_HF_ACTIVATE_VOICE_RECOGNITION: 1810 value = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1811 hfp_connection->ag_activate_voice_recognition_value = value; 1812 break; 1813 case HFP_CMD_AG_ACTIVATE_VOICE_RECOGNITION: 1814 switch(hfp_connection->parser_item_index){ 1815 case 0: 1816 hfp_connection->ag_vra_status = btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1817 break; 1818 case 1: 1819 hfp_connection->ag_vra_state = (hfp_voice_recognition_state_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1820 break; 1821 case 2: 1822 hfp_connection->ag_msg.text_id = 0; 1823 for (i = 0 ; i < 4; i++){ 1824 hfp_connection->ag_msg.text_id = (hfp_connection->ag_msg.text_id << 4) | nibble_for_char(hfp_connection->line_buffer[i]); 1825 } 1826 break; 1827 case 3: 1828 hfp_connection->ag_msg.text_type = (hfp_text_type_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1829 break; 1830 case 4: 1831 hfp_connection->ag_msg.text_operation = (hfp_text_operation_t) btstack_atoi((char *)&hfp_connection->line_buffer[0]); 1832 break; 1833 case 5: 1834 hfp_connection->line_buffer[hfp_connection->line_size] = 0; 1835 hfp_connection->ag_vra_msg_length = hfp_connection->line_size + 1; 1836 break; 1837 default: 1838 break; 1839 } 1840 hfp_connection->parser_item_index++; 1841 break; 1842 default: 1843 break; 1844 } 1845 } 1846 1847 static void hfp_handle_start_sdp_client_query(void * context){ 1848 UNUSED(context); 1849 1850 btstack_linked_list_iterator_t it; 1851 btstack_linked_list_iterator_init(&it, &hfp_connections); 1852 while (btstack_linked_list_iterator_has_next(&it)){ 1853 hfp_connection_t * connection = (hfp_connection_t *)btstack_linked_list_iterator_next(&it); 1854 1855 if (connection->state != HFP_W2_SEND_SDP_QUERY) continue; 1856 1857 connection->state = HFP_W4_SDP_QUERY_COMPLETE; 1858 hfp_sdp_query_context.local_role = connection->local_role; 1859 (void)memcpy(hfp_sdp_query_context.remote_address, connection->remote_addr, 6); 1860 sdp_client_query_rfcomm_channel_and_name_for_service_class_uuid(&handle_query_rfcomm_event, connection->remote_addr, connection->service_uuid); 1861 return; 1862 } 1863 } 1864 1865 uint8_t hfp_establish_service_level_connection(bd_addr_t bd_addr, uint16_t service_uuid, hfp_role_t local_role){ 1866 hfp_connection_t * connection = get_hfp_connection_context_for_bd_addr(bd_addr, local_role); 1867 if (connection != NULL){ 1868 // allow to call hfp_establish_service_level_connection after SLC was triggered remotely 1869 // @note this also allows to call hfp_establish_service_level_connection again before SLC is complete 1870 if (connection->state < HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){ 1871 return ERROR_CODE_SUCCESS; 1872 } else { 1873 return ERROR_CODE_COMMAND_DISALLOWED; 1874 } 1875 } 1876 1877 connection = hfp_create_connection(bd_addr, local_role); 1878 if (!connection){ 1879 return BTSTACK_MEMORY_ALLOC_FAILED; 1880 } 1881 1882 connection->state = HFP_W2_SEND_SDP_QUERY; 1883 1884 bd_addr_copy(connection->remote_addr, bd_addr); 1885 connection->service_uuid = service_uuid; 1886 1887 hfp_sdp_query_request.callback = &hfp_handle_start_sdp_client_query; 1888 // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback 1889 (void) sdp_client_register_query_callback(&hfp_sdp_query_request); 1890 return ERROR_CODE_SUCCESS; 1891 } 1892 1893 void hfp_trigger_release_service_level_connection(hfp_connection_t * hfp_connection){ 1894 // called internally, NULL check already performed 1895 btstack_assert(hfp_connection != NULL); 1896 1897 hfp_trigger_release_audio_connection(hfp_connection); 1898 if (hfp_connection->state < HFP_W4_RFCOMM_CONNECTED){ 1899 hfp_connection->state = HFP_IDLE; 1900 return; 1901 } 1902 1903 if (hfp_connection->state == HFP_W4_RFCOMM_CONNECTED){ 1904 hfp_connection->state = HFP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN; 1905 return; 1906 } 1907 hfp_connection->release_slc_connection = 1; 1908 if (hfp_connection->state < HFP_W4_SCO_CONNECTED){ 1909 hfp_connection->state = HFP_W2_DISCONNECT_RFCOMM; 1910 return; 1911 } 1912 1913 if (hfp_connection->state < HFP_W4_SCO_DISCONNECTED){ 1914 hfp_connection->state = HFP_W2_DISCONNECT_SCO; 1915 hfp_connection->release_audio_connection = 1; 1916 return; 1917 } 1918 } 1919 1920 uint8_t hfp_trigger_release_audio_connection(hfp_connection_t * hfp_connection){ 1921 // called internally, NULL check already performed 1922 btstack_assert(hfp_connection != NULL); 1923 if (hfp_connection->state <= HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED){ 1924 return ERROR_CODE_COMMAND_DISALLOWED; 1925 } 1926 switch (hfp_connection->state) { 1927 case HFP_W2_CONNECT_SCO: 1928 hfp_connection->state = HFP_SERVICE_LEVEL_CONNECTION_ESTABLISHED; 1929 break; 1930 case HFP_W4_SCO_CONNECTED: 1931 case HFP_AUDIO_CONNECTION_ESTABLISHED: 1932 hfp_connection->release_audio_connection = 1; 1933 break; 1934 default: 1935 return ERROR_CODE_COMMAND_DISALLOWED; 1936 } 1937 return ERROR_CODE_SUCCESS; 1938 } 1939 1940 bool hfp_sco_setup_active(void){ 1941 return hfp_sco_establishment_active != NULL; 1942 } 1943 1944 void hfp_setup_synchronous_connection(hfp_connection_t * hfp_connection){ 1945 1946 hfp_sco_establishment_active = hfp_connection; 1947 1948 // all packet types, fixed bandwidth 1949 int setting = hfp_connection->link_setting; 1950 log_info("hfp_setup_synchronous_connection using setting nr %u", setting); 1951 uint16_t sco_voice_setting = hci_get_sco_voice_setting(); 1952 if (hfp_connection->negotiated_codec != HFP_CODEC_CVSD){ 1953 #ifdef ENABLE_BCM_PCM_WBS 1954 sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers 1955 #else 1956 sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise 1957 #endif 1958 } 1959 uint16_t packet_types = hfp_link_settings[setting].packet_types; 1960 hfp_connection->packet_types = packet_types; 1961 1962 // get packet types - bits 6-9 are 'don't allow' 1963 uint16_t packet_types_flipped = packet_types ^ 0x03c0; 1964 #if defined(ENABLE_SCO_OVER_PCM) && defined(ENABLE_NXP_PCM_WBS) 1965 uint8_t radio_coding_format = 3; 1966 uint32_t host_bandwidth = 0; 1967 uint8_t coded_data_size = 0; 1968 switch (hfp_connection->negotiated_codec){ 1969 case HFP_CODEC_CVSD: 1970 radio_coding_format = 0x02; 1971 host_bandwidth = 16000; 1972 coded_data_size = 0x10; 1973 break; 1974 case HFP_CODEC_MSBC: 1975 radio_coding_format = 0x05; 1976 host_bandwidth = 32000; 1977 coded_data_size = 0x08; 1978 break; 1979 default: 1980 log_error("Coding format %u not supported by Controller", hfp_connection->negotiated_codec); 1981 btstack_assert(false); 1982 break; 1983 } 1984 hci_send_cmd(&hci_enhanced_setup_synchronous_connection, 1985 // ACL Handle 1986 hfp_connection->acl_handle, 1987 // Transmit_Bandwidth 1988 8000, 1989 // Receive_Bandwidth 1990 8000, 1991 // Transmit_Coding_Format: radio_config_format, company, codec 1992 radio_coding_format, 0x00, 0x00, 1993 // Receive_Coding_Format: radio_config_format, company, codec 1994 radio_coding_format, 0x00, 0x00, 1995 // Transmit_Codec_Frame_Size 1996 0x3c, 1997 // Receive_Codec_Frame_Size 1998 0x3c, 1999 // Input_Bandwidth 2000 host_bandwidth, 2001 // Output_Bandwidth 2002 host_bandwidth, 2003 // Input_Coding_Format, 0x04 = Linear PCM, company, codec 2004 0x04, 0x00, 0x00, 2005 // Output_Coding_Format, 0x04 = Linear PCM, company, codec 2006 0x04, 0x00, 0x00, 2007 // Input_Coded_Data_Size 2008 coded_data_size, 2009 // Output_Coded_Data_Size 2010 coded_data_size, 2011 // Input_PCM_Data_Format, 0x02 = 2’s complement 2012 0x02, 2013 // Output_PCM_Data_Format, 0x02 = 2’s complement 2014 0x02, 2015 // Input_PCM_Sample_Payload_MSB_Position 2016 0x00, 2017 // Output_PCM_Sample_Payload_MSB_Position 2018 0x00, 2019 // Input_Data_Path - vendor specific: NXP - I2S/PCM 2020 0x01, 2021 // Output_Data_Path - vendor specific: NXP - I2S/PCM 2022 0x01, 2023 // Input_Transport_Unit_Size 2024 0x10, 2025 // Output_Transport_Unit_Size 2026 0x10, 2027 // 2028 hfp_link_settings[setting].max_latency, 2029 packet_types_flipped, 2030 hfp_link_settings[setting].retransmission_effort); 2031 #else 2032 hci_send_cmd(&hci_setup_synchronous_connection, hfp_connection->acl_handle, 8000, 8000, hfp_link_settings[setting].max_latency, 2033 sco_voice_setting, hfp_link_settings[setting].retransmission_effort, packet_types_flipped); 2034 #endif 2035 } 2036 2037 #ifdef ENABLE_HFP_HF_SAFE_SETTINGS 2038 hfp_link_settings_t hfp_safe_settings_for_context(bool use_eSCO, uint8_t negotiated_codec, bool secure_connection_in_use){ 2039 uint8_t i; 2040 hfp_link_settings_t link_setting = HFP_LINK_SETTINGS_NONE; 2041 for (i=0 ; i < (sizeof(hfp_mandatory_safe_settings) / sizeof(struct hfp_mandatory_safe_setting)) ; i++){ 2042 uint16_t packet_types = hfp_link_settings[(uint8_t)(hfp_mandatory_safe_settings[i].link_setting)].packet_types; 2043 bool is_eSCO_setting = (packet_types & SCO_PACKET_TYPES_ESCO) != 0; 2044 if (is_eSCO_setting != use_eSCO) continue; 2045 if ((hfp_mandatory_safe_settings[i].codec_mask & (1 << negotiated_codec)) == 0) continue; 2046 if (hfp_mandatory_safe_settings[i].secure_connection_in_use != secure_connection_in_use) continue; 2047 link_setting = hfp_mandatory_safe_settings[i].link_setting; 2048 break; 2049 } 2050 return link_setting; 2051 } 2052 #endif 2053 2054 void hfp_accept_synchronous_connection(hfp_connection_t * hfp_connection, bool use_eSCO){ 2055 2056 hfp_sco_establishment_active = hfp_connection; 2057 2058 // lookup safe settings based on SCO type, SC use and Codec type 2059 uint16_t max_latency; 2060 uint16_t packet_types; 2061 uint16_t retransmission_effort; 2062 2063 #ifdef ENABLE_HFP_HF_SAFE_SETTINGS 2064 hfp_link_settings_t link_setting = HFP_LINK_SETTINGS_NONE; 2065 // fallback for non-CVSD codec and SCO connection 2066 if ((hfp_connection->negotiated_codec != HFP_CODEC_CVSD) && (use_eSCO == false)){ 2067 max_latency = 0xffff; 2068 retransmission_effort = 0xff; 2069 packet_types = SCO_PACKET_TYPES_HV3 | SCO_PACKET_TYPES_HV1; 2070 } else { 2071 // use safe settings from HFP v1.9, table 6.10 2072 bool secure_connection_in_use = gap_secure_connection(hfp_connection->acl_handle); 2073 link_setting = hfp_safe_settings_for_context(use_eSCO, hfp_connection->negotiated_codec, secure_connection_in_use); 2074 max_latency = hfp_link_settings[(uint8_t) link_setting].max_latency; 2075 retransmission_effort = hfp_link_settings[(uint8_t) link_setting].retransmission_effort; 2076 packet_types = hfp_link_settings[(uint8_t) link_setting].packet_types; 2077 } 2078 #else 2079 max_latency = 0xffff; 2080 retransmission_effort = 0xff; 2081 if (use_eSCO) { 2082 packet_types = SCO_PACKET_TYPES_EV3 | SCO_PACKET_TYPES_2EV3; 2083 } else { 2084 packet_types = SCO_PACKET_TYPES_HV3 | SCO_PACKET_TYPES_HV1; 2085 } 2086 #endif 2087 2088 // transparent data for non-CVSD connections or if codec provided by Controller 2089 uint16_t sco_voice_setting = hci_get_sco_voice_setting(); 2090 if (hfp_connection->negotiated_codec != HFP_CODEC_CVSD){ 2091 #ifdef ENABLE_BCM_PCM_WBS 2092 sco_voice_setting = 0x0063; // Transparent data, 16-bit for BCM controllers 2093 #else 2094 sco_voice_setting = 0x0043; // Transparent data, 8-bit otherwise 2095 #endif 2096 } 2097 2098 // filter packet types 2099 packet_types &= hfp_get_sco_packet_types(); 2100 2101 hfp_connection->packet_types = packet_types; 2102 2103 // bits 6-9 are 'don't allow' 2104 uint16_t packet_types_flipped = packet_types ^ 0x3c0; 2105 2106 log_info("Sending hci_accept_connection_request: packet types 0x%04x, sco_voice_setting 0x%02x", 2107 packet_types, sco_voice_setting); 2108 2109 #if defined(ENABLE_SCO_OVER_PCM) && defined(ENABLE_NXP_PCM_WBS) 2110 uint8_t radio_coding_format = 3; 2111 uint32_t host_bandwidth = 0; 2112 uint8_t coded_data_size = 0; 2113 switch (hfp_connection->negotiated_codec){ 2114 case HFP_CODEC_CVSD: 2115 radio_coding_format = 0x02; 2116 host_bandwidth = 16000; 2117 coded_data_size = 0x10; 2118 break; 2119 case HFP_CODEC_MSBC: 2120 radio_coding_format = 0x05; 2121 host_bandwidth = 32000; 2122 coded_data_size = 0x08; 2123 break; 2124 default: 2125 log_error("Coding format %u not supported by Controller", hfp_connection->negotiated_codec); 2126 btstack_assert(false); 2127 break; 2128 } 2129 hci_send_cmd(&hci_enhanced_accept_synchronous_connection, 2130 // BD_ADDR 2131 hfp_connection->remote_addr, 2132 // Transmit_Bandwidth 2133 8000, 2134 // Receive_Bandwidth 2135 8000, 2136 // Transmit_Coding_Format: radio_config_format, company, codec 2137 radio_coding_format, 0x00, 0x00, 2138 // Receive_Coding_Format: radio_config_format, company, codec 2139 radio_coding_format, 0x00, 0x00, 2140 // Transmit_Codec_Frame_Size 2141 0x3c, 2142 // Receive_Codec_Frame_Size 2143 0x3c, 2144 // Input_Bandwidth 2145 host_bandwidth, 2146 // Output_Bandwidth 2147 host_bandwidth, 2148 // Input_Coding_Format, 0x04 = Linear PCM, company, codec 2149 0x04, 0x00, 0x00, 2150 // Output_Coding_Format, 0x04 = Linear PCM, company, codec 2151 0x04, 0x00, 0x00, 2152 // Input_Coded_Data_Size 2153 coded_data_size, 2154 // Output_Coded_Data_Size 2155 coded_data_size, 2156 // Input_PCM_Data_Format, 0x02 = 2’s complement 2157 0x02, 2158 // Output_PCM_Data_Format, 0x02 = 2’s complement 2159 0x02, 2160 // Input_PCM_Sample_Payload_MSB_Position 2161 0x00, 2162 // Output_PCM_Sample_Payload_MSB_Position 2163 0x00, 2164 // Input_Data_Path - vendor specific: NXP - I2S/PCM 2165 0x01, 2166 // Output_Data_Path - vendor specific: NXP - I2S/PCM 2167 0x01, 2168 // Input_Transport_Unit_Size 2169 0x10, 2170 // Output_Transport_Unit_Size 2171 0x10, 2172 // 2173 max_latency, 2174 packet_types_flipped, 2175 retransmission_effort); 2176 #else 2177 hci_send_cmd(&hci_accept_synchronous_connection, hfp_connection->remote_addr, 8000, 8000, max_latency, 2178 sco_voice_setting, retransmission_effort, packet_types_flipped); 2179 #endif 2180 } 2181 2182 #ifdef ENABLE_CC256X_ASSISTED_HFP 2183 void hfp_cc256x_write_codec_config(hfp_connection_t * hfp_connection){ 2184 uint32_t sample_rate_hz; 2185 uint16_t clock_rate_khz; 2186 if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){ 2187 clock_rate_khz = 512; 2188 sample_rate_hz = 16000; 2189 } else { 2190 clock_rate_khz = 256; 2191 sample_rate_hz = 8000; 2192 } 2193 uint8_t clock_direction = 0; // master 2194 uint16_t frame_sync_duty_cycle = 0; // i2s with 50% 2195 uint8_t frame_sync_edge = 1; // rising edge 2196 uint8_t frame_sync_polarity = 0; // active high 2197 uint8_t reserved = 0; 2198 uint16_t size = 16; 2199 uint16_t chan_1_offset = 1; 2200 uint16_t chan_2_offset = chan_1_offset + size; 2201 uint8_t out_edge = 1; // rising 2202 uint8_t in_edge = 0; // falling 2203 hci_send_cmd(&hci_ti_write_codec_config, clock_rate_khz, clock_direction, sample_rate_hz, frame_sync_duty_cycle, 2204 frame_sync_edge, frame_sync_polarity, reserved, 2205 size, chan_1_offset, out_edge, size, chan_1_offset, in_edge, reserved, 2206 size, chan_2_offset, out_edge, size, chan_2_offset, in_edge, reserved); 2207 } 2208 #endif 2209 2210 #ifdef ENABLE_BCM_PCM_WBS 2211 void hfp_bcm_write_i2spcm_interface_param(hfp_connection_t * hfp_connection){ 2212 uint8_t sample_rate = (hfp_connection->negotiated_codec == HFP_CODEC_MSBC) ? 1 : 0; 2213 // i2s enable, master, 8/16 kHz, 512 kHz 2214 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, sample_rate, 2); 2215 } 2216 #endif 2217 2218 void hfp_prepare_for_sco(hfp_connection_t * hfp_connection){ 2219 #ifdef ENABLE_CC256X_ASSISTED_HFP 2220 hfp_connection->cc256x_send_write_codec_config = true; 2221 if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){ 2222 hfp_connection->cc256x_send_wbs_associate = true; 2223 } 2224 #endif 2225 2226 #ifdef ENABLE_BCM_PCM_WBS 2227 #ifndef HAVE_BCM_PCM_NBS_16KHZ 2228 hfp_connection->bcm_send_write_i2spcm_interface_param = true; 2229 #endif 2230 if (hfp_connection->negotiated_codec == HFP_CODEC_MSBC){ 2231 hfp_connection->bcm_send_enable_wbs = true; 2232 } 2233 #endif 2234 2235 #ifdef ENABLE_RTK_PCM_WBS 2236 hfp_connection->rtk_send_sco_config = true; 2237 #endif 2238 } 2239 2240 void hfp_set_hf_callback(btstack_packet_handler_t callback){ 2241 hfp_hf_callback = callback; 2242 } 2243 2244 void hfp_set_ag_callback(btstack_packet_handler_t callback){ 2245 hfp_ag_callback = callback; 2246 } 2247 2248 void hfp_set_ag_rfcomm_packet_handler(btstack_packet_handler_t handler){ 2249 hfp_ag_rfcomm_packet_handler = handler; 2250 } 2251 2252 void hfp_set_hf_rfcomm_packet_handler(btstack_packet_handler_t handler){ 2253 hfp_hf_rfcomm_packet_handler = handler; 2254 } 2255 2256 void hfp_init(void){ 2257 hfp_allowed_sco_packet_types = SCO_PACKET_TYPES_ALL; 2258 } 2259 2260 void hfp_deinit(void){ 2261 hfp_allowed_sco_packet_types = 0; 2262 hfp_connections = NULL; 2263 hfp_hf_callback = NULL; 2264 hfp_ag_callback = NULL; 2265 hfp_hf_rfcomm_packet_handler = NULL; 2266 hfp_ag_rfcomm_packet_handler = NULL; 2267 hfp_sco_establishment_active = NULL; 2268 hfp_custom_commands_ag = NULL; 2269 hfp_custom_commands_hf = NULL; 2270 (void) memset(&hfp_sdp_query_context, 0, sizeof(hfp_sdp_query_context_t)); 2271 (void) memset(&hfp_sdp_query_request, 0, sizeof(btstack_context_callback_registration_t)); 2272 } 2273 2274 void hfp_set_sco_packet_types(uint16_t packet_types){ 2275 hfp_allowed_sco_packet_types = packet_types; 2276 } 2277 2278 uint16_t hfp_get_sco_packet_types(void){ 2279 return hfp_allowed_sco_packet_types; 2280 } 2281 2282 hfp_link_settings_t hfp_next_link_setting(hfp_link_settings_t current_setting, uint16_t local_sco_packet_types, 2283 uint16_t remote_sco_packet_types, bool eSCO_S4_supported, 2284 uint8_t negotiated_codec) { 2285 int8_t setting = (int8_t) current_setting; 2286 while (setting > 0){ 2287 setting--; 2288 // skip S4 if not supported 2289 if ((setting == (int8_t) HFP_LINK_SETTINGS_S4) && !eSCO_S4_supported) continue; 2290 // skip wrong codec 2291 if ((hfp_link_settings[setting].codec_mask & (1 << negotiated_codec)) == 0) continue; 2292 // skip disabled or not supported packet types 2293 uint16_t required_packet_types = hfp_link_settings[setting].packet_types; 2294 uint16_t allowed_packet_types = hfp_allowed_sco_packet_types & local_sco_packet_types & remote_sco_packet_types; 2295 if ((required_packet_types & allowed_packet_types) == 0) continue; 2296 2297 // found matching setting 2298 return (hfp_link_settings_t) setting; 2299 } 2300 return HFP_LINK_SETTINGS_NONE; 2301 } 2302 2303 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){ 2304 uint8_t negotiated_codec = hfp_connection->negotiated_codec; 2305 uint16_t local_sco_packet_types = hci_usable_sco_packet_types(); 2306 uint16_t remote_sco_packet_types = hci_remote_sco_packet_types(hfp_connection->acl_handle); 2307 return hfp_next_link_setting(current_setting, local_sco_packet_types, remote_sco_packet_types, eSCO_S4_supported, 2308 negotiated_codec); 2309 } 2310 2311 void hfp_init_link_settings(hfp_connection_t * hfp_connection, uint8_t eSCO_S4_supported){ 2312 // get highest possible link setting 2313 hfp_connection->link_setting = hfp_next_link_setting_for_connection(HFP_LINK_SETTINGS_NONE, hfp_connection, eSCO_S4_supported); 2314 log_info("hfp_init_link_settings: %u", hfp_connection->link_setting); 2315 } 2316 2317 #define HFP_HF_RX_DEBUG_PRINT_LINE 80 2318 2319 void hfp_log_rfcomm_message(const char * tag, uint8_t * packet, uint16_t size){ 2320 #ifdef ENABLE_LOG_INFO 2321 // encode \n\r 2322 char printable[HFP_HF_RX_DEBUG_PRINT_LINE+2]; 2323 int i = 0; 2324 int pos; 2325 for (pos=0 ; (pos < size) && (i < (HFP_HF_RX_DEBUG_PRINT_LINE - 3)) ; pos++){ 2326 switch (packet[pos]){ 2327 case '\n': 2328 printable[i++] = '\\'; 2329 printable[i++] = 'n'; 2330 break; 2331 case '\r': 2332 printable[i++] = '\\'; 2333 printable[i++] = 'r'; 2334 break; 2335 default: 2336 printable[i++] = packet[pos]; 2337 break; 2338 } 2339 } 2340 printable[i] = 0; 2341 log_info("%s: '%s'", tag, printable); 2342 #endif 2343 } 2344 2345 void hfp_register_custom_ag_command(hfp_custom_at_command_t * custom_at_command){ 2346 btstack_linked_list_add(&hfp_custom_commands_ag, (btstack_linked_item_t *) custom_at_command); 2347 } 2348 2349 void hfp_register_custom_hf_command(hfp_custom_at_command_t * custom_at_command){ 2350 btstack_linked_list_add(&hfp_custom_commands_hf, (btstack_linked_item_t *) custom_at_command); 2351 } 2352 2353 // HFP H2 Synchronization - might get moved into a hfp_h2.c 2354 2355 // find position of h2 sync header, returns -1 if not found, or h2 sync position 2356 static int16_t hfp_h2_sync_find(const uint8_t * frame_data, uint16_t frame_len){ 2357 uint16_t i; 2358 for (i=0;i<(frame_len - 1);i++){ 2359 // check: first byte == 1 2360 uint8_t h2_first_byte = frame_data[i]; 2361 if (h2_first_byte == 0x01) { 2362 uint8_t h2_second_byte = frame_data[i + 1]; 2363 // check lower nibble of second byte == 0x08 2364 if ((h2_second_byte & 0x0F) == 8) { 2365 // check if bits 0+2 == bits 1+3 2366 uint8_t hn = h2_second_byte >> 4; 2367 if (((hn >> 1) & 0x05) == (hn & 0x05)) { 2368 return (int16_t) i; 2369 } 2370 } 2371 } 2372 } 2373 return -1; 2374 } 2375 2376 static void hfp_h2_sync_reset(hfp_h2_sync_t * hfp_h2_sync){ 2377 hfp_h2_sync->frame_len = 0; 2378 } 2379 2380 void hfp_h2_sync_init(hfp_h2_sync_t * hfp_h2_sync, 2381 bool (*callback)(bool bad_frame, const uint8_t * frame_data, uint16_t frame_len)){ 2382 hfp_h2_sync->callback = callback; 2383 hfp_h2_sync->dropped_bytes = 0; 2384 hfp_h2_sync_reset(hfp_h2_sync); 2385 } 2386 2387 static void hfp_h2_report_bad_frames(hfp_h2_sync_t *hfp_h2_sync){ 2388 // report bad frames 2389 while (hfp_h2_sync->dropped_bytes >= HFP_H2_SYNC_FRAME_SIZE){ 2390 hfp_h2_sync->dropped_bytes -= HFP_H2_SYNC_FRAME_SIZE; 2391 (void)(*hfp_h2_sync->callback)(true,NULL, HFP_H2_SYNC_FRAME_SIZE); 2392 } 2393 } 2394 2395 static void hfp_h2_sync_drop_bytes(hfp_h2_sync_t * hfp_h2_sync, uint16_t bytes_to_drop){ 2396 btstack_assert(bytes_to_drop <= hfp_h2_sync->frame_len); 2397 memmove(hfp_h2_sync->frame_data, &hfp_h2_sync->frame_data[bytes_to_drop], hfp_h2_sync->frame_len - bytes_to_drop); 2398 hfp_h2_sync->dropped_bytes += bytes_to_drop; 2399 hfp_h2_sync->frame_len -= bytes_to_drop; 2400 hfp_h2_report_bad_frames(hfp_h2_sync); 2401 } 2402 2403 void hfp_h2_sync_process(hfp_h2_sync_t *hfp_h2_sync, bool bad_frame, const uint8_t *frame_data, uint16_t frame_len) { 2404 2405 if (bad_frame){ 2406 // drop all data 2407 hfp_h2_sync->dropped_bytes += hfp_h2_sync->frame_len; 2408 hfp_h2_sync->frame_len = 0; 2409 // all new data is bad, too 2410 hfp_h2_sync->dropped_bytes += frame_len; 2411 // report frames 2412 hfp_h2_report_bad_frames(hfp_h2_sync); 2413 return; 2414 } 2415 2416 while (frame_len > 0){ 2417 // Fill hfp_h2_sync->frame_buffer 2418 uint16_t bytes_free_in_frame_buffer = HFP_H2_SYNC_FRAME_SIZE - hfp_h2_sync->frame_len; 2419 uint16_t bytes_to_append = btstack_min(frame_len, bytes_free_in_frame_buffer); 2420 memcpy(&hfp_h2_sync->frame_data[hfp_h2_sync->frame_len], frame_data, bytes_to_append); 2421 frame_data += bytes_to_append; 2422 frame_len -= bytes_to_append; 2423 hfp_h2_sync->frame_len += bytes_to_append; 2424 // check complete frame for h2 sync 2425 if (hfp_h2_sync->frame_len == HFP_H2_SYNC_FRAME_SIZE){ 2426 bool valid_frame = true; 2427 int16_t h2_pos = hfp_h2_sync_find(hfp_h2_sync->frame_data, hfp_h2_sync->frame_len); 2428 if (h2_pos < 0){ 2429 // no h2 sync, no valid frame, keep last byte if it is 0x01 2430 if (hfp_h2_sync->frame_data[HFP_H2_SYNC_FRAME_SIZE-1] == 0x01){ 2431 hfp_h2_sync_drop_bytes(hfp_h2_sync, HFP_H2_SYNC_FRAME_SIZE - 1); 2432 } else { 2433 hfp_h2_sync_drop_bytes(hfp_h2_sync, HFP_H2_SYNC_FRAME_SIZE); 2434 } 2435 valid_frame = false; 2436 } 2437 else if (h2_pos > 0){ 2438 // drop data before h2 sync 2439 hfp_h2_sync_drop_bytes(hfp_h2_sync, h2_pos); 2440 valid_frame = false; 2441 } 2442 if (valid_frame) { 2443 // h2 sync at pos 0 and complete frame 2444 bool codec_ok = (*hfp_h2_sync->callback)(false, hfp_h2_sync->frame_data, hfp_h2_sync->frame_len); 2445 if (codec_ok){ 2446 hfp_h2_sync_reset(hfp_h2_sync); 2447 } else { 2448 // drop first two bytes 2449 hfp_h2_sync_drop_bytes(hfp_h2_sync, 2); 2450 } 2451 } 2452 } 2453 } 2454 } 2455